簡體   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