I did quite a lot of tasks with Ansible in the last few months. Here are a few tricks for my future me and everybody else:
Check for Multiple Lines in a File
Sometimes you don't want to check for a whole block but several lines. In case you are working with an ini-config file, you might use this snippet:
- name: Configure dnf
lineinfile:
dest: /etc/dnf/dnf.conf
regexp: "^{{ item.split('=')|first }}"
line: "{{ item }}"
with_items:
- gpgcheck=1
- installonly_limit=3
- clean_requirements_on_remove=True
- best=True
- defaultyes=True
- fastestmirror=True
- skip_if_unavailable=False
Force Docker Image Built
In case an image should be built every time, no matter if it's present or not:
- name: Build image
community.docker.docker_image:
source: build
force_source: true
build:
path: ...
Backup Docker Volumes
Mounted Docker volumes can be slow, e.g., due to security constraints. Keeping the volumes within Docker improves performance most of the time but requires adjusting the backup strategies. Here is one:
- name: Install docker volume backup
ansible.builtin.cron:
name: "backup {{project}} files"
minute: "{{ 59 | random(seed=inventory_hostname) }}"
hour: "3"
job: "docker run --rm -v {{backupdir.files}}:/dest -v {{docker_volume}}:/src -w /src alpine /bin/tar -czf /dest/'files_'`date +\\%w`'.tgz' . > /dev/null"
when: docker_volume is defined