如何使用Ansible将大量文本追加到文件中?

6

我们的应用程序在/etc/services中创建了很多定义。我们保留了一个包含所有这些定义的services文件,以便我们可以像这样将它们直接传输到/etc/services

cp /etc/services /etc/services.stock
cat /path/to/build/services >> /etc/services

这个命令可以正常运行,但它不具备幂等性,也就是说,重复执行此命令会导致服务文件再次附加信息。

在处理 Ansible playbook 时,我正在尝试找出如何实现幂等性。我可以这样做:

- command: "cat /path/to/build/services >> /etc/services"

但我不希望它在每次运行playbook时都运行。

另一个选项是这样做:

- name: add services
  lineinfile: 
    state: present
    insertafter: EOF
    dest: /etc/services
    line: "{{ item }}"
  with_items:
   - line 1
   - line 2
   - line 3
   - line 4
   - ...

但是这种方法非常缓慢,因为它会逐行处理每个文件。

有更好的方法吗?模板并不能帮助,因为它们会完全覆盖服务文件,这似乎有点无礼。


1
不是 Ansible 用户,但你可以这样做:1)只有当文件 /etc/services.stock 不存在时才执行 cp /etc/services /etc/services.stock。2)执行 cat /etc/services.stock /path/to/build/services >/etc/services - clstrfsck
1个回答

8

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接