有没有更好的方法使用 Ansible 剧本遍历节点机器上的多个文件并搜索 n 替换特定行

Is there a better way to iterate through multiple files on the node machine using Ansible playbook and search n replace a particular line

有没有更好的方法使用 Ansible playbook 遍历节点机器上的多个文件并搜索 n 替换特定行。

我的目录中有以下文件,它需要遍历这些文件并检查并替换文件中的特定行。

/opt/a1.conf
/opt/a2.con.f
/var/app1/conf/a3.conf
/etc/a5.conf
/etc/a6.conf
/etc/a7.conf
/etc/a8.conf
/etc/a9.conf

我的 Ansible Playbook 可以格式化如下:


- 
 name: Install nginx and other binaries using with_item and variables.
 gather_facts: yes
 hosts: aws1
 become_method: sudo
 become: yes
 tasks:
- name: Modify line to include Timeout
  become: yes
  become_method: sudo
    lineinfile:
    path: {{ item }}
    regexp: 'http\s+Timeout\s+\='
    line: 'http Timeout = 10'
    backup: yes
   with-items
     - /opt/a1.conf
     - /opt/a2.con.f
     - /var/app1/conf/a3.conf
     - /etc/a5.conf
     - /etc/a6.conf
     - /etc/a7.conf
     - /etc/a8.conf
     - /etc/a9.conf

这确实有效并且对我有帮助。我还可以创建一个 vars.yaml 文件并添加所有这些文件并在 "with_items" 语法中使用它们。 然而,这实际上使剧本看起来很长,因为要搜索的文件数量更多

我们可能可以通过使用 "for" 循环使用 jinja2 模板有效地实现同样的事情。 例如:{vars.yml %}

中的项目的%

这更像是一种有效的方法,不会让我的 Ansible 剧本变得笨拙,但我无法计算出循环它的确切命令。

是否有 jinja 命令可以实现相同或更好的方法来遍历多个文件而不是将每个文件都写入剧本。

谢谢

你不需要 jinja2。为什么不为文件列表变量使用单独的文件,例如 vars.yml,其内容如下:

---
files:
  - /opt/a1.conf
  - /opt/a2.con.f
  - /var/app1/conf/a3.conf
  - /etc/a5.conf
  - /etc/a6.conf
  - /etc/a7.conf
  - /etc/a8.conf
  - /etc/a9.conf

并将此文件包含在您的剧本中:

---
- name: Install nginx and other binaries using with_item and variables.
  gather_facts: yes
  hosts: aws1
  become_method: sudo
  become: yes
  vars_files:
    - z.var

  tasks:
  - name: Modify line to include Timeout
    lineinfile:
      path: {{ item }}
      regexp: 'http\s+Timeout\s+\='
      line: 'http Timeout = 10'
      backup: yes
    loop:
      "{{ files }}"