Ansible模块"lineinfile"在多个文件中替换多行 [英] Ansible Module "lineinfile" replace multiple lines in several files
问题描述
我们的SSL证书将在几天内用完.因此,我认为Ansible可以将新证书放到服务器上并更改apache2网站.
our SSL certificate runs out in a couple of days. So I thought Ansible can put the new certs on the server und change the apache2 sites.
服务器站点正在此服务器上运行.
Serveral sites are running on this server.
我要替换以下几行:
- SSLCertificateChainFile
- SSLCertificateKeyFile
- SSLCertificateFile
我使用此命令来获取/etc/apache2中所有模式为"SSLCertificate"的站点的列表.存在.
I use this command to get a list of all sites in /etc/apache2 where the pattern "SSLCertificate" exists.
- name: Apache 2.2 list sites files and store it in register
command: grep -lR --exclude default-ssl "SSLCertificate" /etc/apache2/
register: apache22_sites
当只需要更改一个文件时,这就是我所使用的:
This is what I use, when only one file has to be changed:
- name: apache2.2.* | configure certs
lineinfile: dest=/path/to/... regexp={{ item.regexp }} line={{ item.line}} backrefs=yes
with_items:
- { regexp: "SSLCertificateChainFile", line: " SSLCertificateChainFile = ..." }
- { regexp: "SSLCertificateKeyFile ", line: " SSLCertificateKeyFile = ..." }
- { regexp: "SSLCertificateFile", line: " SSLCertificateFile = ..."
notify: reload apache2
我该如何告诉Ansible将此代码与变量"apache22_sites"中列出的多个文件一起使用? 和倍数行?
How can i tell ansible to use this code with multiple files listed in variable "apache22_sites" and multiples lines?
I found a good hint here, bad sadly only for one line.
我感谢任何小费,技巧和提示:)
I appreciate any tipps, tricks, hints :)
问候 丹尼斯
推荐答案
在注释中指出了 tedder42 ,通常,当人们使用 lineinfile
时,最好对这些文件进行模板.
As tedder42 pointed out in the comments, and as is generally the case when people are using lineinfile
, you'd be much better off templating these files instead.
但是,如果您想解决更常见的问题,即如何遍历多个事物列表,则应使用 with_nested
循环.
However, if you want to solve the more general problem of how you loop through multiple lists of things then you should be using the with_nested
loop.
因此,您的情况如下:
- name: Apache 2.2 list sites files and store it in register
command: grep -lR --exclude default-ssl "SSLCertificate" /etc/apache2/
register: apache22_sites
- name: apache2.2.* | configure certs
lineinfile: dest={{ item.0 }} regexp={{ item.1.regexp }} line={{ item.1.line}} backrefs=yes
with_nested:
- apache22_sites
- lines_to_replace
notify: reload apache2
只要您在如下位置定义lines_to_replace
:
As long as you define your lines_to_replace
somewhere like this:
lines_to_replace:
- { regexp: "SSLCertificateChainFile", line: " SSLCertificateChainFile = ..." }
- { regexp: "SSLCertificateKeyFile ", line: " SSLCertificateKeyFile = ..." }
- { regexp: "SSLCertificateFile", line: " SSLCertificateFile = ..."
这篇关于Ansible模块"lineinfile"在多个文件中替换多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!