prelic
prelic

Reputation: 4518

Executing roles based on variables

I'm having some odd behavior. I'm still an Ansible novice, so I apologize in advance.

I'm trying to conditionally execute a role, based on an example I saw here: https://github.com/atomicobject/ansible-laptop-playbook-example/blob/1785f25014fa5a7776de5b332d093b60bf59c8e0/laptop.yml

Anyway, I have a host_vars/localhost:

has_thing: true

In my top-level site.yml, I have:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing is defined and has_thing == "true" }

This skips the role.

If I do this instead:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing is defined }

the role executes.

If I do this:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing == "true" }

It does not work.

If I do:

  -name: Title
   hosts: all

   roles:
     - { role: myrole, when: has_thing != "true" }

It still does not work. I don't understand why, the variables has_thing is clearly defined because it works as long as I don't test its value.

What am I missing here?

Upvotes: 3

Views: 3866

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68319

has_thing: true is a boolean, you may test with has_thing: 'true'.

But better change your when statement to handle boolean values.

P.S. And you can't conditionally execute a role a role this way, role will be always executed, but the when statement will be appended to every task in this role generating a lot of skipped tasks in the output.

Upvotes: 1

Related Questions