Foremost, I know the ‘best practice’ is to use the copy command for items such as this, however one goal is to keep the package-installed config files for basic system tools as close to the original package version to ease upgrades of systems and operating systems down the road and make easy ‘diffs’ as to what may have changed in a package maintainer’s version of the file. I don’t do this for essential types of programs, but for tweaking a couple options from the package maintainers, I like it this way. Now on to the example:
I have a task as follows that basically changes some commented out options and replaces the line with uncommented versions. For anyone who is seeing this as an example, I also have a handler caleld ‘restart denyhosts’ to complete this example.
- name: configure denyhosts
lineinfile: dest=/etc/denyhosts.conf regexp=‘{{ item.re }}’ line=‘{{ item.ln }}’
with_items: - { re: ‘^PURGE_DENY =$’, ln: ‘#PURGE_DENY =’ }
- { re: ‘^#PURGE_DENY = 1w$’, ln: ‘PURGE_DENY = 1w’ }
- { re: ‘^DENY_THRESHOLD_ROOT = 1$’, ln: ‘DENY_THRESHOLD_ROOT = 5’ }
- { re: ‘^#RESET_ON_SUCCESS = yes$’, ln: ‘RESET_ON_SUCCESS = yes’ }
- { re: '^ADMIN_EMAIL = ', ln: ‘ADMIN_EMAIL =’ }
notify: restart denyhosts
tags: denyhostsconfig
The result on execution is as follows:
TASK: [common | configure denyhosts] ******************************************
changed: [clover.domain.tld] => (item={‘ln’: ‘#PURGE_DENY =’, ‘re’: ‘^PURGE_DENY =$’})
changed: [clover.domain.tld] => (item={‘ln’: ‘PURGE_DENY = 1w’, ‘re’: ‘^#PURGE_DENY = 1w$’})
changed: [clover.domain.tld] => (item={‘ln’: ‘DENY_THRESHOLD_ROOT = 5’, ‘re’: ‘^DENY_THRESHOLD_ROOT = 1$’})
changed: [clover.domain.tld] => (item={‘ln’: ‘RESET_ON_SUCCESS = yes’, ‘re’: ‘^#RESET_ON_SUCCESS = yes$’})
changed: [clover.domain.tld] => (item={‘ln’: ‘ADMIN_EMAIL =’, ‘re’: '^ADMIN_EMAIL = '})
NOTIFIED: [common | restart denyhosts] ****************************************
changed: [clover.domain.tld]
PLAY RECAP ********************************************************************
clover.domain.tld : ok=3 changed=2 unreachable=0 failed=0
THE QUESTION
The file has already been changed by running this once and contains NONE of those ‘regexp’ lines. Meanwhile, the lineinfile is showing changed on each one of them.
How can I get this command to show as unchanged if those lines don’t match?
Obviously I can add changed_when: False to that statement, but then it’ll never tell me if it actually made those changes, as it will always return ‘ok’.
Can lineinfile simply return changed only if the line on the regexp is found?
-Michael