Use Backups When Deploying with Ansible

Backup flag in the template module Backup flag in the template module

I’m back on the task of completely converting my home office and online servers to full Ansible coverage – creating server groups, developing roles and translating any existing setup elements into Ansible playbooks. One important thing to do when deploying configuration files with Ansible is to always keep backups, that’s what I’m going to document today.

Backups of Files in Ansible

To be on the same page, let me explain what I’m referring to: the scope of Ansible backups is any file copied or created from a template in Ansible playbook. So we’re not talking about magical backups of Ansible playbooks or Ansible config files, just the files deployed by Ansible in a certain way.

What happens is Ansible checks for existing file in the destination location, and if found, it gets copied into a timestamped version.

How to activate backups in Ansible playbooks

It’s very simple, actually. Just add this to a file or template section in your Ansible code:

backup: yes

Backup in Ansible template module

Here’s how I use this with template module:

- name: sudoers for techstack user
  src: templates/sudoers-techstack.j2
  dest: /etc/sudoers.d/techstack
  mode: 0640
  backup: yes
  tags: sudo

What this does is it puts existing /etc/sudoers.d/techstack file into a copy like /etc/sudoers.d/techstack.10600.2020-01-12@13:21:39~

Not every file/template operation needs this, but most do – because if you accidentally broke a config file or removed important lines from a text file, there’s a fairly straightforward way to recover from the datestamped copy.

That’s all for today. Have fun with Ansible!

See Also

Contact Me

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!

Recent Tweets