Linux ansible如何将路径选项下的多个文件作为变量调用
我正在学习ansible,并试图了解如何在ansibleLinux ansible如何将路径选项下的多个文件作为变量调用,linux,ansible,Linux,Ansible,我正在学习ansible,并试图了解如何在ansiblereplace模块的路径选项中包含多个文件 我有三个文件需要将旧主机名替换为新主机名 档案包括: 下面是简单的游戏: 然而,经过大量的谷歌搜索后,我发现这可以按如下方式完成,但如果我有多个文件,并且这些文件需要在不同的模块中作为变量调用,那么我们如何以这样的方式定义它们,以便通过变量名调用它们 下面就是我想理解的。。 -name:替换主机文件中的字符串 主持人:全部 收集事实:错误 任务: -名称:检查文件内容 啜食: 路径:“{{???}
replace
模块的路径选项中包含多个文件
我有三个文件需要将旧主机名
替换为新主机名
档案包括:
下面是简单的游戏:
然而,经过大量的谷歌搜索后,我发现这可以按如下方式完成,但如果我有多个文件,并且这些文件需要在不同的模块中作为变量调用,那么我们如何以这样的方式定义它们,以便通过变量名调用它们
下面就是我想理解的。。
-name:替换主机文件中的字符串
主持人:全部
收集事实:错误
任务:
-名称:检查文件内容
啜食:
路径:“{{???}}”创建一对变量;包含所有文件的列表,从和到替换字符串,或按ip和域划分。然后使用file list变量循环所有文件,并为每个文件使用from和to替换变量。如果需要多个ip和域映射,则需要进一步调整结构。因此,建议阅读ansible文档,了解更多详细信息
剧本可能如下所示。使用了次要正则表达式,您可以根据需要进行调整
-name:替换主机文件中的字符串
主持人:全部
收集事实:错误
变量:
文件夹:
-/etc/hosts
-/etc/hosts.custom
-/etc/hosts备份
来自ip:“171.20.20.16”
摘自:fostrain.example.com
致叶澍鹖:“171.20.20.16”
收件人:“dbfoxtrain.example.com”
任务:
-名称:替换主机文件中的字符串
替换:
路径:“{item}}”
regexp:“{from_ip}\\s+{{from_dn}”
替换:“{{to_ip}}{{{to_dn}}”
循环:“{{files}}”
如果您想查看每个文件的内容,则可以使用slurp
和debug
模块,如下所示:
-slurp:
路径:“{item}}”
循环:“{{files}}”
注册:目录
-调试:
msg:{(item.content | b64decode).split('\n')}
循环:“{contents.results}}”
@。文在寅,谢谢你的解决方案,+1,如果我还有两个变量,比如来自_-ip
和到_-ip
,让我们假设值是来自_-ip:“192.168.12.22”
和到_-ip:“192.168.13.22”
,那么该怎么做呢,抱歉问得太多了。我们已经更新了答案。还建议阅读ansible文档以更好地了解其用法。
- /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"}