[英]Is there a better way to iterate through multiple files on the node machine using Ansible playbook and search n replace a particular line
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替换特定行。
I have the following files in my directory and it needs to iterate through these files and check and replace a particular line in the file. 我的目录中有以下文件,它需要遍历这些文件并检查并替换文件中的特定行。
/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
My Ansible Playbook can be formatted as follows: 我的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
This will actually work and help me. 这实际上会工作并为我提供帮助。 I could also create a vars.yaml file and add all these files and use them in "with_items" syntax.
我还可以创建一个vars.yaml文件并添加所有这些文件,并以“ with_items”语法使用它们。 However this is actually making the playbook look to lengthy as the number of files to search are higher
但是,实际上这会使剧本显得冗长,因为要搜索的文件数量更多
We possibly can achieve the same thing effectively by using the jinja2 template using the "for" loop. 通过使用“ for”循环的jinja2模板,我们可能可以有效地实现相同的目的。 EX: {% for item in vars.yml %}
例如:{%为vars.yml中的项目%}
and that would rather be an effective way to do it and wont make my Ansible playbook clumsy but I'm unable to figure the exact command for looping it. 那将是一种有效的方法,并且不会使Ansible剧本变得笨拙,但是我无法弄清楚用于循环播放它的确切命令。
Is there a jinja command to achieve the same or a better way to iterate through multiple files and not writing each of them into the playbook. 是否有jinja命令来实现相同或更好的方法来遍历多个文件,而不是将每个文件都写入到剧本中。
Thank you 谢谢
You don't need jinja2 for that. 您不需要jinja2。 Why don't you use a separate file for the file list variable like
vars.yml
with the following contents: 为什么不为文件列表变量(如
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
and include this file in your playbook: 并将此文件包含在您的剧本中:
---
- 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.