Ansible & lineinfile
This is a pattern I keep using for simple configuration file changes, but I never quite remember where and how so time to document it here!
The typical use case for me – changing a configuration file like
sshd_config
:
- name: Disable password logins
ansible.builtin.lineinfile:
path: "/etc/ssh/sshd_config"
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
state: "{{ item.state|default('present') }}"
with_items:
- { "regexp": "^#?ChallengeResponseAuthentication", "line": "ChallengeResponseAuthentication no", "state": "present" }
- { "regexp": "^#?PasswordAuthentication", "line": "PasswordAuthentication no", "state": "present" }
- { "regexp": "^#?UsePAM", "line": "UsePAM no", "state": "present" }
- { "regexp": "^#?PermitRootLogin", "line": "PermitRootLogin prohibit-password", "state": "present" }
- { "regexp": "^#?X11Forwarding", "line": "X11Forwarding no", "state": "present" }
notify: restart sshd
The above will change each regexp to it’s desired state, no matter if
the configuration option is commented out or not. You can omit
"state": "present"
for each line as it’s the default.