HomeHome ArchiveArchive

Only copy files when there are any with ansible

Lets say you have a service that needs to be configured, and that service has optional configuration files - if the configuration file is there, then it is used, if not then not.

How would you configure such a service with ansible?

A line like the following

copy: src=files/optional.config dest=/etc/service/optional.config

will lead to ansible aborting with an error if you do not need and therefore do not provide the files/optional.config in your local configuration.

If you add a:

ignore_errors: True

then ansible will happily continue, even if you locally did provide the files/optional.config config file but there was some problem, as f.ex. insufficient write permissions on the target machine.

Here’s a possible solution:

- name: check wheter we want to copy the optional config file
  local_action: stat path=/files/optional.config
  register: optional_config

- name: upload optional config
  copy: src=files/optional.config dest=/etc/service/optional.config
  when: optional_config.stat.exists