include a conditioanl role at playbook

Hi,

I am trying to include a conditional role in my playbook, this role will only apply to first node of my server group, and this server group is automatically created, the ip/hostnames are not fixed. So we could not use following format

roles:

  • common
  • { role: cassandra_opscenter, when: (“10.1.1.1” == inventory_hostname )}

I tried to use something like:

  • { role: cluster_config, when: “{% for host in groups[‘myservers’] %}{% if loop.index0 == 0 %}{{ host }}{% endif %}{% endfor %}” == inventory_hostname }
    or
  • { role: cassandra_opscenter, when: (“groups[‘myservers’][0] == inventory_hostname” )}

But got syntax error for both cases. Does anyone know the correct way to do that?

Thanks

Hi Jack!

It’s not intended that you would need to use template expressions in the when statement (I wanted to make that not required to access variables), but it’s also true that conditional expressions in Jinja2 are not allowed the full python gamut. So that first version is probably going to throw it for a loop – and I think that’s fine, as that’s a bit too complex for the design aesthetic of ansible anyway – that is, we want to keep things simple when we can.

So you had this and this was close though:

  • { role: cassandra_opscenter, when: (“groups[‘myservers’][0] == inventory_hostname” )}

I think is thrown only by the parens:

  • { role: cassandra_opscenter, when: groups.myservers[0] == inventory_hostname }

should be fine.

The bracket around myservers like you had above is still valid, I just simplified it a bit

Let me know if this works for you!

An alternative would be to just have a micro-play in there:

hosts: myservers[0]
tasks:

Which just targets the head node ahead of the others.

I think that would generally be more intuitive, but may not make sense depending on what you want in your playbooks.

Hi Mike:

Thank you so much for the response. I made the change like you suggested:

  • { role: cassandra_opscenter, when: groups.myservers[0] == inventory_hostname }

But I still get following errors:
fatal: [10.1.1.1] => Conditional expression must evaluate to True or False: (True) and ({% if groups.myservers[0] == inventory_hostname %} True {% else %} False {% endif %})
fatal: [10.1.1.2] => Conditional expression must evaluate to True or False: (True) and ({% if groups.myservers[0] == inventory_hostname %} True {% else %} False {% endif %})
fatal: [10.1.1.2] => Conditional expression must evaluate to True or False: (True) and ({% if groups.myservers[0] == inventory_hostname %} True {% else %} False {% endif %})

By the way, I am using ansible server version 1.2.2.

Thanks
Jack

Can you please try this in 1.3.X?

This is the currently released version.

Thanks!