HeroFromEarth
HeroFromEarth

Reputation: 93

Ansible templates with undefined variables

I have a file with variables that I use in my playbook:

net_interfaces:
  ...
  - name: "eth0"
    ip: "192.168.1.100"
    mask: "255.255.255.0"
    gateway: "192.168.1.1"
  ...

and I want to deploy some configs with this variables, for example ifcfg-eth0:

DEVICE={{ item.name }}
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR={{ item.ip }}
NETMASK={{ item.netmask }}
GATEWAY={{ item.gateway }}

but sometimes there is no gateway variable for item and in this case I want to remove string

GATEWAY={{ item.gateway }}

from this config file on the target machine. How can I achieve this without creating another task for a certain hosts?

Upvotes: 4

Views: 9238

Answers (2)

HeroFromEarth
HeroFromEarth

Reputation: 93

Another (and better) way is to use 'default' filter because in this case we can check if some variable was defined and set it's default value if it wasn't. Example:

{{ my_string_value | default("awesome") }}

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68309

Add condition:

{% if item.gateway is defined %}
GATEWAY={{ item.gateway }}
{% endif %}

Upvotes: 9

Related Questions