What is the equivalent of Puppet's `unless` in Ansible?

I think what you're looking do is this:

- name: get vhosts
  command: rabbitmqctl list_vhosts
  register: vhosts
  changed_when: false

- name: add vhost sensu
  command: rabbitmqctl add_vhost /sensu
  when: "'/sensu' not in vhosts.stdout"

Re: #3 register does not create a file. If you're capturing the output of rabbitmqctl list_vhosts via register, the contents will be as valid as the system's current state.


The problem is the line when: rabbitmqctl list_vhosts | grep sensu. It is not possible to use bash here.

You need to put the rabbitmqctl list_vhosts | grep sensu in a separate task and register the result to use it in the when clause. You can use not filter to get unless like behavior.

Something like this should work:

- name: Get rabbitmq vhosts.
  command: rabbitmqctl list_vhosts | grep sensu
  register: rabbitmq_vhosts

- name: add vhost sensu
  command: rabbitmqctl add_vhost /sensu
  when: not 'sensu' in rabbitmq_vhosts.stdout

The Get rabbitmq vhosts. in this example will always be executed. The add vhost sensu only if the string sensu is not in the registered rabbitmq_vhosts.

Consult the documentation on conditionals and jinja filters for more information.

Tags:

Ansible