Conditional inclusion in template

Hi,

I’m looking for the idiomatic way of including a fragment in a j2 template only for hosts in a group called production.

In pseudo-code, I’m imagining something like this:

{% if host is “production” %}

{% endif %}

Is this an idiomatic approach? If so, what would the concrete syntax look like? If not, how do other people achieve this kind of thing?

Cheers,

Ben

have you looked into group_by?

No, what he's asking is how, in the middle of the template, do you
make a decision based on whether something is in a group or not.
Different question, it's about how you avoid having two templates if
just a part of them changes.

I believe this is what you want...

{% if inventory_hostname in groups["webservers"] %}

{% endif %}

Hi Brian,

Thanks for pointing this out - group_by is definitely a nice dimension to
know about. This has helped me solve the problem for now, although on
reflection I think it would be conciser to be able to an equality test on
an attribute called group within the context of the j2 template. But this
gets me moving for now :slight_smile:

Cheers,

Ben

I think it would be conciser to be able to an equality test on an

attribute called group within the context of the j2 template. But this gets
me moving for now :slight_smile:

Did you see my email?

Hey Michael,

Sorry I didn't see your mail before Brian's - your suggestion is what I was
looking for, so thank you for that.

Cheers,

Ben

Ben,

check the list/thread for Micheal’s post, it is the exact solution you wanted, group by forces the division up to the playbook level, it works but the ‘in-template’ solution Micheal points out is exactly what you wanted.

quoted here, JIC:

Yes, I did (see my reply from 1 minute ago) - thanks for following up on this :slight_smile:

Hey Brian,

Thanks for the heads up :slight_smile:

Cheers,

Ben