[英]How to append entries in `/etc/fstab` of disks using Ansible-playbook?
我正在使用下面的剧本将条目写入/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"
输出/输出:
"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
中获取条目,当我尝试在命令上方运行时,它会成功。
我已经通过使用以下解决了它:
- 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
根据模块文档https://docs.ansible.com/ansible/latest/modules/command_module.html :
如果您想通过 shell 运行命令(假设您正在使用 <、>、| 等),您实际上需要 shell 模块。 如果引用不正确,解析 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"
现在只有当它不存在时才会添加该行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.