Raymii.org IEC Resistor logo

Quis custodiet ipsos custodes?
RSS Feed

Ansible - Only if a file exists or does not exist

02-02-2014 | Remy van Elst

This Ansible playbook example helps you execute actions only if a file exists or does not exist. If you for example have a command you need to run to generate a certificate (or Diffie Hellman parameters for nginx) you only want to do that once. The command itself is not convergent so it will run with every ansible run. However, the command creates a file and Ansible is able to check if that file exists. If the file exists, it will not execute the action. The same goes for checking if a file does exist and only executing the action if it exists. (The action you want to do will remove that file).

The below example command will generate Diffi Hellman parameters for NGINX ssl. This command creates the file /etc/ssl/certs/dhparam.pem. It should run only if that file does not exist (because only newly deployed servers will not have the file), if the file exist there is no need to run again.

- command: sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048 creates=/etc/ssl/certs/dhparam.pem

Ansible has the creates option in the command module. Give it a filename (directories will not work) and if it already exists Ansible will skip the action.

The same goes for only executing an action if a file exists. The command you are using will remove that file, so only if the file is there the action should be executed. Just as the creates option, there is the removes option. For the removes option, you need at least Ansible 0.8.

The below example is for a custom piece of software one of my clients uses. If we deploy a new version, we check out the code repository and run a script to install a new version. That script will only run when the configuration file is renamed to software.conf.upgrade. After the upgrade it renamed that config file to the original software.conf and also puts the config in its database. It is sadly proprietary software and the manufacturer has stated they are not changing the behavior to a more sane default. The below example will only run the upgrade script when the file /etc/software/software.conf.upgrade exists. Since the script removes it, the next time Ansible runs it does not try to upgrade the software.

- command: /opt/software/bin/upgrade removes=/etc/software/software.conf.upgrade

Documentation for the Command Module

Tags: ansible, configuration-management, deployment, devops, nginx, openssl,