繁体   English   中英

是否有更好的方法使用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剧本遍历节点计算机上的多个文件并搜索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剧本的格式如下:


- 
 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 }}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM