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.
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
According to the module doc https://docs.ansible.com/ansible/latest/modules/command_module.html :
If you want to run a command through the shell (say you are using <, >, |, etc), you actually want the shell module instead. Parsing shell metacharacters can lead to unexpected commands being executed if quoting is not done correctly so it is more secure to use the command module when possible.
Anyway, I think you don't want this line to be added to your file on every run of this playbook, use lineinfile instead to ensure that this line exists:
- shell: blkid -s UUID -o value {{ ebs_swap }})
register: blkid_out
- lineinfile:
path: /etc/fstab
regexp: "^UUID={{ blkid_out.stdout }}"
line: "UUID={{ blkid_out.stdout }} swap swap defaults 0 0"
Now the line will be added only when it doesn't exist
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.