我正在使用下面的剧本将条目写入/etc/fstab
。并创建swap
文件:
---
- 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}}"
我们正在使用命令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"
谁能告诉我为什么我无法在/etc/fstab
中获得该条目,而当我试图在上述命令中运行时,它却获得了成功。
根据模块文档https://docs.ansible.com/ansible/latest/modules/command_module.html:
如果要通过外壳运行命令(例如您正在使用,|等),则实际上需要外壳模块。如果未正确执行引用,则解析shell元字符可能导致执行意外命令,因此在可能的情况下使用命令模块会更加安全。
无论如何,我不希望您在每次运行此剧本时将此行添加到文件中,请使用lineinfile来确保该行存在:
- 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"
现在仅当行不存在时才添加该行
我已经使用以下方法解决了它:
- 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