linuxbashansibleswapfstab

How to append entries in `/etc/fstab` of disks using Ansible-playbook?


I am using below playbook to write entries to /etc/fstab. And to create swap file:

---

- name: Configure SWAP
  hosts: localhost
  become: yes
  become_user: root

  tasks:
    - name: Configuring a SWAP
      command: "{{ item }}"
      loop:
        - mkswap -f "{{ ebs_swap }}"
        - echo "UUID=$(blkid -s UUID -o value {{ ebs_swap }})   swap    swap   defaults  0   0" | sudo tee -a /etc/fstab
        - swapon -a
      register: output

    - name: Display the variable
      debug:
       msg: "{{ output}}"

We are running it with command: ansible-playbook mount.yml -e "ebs_swap=/dev/xvdj"

O/P:

                "item": "echo \"UUID=$(blkid -s UUID -o value /dev/xvdj)   swap    swap   defaults  0   0\" | sudo tee -a /etc/fstab",
                "rc": 0,
                "start": "2020-04-09 14:51:23.890047",
                "stderr": "",
                "stderr_lines": [],
                "stdout": "UUID=$(blkid -s UUID -o value /dev/xvdj)   swap    swap   defaults  0   0 | sudo tee -a /etc/fstab",
                "stdout_lines": [
                    "UUID=$(blkid -s UUID -o value /dev/xvdj)   swap    swap   defaults  0   0 | sudo tee -a /etc/fstab"

Can any one tell me why am I unable to get the entry in /etc/fstab & when I am trying to run above commands its getting success.


Solution

  • I have resolved it by using below:

    - name: Dispaly uuid & store in variable
      command: blkid -s UUID -o value {{ ebs_swap }}
      register: uuid_swap
    
    - name: Add the below lines
      blockinfile:
        path: /etc/fstab
        state: present
        block: |
          UUID={{ uuid_swap.stdout }}   swap      swap defaults                         0   0