Files
raspi/playbooks/append_to_cmdline_txt.md
2024-11-06 18:21:40 +00:00

2.8 KiB

To create an Ansible playbook that appends the specified kernel parameters (rootwait cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory) to the /boot/firmware/cmdline.txt file only if they are not already present, you can use the lineinfile Ansible module.

Here's how the playbook can be written:

Ansible Playbook (append_cmdline.yml):

---
- name: Ensure required parameters are in /boot/firmware/cmdline.txt
  hosts: raspberry_pi
  become: yes
  tasks:
    - name: Append kernel parameters to cmdline.txt if not present
      lineinfile:
        path: /boot/firmware/cmdline.txt
        line: "rootwait cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory"
        insertafter: EOF
        state: present
        create: yes
        backup: yes  # This creates a backup of the file before making changes
      notify:
        - Reboot system

  handlers:
    - name: Reboot system
      reboot:
        msg: "Rebooting system to apply new kernel parameters"
        reboot_timeout: 600
        test_command: uptime

Explanation of the Playbook:

  • hosts: raspberry_pi: Targets the Raspberry Pi group from your inventory.
  • become: yes: Ensures that the task runs with elevated privileges (sudo), which is necessary for modifying system files like /boot/firmware/cmdline.txt.

Task:

  • lineinfile module:
    • path: /boot/firmware/cmdline.txt: This specifies the file to modify.
    • line: This is the exact string to ensure is present in the file.
    • insertafter: EOF: This ensures the line is appended at the end of the file if it is not already there.
    • state: present: Ensures that the specified line exists in the file.
    • create: yes: If the file doesn't exist, it will be created (though it's unlikely in this case because /boot/firmware/cmdline.txt should exist on a Raspberry Pi).
    • backup: yes: This creates a backup of the file before modifying it (important for safety).

Handler:

  • Reboot system handler:
    • This handler is triggered if the task changes the file (i.e., if it appends the line).
    • It will reboot the Raspberry Pi to apply the changes, which often requires a reboot to take effect.
    • reboot_timeout: 600 specifies that the playbook will wait up to 600 seconds for the system to reboot successfully.
    • test_command: uptime ensures that the system is back up and running after the reboot.

To run the playbook:

  1. Save the playbook to a file, e.g., append_cmdline.yml.

  2. Run the playbook with the following command:

    ansible-playbook -i inventory.ini append_cmdline.yml
    

This will ensure the specified parameters are added to /boot/firmware/cmdline.txt only if they are not already present and reboot the system if necessary. If you have any more questions or need further adjustments, feel free to ask!