Conditionally execute a task if directory exists?

Hi all,

I’ve searched the group and the ansible documentation, but haven’t been able to find a clear answer.

I want to conditionally upload a monit config file in a nginx playbook, but only when the monnit conf directory is present.

tasks:- name: “add monit nginx config”
copy: src=nginx.monit dest=/etc/monit/conf.d owner=root group=root mode=0700
when: ???

The when condition should return True if the directory /etc/monit/conf.d/ exists.

How can I achieve this? Is the an expression I can use, or should I set a “monit_installed” fact in the monit role, or use facter?
Also, is there a difference between only_if and when?

Cheers and one zillion gallactic kudos for developing Ansible!

Sebastiaan

Sure thing.

You probably want to use the register module to save the result of a test and act upon it. What command you want to execute is pretty wide open, maybe it’s rpm -qa, etc.

  • shell: …
    register: some_result

Then you might do:

  • copy: …
    when: some_result.rc == 0

In 1.3, there’s also a ‘stat’ module you can use which returns lots of useful attributes and works really well with register.

Should you want to use facts instead to write a “monit installed fact”, you could do that too … there shouldn’t be any need to use facter, as you could write your own ansible facts and just call the module.

There is also the new “facts.d” feature in Ansible 1.3 (not yet documented as it’s the development version), where you can drop a JSON file or executable script that returns JSON into /etc/ansible/facts.d/*.fact

if you need an example, I did it this way here:
https://github.com/markmandel/dotfiles/blob/master/provision/roles/core/tasks/_oh_my_zsh.yml#L4

For my local oh-my-zsh provisioning.

(Short version)


- name: See if zsh is installed

  shell: "[ -d ~/.oh-my-zsh ] && echo 'Found' || echo ''"

  register: zsh_installed
- name: install oh my zsh

Thanks for your help Michael and Mark, I appreciate it!
In addition to Mark’s example, another way of checking the existence of a path is with the stat module which was added in 1.3:

Oh Nice! I didn't see that come in. Very cool!

Mark

Hi Sebastiaan,

Thanks for sharing. It’s helpful…

Kevin

Hi Sebastiaan Pouyet,

once read this articale how to know if the directory is already existed or not, you can implement this condition in your case.

Ansible Create directory if not exists