ansible如何在path选项下调用多个文件作为变量



我只是在学习ansible,并试图了解如何在ansiblereplace模块的路径option中包含多个文件。

我有三个文件,需要用new hostanme替换old hostname

文件包括:

- /etc/hosts
- /etc/hosts.custom
- /etc/hosts-backup

以下简单播放效果良好:

- name: Replace string in hosts file
hosts: all
gather_facts: false
tasks:
- name: Replace string in host file
replace:
path: /etc/hosts
regexp: "171.20.20.16   fostrain.example.com"
replace: "171.20.20.16   dbfoxtrain.example.com"
backup: yes

然而,经过大量的谷歌搜索,我发现这可以按照如下方式完成,但如果我有多个文件,并且这些文件需要在不同的模块中作为变量调用,我们如何定义,以便通过变量名调用它们。

以下是我试图理解的内容

- name: Replace string in hosts file
hosts: all
gather_facts: false
tasks:
- name: Checking file contents
slurp:
path: "{{ ?? }}"  <-- How to check these three files here
register: fileCheck.out
- debug:
msg: "{{ (fileCheck.out.content | b64decode).split('n') }}"
- name: Replace string in host file
replace:
path: "{{ item.path }}"
regexp: "{{ item:from }}"
replace: "{{ item:to }}"
backup: yes
loop:
- { path: "/etc/hosts", From: "171.20.20.16   fostrain.example.com", To: "171.20.20.16   dbfoxtrain.example.com"}
- { Path: "/etc/hosts.custom", From: "171.20.20.16   fostrain.example.com", To: "171.20.20.16   dbfoxtrain.example.com"}
- { Path: "/etc/hosts-backup", From: "171.20.20.16   fostrain.example.com", To: "171.20.20.16   dbfoxtrain.example.com"}

我将感谢任何帮助。

创建两个变量;包含所有文件的列表,from和to替换字符串或按ip和domain划分。然后使用文件列表变量循环所有文件,并为每个文件使用from和to替换变量。如果需要多个ip和域映射,则需要进一步调整结构。因此,建议您仔细阅读有关使用变量和循环的易理解文档,了解更多详细信息。

行动手册可能如下所示。已经使用了一个小正则表达式,您可以根据需要进行调整。

- name: Replace string in hosts file
hosts: all
gather_facts: false
vars:
files:
- /etc/hosts
- /etc/hosts.custom
- /etc/hosts-backup
from_ip: "171.20.20.16"
from_dn: "fostrain.example.com"
to_ip: "171.20.20.16"
to_dn: "dbfoxtrain.example.com"
tasks:
- name: Replace string in host file
replace:
path: "{{ item }}"
regexp: "{{ from_ip }}\s+{{ from_dn }}"
replace: "{{ to_ip }} {{ to_dn }}"
loop: "{{ files }}"

如果您想查看每个文件的内容,则可以使用slurpdebug模块,如下所示:

- slurp:
path: "{{ item }}"
loop: "{{ files }}"
register: contents

- debug:
msg: "{{ (item.content | b64decode).split('n') }}"
loop: "{{ contents.results }}"

最新更新