简体   繁体   English

是否可以使用Ansible playbook迭代节点机器上的多个文件,并搜索n替换特定行

[英]Is it possible to iterate through multiple files on the node machine using Ansible playbook and search n replace a particular line

Is there a module/way to iterate over multiple files? 是否存在迭代多个文件的模块/方法?

Use Case: 使用案例:

There are multiple .conf files 有多个.conf文件

/opt/a1.conf

/opt/a2.conf

/var/app1/conf/a3.conf

/etc/a4.conf

Is there a module or a way to iterate over multiple files and search if a particular string exists in these files. 是否存在迭代多个文件的模块或方法,并搜索这些文件中是否存在特定字符串。 The string will remain the same. 字符串将保持不变。

The "lineinfile" module help you search a single file but I would like to know if there is a way to iterate over multiple files and search for this string and replace it with a different values “lineinfile”模块可以帮助您搜索单个文件,但我想知道是否有办法迭代多个文件并搜索此字符串并将其替换为不同的值

My Current playbook Contents for a single file: 我的当前剧本单个文件的内容:

    - name: Modify line to include Timeout
      become: yes
      become_method: sudo
        lineinfile:
        path: /tmp/httpd.conf
        regexp: 'http\s+Timeout\s+\='
        line: 'http Timeout = 10'
        backup: yes

The above can be used only for a single file. 以上只能用于单个文件。

Alternatively, we can use some kind of shell command to do it but is there an Ansible way to achieve this? 或者,我们可以使用某种shell命令来执行此操作但是有一种Ansible方法可以实现此目的吗?

Thank you 谢谢

Have you tried iterating thru loop parameter? 你尝试过迭代loop参数吗?

- 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
  loop:
    - /opt/a1.conf
    - /opt/a2.conf
    - /var/app1/conf/a3.conf
    - /etc/a4.conf

You use with_items directive to transvere of the file, or you can use Jinja scripts look for the string something like below: 您使用with_items指令来传输文件,或者您可以使用Jinja脚本查找以下字符串:

files: 
  - /opt/a1.conf
  - /opt/a2.conf
  - /var/app1/conf/a3.conf
  - /etc/a4.conf

{% for item in files %} {{item.find('string')}} {% endfor %}

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

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