简体   繁体   中英

Ansible: Replace word in file

I'm making a Ansible playbook to setup 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. So TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995" needs 22 removed. I don't want to replace the entire line as some lines are different, some got port 2087 open, or 2222 for example. Is there any way I can only filter on 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.

  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.,)
  • \\1 - Whatever matched in the first group (.*)
  • \\2 - Whatever matched in the second group (.*)

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 . Make a copy of your /etc/csf/csf.conf file and for the TCP_OUT line replace it with an ansible variable:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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