简体   繁体   English

Ansible:替换文件中的单词

[英]Ansible: Replace word in file

I'm making a Ansible playbook to setup CSF. 我正在制作Ansible手册来设置CSF。 I've got everything done except for the last part. 除了最后一部分,我已完成所有工作。

I'd like to disable port 22 in the /etc/csf/csf.conf file. 我想在/etc/csf/csf.conf文件中禁用端口22。 So TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995" needs 22 removed. 因此, TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995"需要删除22 I don't want to replace the entire line as some lines are different, some got port 2087 open, or 2222 for example. 我不想替换整行,因为某些行不同,例如某些端口打开了2087端口或2222 Is there any way I can only filter on 22 ? 有什么办法只能过滤22吗?

Thank you in advance!! 先感谢您!!

You have several options: 您有几种选择:

This solution uses replace module, to look for a line beginning with TCP_OUT = and replace ,22, with , in the line. 此解决方案使用更换模块,以寻找与开头的行TCP_OUT =和替换,22,,在该行。

  tasks:
  - name: Strip port 22
    replace:
      dest: /etc/csf/csf.conf
      regexp: '^TCP_OUT\s*=\s*(.*),22,(.*)$'
      replace: 'TCP_OUT = \1,\2'
  • \\s* - Matches zero or more white spaces (blanks, tabs etc.,) \\ s * -匹配零个或多个空格(空格,制表符等)
  • \\1 - Whatever matched in the first group (.*) \\ 1-第一组中匹配的任何内容(。*)
  • \\2 - Whatever matched in the second group (.*) \\ 2-第二组中匹配的任何内容(。*)

Code working proof 代码工作证明

>>> TCP_OUT = '20,21,22,25,53,80,110,113,443,587,993,995,2087,2222,22'
>>> print(','.join([port for port in TCP_OUT.split(',') if port != '22']))
'20,21,25,53,80,110,113,443,587,993,995,2087,2222'

You could use template . 您可以使用template Make a copy of your /etc/csf/csf.conf file and for the TCP_OUT line replace it with an ansible variable: 复制/etc/csf/csf.conf文件,并在TCP_OUT行中将其替换为ansible变量:

TCP_OUT = {{ port_list }}

Then set the list ahead of time in a variable with the ports you desire in the file. 然后,在变量中预先设置列表,并在文件中添加所需端口。

vars:
  port_list = "20,21,25,53,80,110,113,443,587,993,995"

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

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