Managing Files: file, copy, lineinfile & Friends
Most server configuration is files under /etc. Ansible gives you a module for each way of owning a file, from "I own the whole file" to "I own one line in it".
| You own… | Module |
|---|---|
| the file's existence, type, mode, owner (directories, links, empty files, deletion) | file |
| the whole content, static | copy (from files/ or inline content:) |
| the whole content, with variables | template (Jinja2 Templates) |
| one line | lineinfile |
| a block of lines between markers | blockinfile |
| one key in an INI section | community.general.ini_file |
| every match of a regex | replace |
Prefer owning the whole file (copy/template) when you can: the result is fully predictable. Editing lines is for files that other packages or people also write, such as /etc/hosts or a distribution's default sshd_config.
file and copy
cat > files.yml <<'YML'
- name: Files and directories
hosts: localhost
gather_facts: false
vars:
root: /home/learner/srv
tasks:
- name: Directory tree
ansible.builtin.file:
path: "{{ root }}/{{ item }}"
state: directory
mode: "0750"
loop: [conf, releases, logs]
- name: Config from inline content
ansible.builtin.copy:
dest: "{{ root }}/conf/app.env"
content: |
APP_ENV=production
APP_PORT=8080
mode: "0640"
backup: true
- name: A symlink to the current release
ansible.builtin.file:
src: "{{ root }}/releases"
dest: "{{ root }}/current"
state: link
- name: Remove an old file (absent is idempotent too)
ansible.builtin.file:
path: "{{ root }}/legacy.conf"
state: absent
YML
ansible-playbook files.yml | grep -E '^(ok|changed)'
find srv | sort
stat -c '%A %n' srv/conf srv/conf/app.envchanged: [localhost] => (item=conf)
changed: [localhost] => (item=releases)
changed: [localhost] => (item=logs)
changed: [localhost]
changed: [localhost]
ok: [localhost]
srv
srv/conf
srv/conf/app.env
srv/current
srv/logs
srv/releases
drwxr-x--- srv/conf
-rw-r----- srv/conf/app.env
backup: true keeps a timestamped copy of the old file whenever copy replaces it, which is useful on hand-managed servers. state: absent on a missing file is simply ok.
lineinfile: one line, found by a regex
regexp finds the line to replace; line is what it should become. If nothing matches, the line is appended (or placed with insertafter/insertbefore).
cat > sshd_config <<'CONF'
Port 22
#PermitRootLogin prohibit-password
PasswordAuthentication yes
UsePAM yes
CONF
cat > ssh.yml <<'YML'
- name: Harden an sshd_config
hosts: localhost
gather_facts: false
tasks:
- name: Set sshd options
ansible.builtin.lineinfile:
path: sshd_config
regexp: "^#?{{ item.key }}\\s"
line: "{{ item.key }} {{ item.value }}"
loop:
- {key: PermitRootLogin, value: "no"}
- {key: PasswordAuthentication, value: "no"}
- {key: MaxAuthTries, value: "3"}
YML
ansible-playbook ssh.yml | grep -E '^(ok|changed)'
cat sshd_config
echo "=== again"
ansible-playbook ssh.yml | grep -E '^(ok|changed)'changed: [localhost] => (item={'key': 'PermitRootLogin', 'value': 'no'})
changed: [localhost] => (item={'key': 'PasswordAuthentication', 'value': 'no'})
changed: [localhost] => (item={'key': 'MaxAuthTries', 'value': '3'})
Port 22
PermitRootLogin no
PasswordAuthentication no
UsePAM yes
MaxAuthTries 3
=== again
ok: [localhost] => (item={'key': 'PermitRootLogin', 'value': 'no'})
ok: [localhost] => (item={'key': 'PasswordAuthentication', 'value': 'no'})
ok: [localhost] => (item={'key': 'MaxAuthTries', 'value': '3'})
The #? in the regex also catches the commented default, so you don't end up with both #PermitRootLogin and PermitRootLogin in the file. On a real server, add validate: /usr/sbin/sshd -t -f %s so a broken file is never written (see Hardening the SSH Server), and a handler to reload sshd.
blockinfile and ini_file
printf '127.0.0.1 localhost\n' > hosts
printf '[server]\nport = 80\n\n[log]\nlevel = info\n' > app.ini
cat > edit.yml <<'YML'
- name: Blocks and INI keys
hosts: localhost
gather_facts: false
tasks:
- name: Our hosts block
ansible.builtin.blockinfile:
path: hosts
marker: "# {mark} ANSIBLE MANAGED: app cluster"
block: |
10.0.1.10 web1
10.0.1.11 web2
- name: One INI key
community.general.ini_file:
path: app.ini
section: server
option: port
value: "8080"
mode: "0644"
YML
ansible-playbook edit.yml | grep -E '^(ok|changed)'
cat hosts app.inichanged: [localhost]
changed: [localhost]
127.0.0.1 localhost
# BEGIN ANSIBLE MANAGED: app cluster
10.0.1.10 web1
10.0.1.11 web2
# END ANSIBLE MANAGED: app cluster
[server]
port = 8080
[log]
level = info
The markers let blockinfile find and replace its block on the next run, and remove it with state: absent. Use a different marker text for each block you manage in the same file.
Test yourself
Which module fits best for owning a single key = value in one section of an INI file?
copycommunity.general.ini_filefileblockinfile
What does lineinfile do when regexp matches nothing?
- Fails
- Appends
line(or inserts it whereinsertafter/insertbeforesay) - Deletes the file
- Does nothing
Why prefer template over many lineinfile tasks when you own a config file completely?
- It is faster to type
- The whole file is predictable; no leftover lines from defaults or hand edits
- lineinfile is deprecated
- template doesn't need Python