Conditional role execution problem

Hello all,

I’m trying to execute roles in a playbook conditionally. The conditions are based on command line args as passed through “–extra-vars”. I’ve tried several things and none work. Here are a few examples:

  • hosts: ec2hosts
    user: ubuntu
    roles:

  • common

  • { role: role_1, when: “{{role_1}} == ‘yes’” }

  • { role: role_2, when: “{{role_2}} == ‘yes’” }

When I run the above with “role_1=no” in extra-vars the role is still executed. Here is the debug output from the above:

TASK: [common | print 2] ******************************************************
<X.X.X.X> ESTABLISH CONNECTION FOR USER: ubuntu
ok: [X.X.X.X] => {
“item”: “”,
“msg”: “role_1_matt no”
}

  • hosts: ec2hosts
    user: ubuntu
    roles:
  • common
  • { role: role_1, when: “{{role_1}} is defined” }
  • { role: role_2, when: “{{role_2}} is defined” }

When I run the above with “role_1” omitted from extra-vars it is still run. The debug output from the latter scenario is this:

TASK: [common | print] ********************************************************
<X.X.X>X> ESTABLISH CONNECTION FOR USER: ubuntu
ok: [X.X.X.X] => {
“item”: “”,
“msg”: “role_1_matt {{role_1}}”
}

Any help is greatly appreciated, thanks!

For conditional roles you should just do this:

  • { role: role_1, when: role_1 == ‘yes’ }
  • { role: role_2, when: role_2 == ‘yes’ }

To follow up here, since this was worked out in IRC. The solution to getting this working is to change the role statement to look something like the following:

  • { role: role_2, when: role_2|default(’no’) == 'yes’ }

So sounds like role_2 as a variable just wasn’t passed in and there was no problem with role_1 ?