Condition in Templates

Hi everyone,

one simple question and sry for my english skills :slight_smile:

I have a playbook with some templates, in one template I added a condition to write a specific IP Address in my template.
(My servers have several network ports and unfortunately they have sometimes different names. Ok, i could use different templates but i wanted to use a single file)

The code:

{% if ansible_mgt.ipv4.address is defined %}
server_address={{ansible_mgt.ipv4.address}}
{% else %}
server_address={{ansible_eth0.ipv4.address}}
{% endif %}

If I run the playbook against a server which has not the network port ansible_mgt the playbook fails because the variable ansible_mgt.ipv4.address is not defined.

What I am doing wrong? Or it is not possible to check in a template if a variable is not defined?

Thanks for your help!

Regards,
Jost

Hi,

I guess, in that case not even ansible_mgt will be defined? What is exact error message (try ansible-playbook with -vvv) ?

David

Hi David,

the error message is:

fatal: [testserver.xxx] => {ā€˜msgā€™: ā€œAnsibleUndefinedVariable: One or more undefined variables: ā€˜ansible_mgtā€™ is undefinedā€, ā€˜failedā€™: True}
fatal: [testserver.xxx] => {ā€˜msgā€™: ā€œAnsibleUndefinedVariable: One or more undefined variables: ā€˜ansible_mgtā€™ is undefinedā€, ā€˜failedā€™: True}
FATAL: all hosts have already failed ā€“ aborting

Well, that is true. On this machine I have only ansible_eth0:

ā€œansible_eth0ā€: {
ā€œactiveā€: true,
ā€œdeviceā€: ā€œeth0ā€,
ā€œipv4ā€: {
ā€œaddressā€: ā€œ10.101.10.133ā€,
ā€œnetmaskā€: ā€œ255.255.255.0ā€,
ā€œnetworkā€: ā€œ10.101.10.0ā€
},

My idea was to use the condition, if ansible_mgt is defined ā†’ use ansible_mgt and if not ā†’ ansible_eth0

Regards,
Jost

Hi Josh,

your idea is right:

{% if ansible_mgt is defined and ansible_mgt.ipv4.address is defined %}
server_address={{ansible_mgt.ipv4.address}}
{% else %}
server_address={{ansible_eth0.ipv4.address}}
{% endif %}

you have to check ansible_mgt first.

Hi David,

of course! thank you very much!

I didnā€™t recognized that the error message was only saying ā€œansible_mgtā€ and not ā€œansible_mgt.ipv4.addressā€ā€¦facepalm

Regards,
Jost