如何使用 Ansible 将大量文本附加到文件?
How do I append a large amount of text to a file using Ansible?
我们的应用程序在 /etc/services
中创建了很多定义。我们将所有这些定义放在手边的 services
文件中,这样我们就可以像这样将它们通过管道传输到 /etc/services
中:
cp /etc/services /etc/services.stock
cat /path/to/build/services >> /etc/services
它有效,但它不是幂等的,即 运行重复执行这些命令将导致服务文件再次附加信息。
当我研究我们的 Ansible 剧本时,我正在努力弄清楚如何做到这一点。我可以这样:
- command: "cat /path/to/build/services >> /etc/services"
但我不希望它每次 运行 剧本时都 运行。
另一个选择是做这样的事情:
- name: add services
lineinfile:
state: present
insertafter: EOF
dest: /etc/services
line: "{{ item }}"
with_items:
- line 1
- line 2
- line 3
- line 4
- ...
但这真的很慢,因为它会单独处理每一行。
有没有更好的方法?模板没有帮助,因为它们会完全覆盖服务文件,这似乎有点粗鲁。
blockinfile
是一个本机的幂等模块,用于确保文件中存在(不存在)一组指定的行。
示例:
- name: add services
blockinfile:
state: present
insertafter: EOF
dest: /etc/services
marker: "<!-- add services ANSIBLE MANAGED BLOCK -->"
content: |
line 1
line 2
line 3
我们的应用程序在 /etc/services
中创建了很多定义。我们将所有这些定义放在手边的 services
文件中,这样我们就可以像这样将它们通过管道传输到 /etc/services
中:
cp /etc/services /etc/services.stock
cat /path/to/build/services >> /etc/services
它有效,但它不是幂等的,即 运行重复执行这些命令将导致服务文件再次附加信息。
当我研究我们的 Ansible 剧本时,我正在努力弄清楚如何做到这一点。我可以这样:
- command: "cat /path/to/build/services >> /etc/services"
但我不希望它每次 运行 剧本时都 运行。
另一个选择是做这样的事情:
- name: add services
lineinfile:
state: present
insertafter: EOF
dest: /etc/services
line: "{{ item }}"
with_items:
- line 1
- line 2
- line 3
- line 4
- ...
但这真的很慢,因为它会单独处理每一行。
有没有更好的方法?模板没有帮助,因为它们会完全覆盖服务文件,这似乎有点粗鲁。
blockinfile
是一个本机的幂等模块,用于确保文件中存在(不存在)一组指定的行。
示例:
- name: add services
blockinfile:
state: present
insertafter: EOF
dest: /etc/services
marker: "<!-- add services ANSIBLE MANAGED BLOCK -->"
content: |
line 1
line 2
line 3