I used the replace module instead of lineinfile since you can find several matches for any of these lines that you want to replace.
The tricky thing about this task is the use of Regular expressions in Python.
The module works in the following way, what it is matched with the regexp expression will be replaced by the replace line.
What was challenging for me was to learn the backreferences. This is used to match a regular expression and use it later in your replace line.
I will use the last line to explain how it works.
You have to add the regular expression you want to match inside the parentheses. You can name it using ?P , otherwise it will be named as expression number 1.
In my example is ?P<comm>
In my case I wanted to replace
community tivoli 192.132.10.0 255.255.255.0 writeOnly
with
community tivoli 192.132.10.0 255.255.255.0 readOnly
I used the following regexp line in my play
community
\s for whitespace
\w* for word characters plus the * to match 0 or more repetitions to match tivoli
\s for whitespace
\b(?:\d{1,3}\.){3}\d{1,3}\b\ to match 192.132.10.0
s\ for whitespace
b(?:\d{1,3}\.){3}\d{1,3}\b) to match 255.255.255.0
(?P<rw>readWrite) to match readWrite
In the line, I used the group I had created g<comm> (if I hadn't name it I would have used g<1> ) and the pattern I wanted to add which was readOnly.
My new line will be g<comm> which is community tivoli 192.132.10.0 255.255.255.0 plus readOnly
- name: SNMP Configuration
replace:
path: /etc/snmpd.conf
regexp: "{{ item.regexp }}"
replace: "{{ item.line }}"
loop:
- { regexp: '^community(.+)public', line: '#community public' }
- { regexp: '^community(.+)private', line: '#community private' }
- { regexp: '^community(.+)system', line: '#community system' }
- { regexp: '(?P<comm>^community\s\w*\s\b(?:\d{1,3}\.){3}\d{1,3}\b\s\b(?:\d{1,3}\.){3}\d{1,3}\b)\s(?P<rw>readWrite)', line: '\g<comm> readOnly' }
References:
No comments:
Post a Comment