Jinja2 if/else matching both - ansible

I'm trying to use an if/else statement in an ansible template to populate values based on my hostname. I've written a module that parses the hostname and adds the values as facts. I'm able to use these facts in my playbooks but am having trouble getting an if/else statement to use them correctly. I end up with both the if and else matching so both values end up in my file.
jinja2 template
{% for host in groups['tag_Function_logfe'] %}
{% if hostvars[host]['tt_number'] == "01" %}
is_master = true
{% else %}
is_master = false
{% endif %}
{% endfor %}
Ansible Facts:
ok: [node1] => {"ansible_facts": {"tt_number": "01"}, "changed": false, "msg": "Additional facts added successfully"}
ok: [node2] => {"ansible_facts": {"tt_number": "02"}, "changed": false, "msg": "Additional facts added successfully"}
results:
is_master = true
is_master = false

I don’t have the full picture of what you’re trying to do overall, but Ansible and Jinja seem to behave as documented in this case so there might be a misunderstanding elsewhere.
You have a template that Ansible would render into a configuration file on every host. In this template, a for loop iterates over hosts in given group and declares is_master for each of those hosts. That would result in multiple definitions in every instance of the template, equal to the number of hosts in the “tag_Function_logfe“ group.
That doesn’t seem to make sense to me, since I’d assume there would be only one is_master definition per host.
Perhaps what you wanted to do instead is having this in the template:
{% if inventory_hostname in groups['tag_Function_logfe'] %}
{% if tt_number == "01" %}
is_master = true
{% else %}
is_master = false
{% endif %}
{% endif %}
The inventory_hostname points to the host Ansible would be working with at the moment. We apparently want to check that this host belongs to the “tag_Function_logfe” group, and if it doesn’t we don’t define is_master at all.
Then we want to determine what value is_master should have based on tt_number. Note that we don’t need to use hostvars because we access tt_number’s value only for current host where the template is rendered into the configuration file.
It’s probably possible to further eliminate the group membership test, but that’s harder to tell without looking at the rest of the configuration.

Related

How to get desired output using Ansible jinja2 if else statement

Below is tasK:
- name: primary slot on active
debug: msg={{slotid.stdout_lines}}
register: slotidoutput
output1:
TASK [primary slot on active] *************************************************************************
ok: [1.1.1.1] => {
"msg": [
[
"Primary Slot ID 1"
]
]
}
some devices dosen't have primary slot ID so at that time output will be like :
output2:
TASK [primary slot on active] ***********************************************************************
ok: [2.2.2.2] => {
"msg": []
}
so i am working on a jinja2 template
{% if 'Primary Slot ID' in slotidoutput %}
{{slotidoutput.msg[0][0]}}
{% else %}
Single Slot
{% endif %}
i am always getting value as "Single Slot" even though i ran on multi slot device which has output1
Single Slot
desired print value for device 1.1.1.1 is:
Primary Slot ID 1
desired print value for device 2.2.2.2 is:
Single Slot
I am sure that i am doing some mistake in jinja if else statement. Can some one check and let me know.
There are few conditions that we need to address for the template to work properly.
sometimes slotid.stdout_lines is a nested list
in some cases it is an empty list []
conditional check with in will perform exact match on list items, and search match on a string
Also, register on debug output seems unnecessary as it holds the same data structure as slotid.stdout_lines.
So tasks and template such as below should address the above issues:
Tasks:
# Flatten nested list to single level
- set_fact:
slotidout: "{{ slotid.stdout_lines|flatten }}"
# Using random name for template
- template:
src: testtemplate.j2
dest: /tmp/testtemplate
Template testtemplate.j2:
{% if slotidout[0] is defined %}
{% if "Primary" in slotidout[0] %}
{{ slotidout[0] }}
{% endif %}
{% else %}
Single slot
{% endif %}
This should create the file with appropriate values based on conditions. You may adjust the conditions based on your requirements.

Ansible facts of all hosts to template

I'm trying to write a dhcpd.conf template for my server to set static leases that is looking like this atm:
`
{% for item in groups.all %}
{% set short_name = item.split('.') %}
host {{ item }} {
hardware ethernet {{ ansible_eth0.macadress }};
fixed-address {{ hostvars[item]['ipaddress'] }};
}
{% endfor %}
`
'ipaddress' is a variable set in the inventory file
After running the playbook everything works fine, but the value for 'ansible_eth0.macaddress' is always the same and not like expected the macaddress matching to the right host.
Does anyone have an idea how i can make the loop working like i want to?
Without the tasks you use this jinja2 template i can just guess. Maybe u are fine with_subelements.

Translating multiple default variables from Chef to Ansible

How would a node attribute being set by a case in Chef be translated to a variable in Ansible?
Example:
case node['custom_attribute']
when 'security_standard_1'
security_standard = 'ss1'
when 'security_standard_2'
security_standard = 'ss2'
else
security_standard = 'off'
end
I've only seen things that have two possible values being set with jinja.
security_standard: "{{ security_standard_1 | security_standard_2 }}"
Is this thought process even doable in Ansible?
You can define variables using jinja template with if-else conditions to suit your needs.
Here's an example:
security_standard: "{%- if (security_standard_1 is defined) -%}ss1
{%- elif (security_standard_2 is defined) -%}ss2
{%- else -%}off
{%- endif -%}"

How can one generate a dict in Jinja/Ansible as a var?

I need to dynamically generate a dict and assign it to an Ansible var so that the same data is available to every host and does not need to be regenerated on each one. This will be looped over by a task and template. It is possible to build lists by nesting Jinja in a var definition like so:
var_list: >
[
{% set data = [] %}
{% for host in groups['all'] %}
{{ data.append(host) }}
{% endfor %}
{{ data }}
]
However, I am not able to do so with dicts:
var_dict: >
{
{% set data = dict() %}
{% for host in groups['all'] %}
{{ data | combine({host: []}) }}
{% endfor %}
{{ data }}
}
This results in a giant, garbled string: {u'host.subdom.dom.tld': []} {}...
What I am expecting is a var set to a true dict object that can have its components referenced individually (like {{ var_dict.host1[0] }}), with a structure similar to the following JSON:
{
"host1": [],
"host2": []
}
Is there a way to cause this to expand into a proper dict when assigned to the variable? Or is there perhaps another way to generate a dict from a loop without that awful set_fact hackery?
Either of your templates is broken (the first one produces nested lists, the second one prints data in loop with this expression {{ data | combine({host: []}) }}, the value of data remains empty until the end).
Jinja2 is a templating engine, you don't really need to create data structures to print them later. You can form your output directly.
For the list:
var_list: >
[ {% for host in groups['all'] %}'{{ host }}',{% endfor %} ]
For the dictionary:
var_dict: >
{ {% for host in groups['all'] %}'{{ host }}': [],{% endfor %} }
As you expect the values to be interpreted by Ansible, you don't need to pay attention to the trailing coma, otherwise there is loop.last.

Change variable in Ansible template based on group with children?

I found Change variable in Ansible template based on group. However how do I extend the answer in groups with children?
If I extend the group vars file in the link above to
[host0]
host0.my-network.com
[host1]
host1.my-network.com
[es-masters:children]
host0
host1
How can I extend the above post's answer (shown below) to make it work with the group vars file above? Simply putting the FQDN in the jinja2 statement does not work.
{% if ansible_fqdn in groups['es-masters'] %}
node_master=true
{% else %}
node_master=false
{% endif %}
What you should do is:
Provide default in template
# role_name/templates/template.j2
node_master={{ role_name_node_master | default(true) }}
Than override in group_vars
# group_vars/es-masters.yml
role_name_node_master: false

Resources