Florius
Florius

Reputation: 407

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!!

Upvotes: 1

Views: 2337

Answers (3)

helloV
helloV

Reputation: 52463

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 (.*)

Upvotes: 3

Alex Cohen
Alex Cohen

Reputation: 6236

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"

Upvotes: 0

KingMak
KingMak

Reputation: 1478

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'

Upvotes: 1

Related Questions