---
- block:
  - name: Install cpufrequtils
    apt:
      name: cpufrequtils
      state: present
      install_recommends: no

  - name: Set default CPU speed governor
    copy:
      dest: /etc/default/cpufrequtils
      content: "GOVERNOR=\"{{ governor_mode }}\"\n"

  # Make sure this system supports setting the scaling_governor
  # before trying to set it. (e.g. the zimbeast_vagrant environment
  # does not support setting this)
  - name: Check for scaling_governor
    stat:
      path: /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
    register: scaling_governor

  - name: Set CPU governor
    shell: "grep {{ governor_mode }} {{ item }} || echo {{ governor_mode }} > {{ item }}"
    with_sequence: start=0 end={{ansible_processor_vcpus - 1}} format=/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor
    when: scaling_governor.stat.exists
    register: cpu_freq
    changed_when: "{{ '{{ governor_mode }}' not in cpu_freq.stdout }}"
  become: yes
