runnerpaul
runnerpaul

Reputation: 7236

include role if variable is true

I want a role to be included in my Ansible playbook if a variable value is true and not executed if it is false. I thought this should work but the integration test gets run even if run_integration_test is false

- include_role:
    name: integration_test
    when: "{{ run_integration_test }}"
  tags:
  - configure_integration
  - aws

What is the correct way to do this?

Upvotes: 0

Views: 1711

Answers (1)

larsks
larsks

Reputation: 312470

You have an indentation problem: when is a task option, not an argument to include_role. You need to write:

- include_role:
    name: integration_test
  when: run_integration_test
  tags:
  - configure_integration
  - aws

Notice that when is aligned with tags in this example.


There's a trap here you might hit depending on how you're setting run_integration_test. You might try running something like this:

ansible-playbook -e run_integration_test=false ...

And you would be surprised that the task still runs. In the above command line, we're setting run_integration_test to the string value "false" rather than to boolean false, and a non-empty string evaluates to true. One way to deal with this is to write your when expression like this:

when: "run_integration_test|default(false)|bool"

This will (a) default to false if run_integration_test is unsent, and (b) will cast string values "true" and "false" to the correct boolean value using the bool filter.

Upvotes: 2

Related Questions