How can i load a vars file in inventory which "prepares" a large number of variables via jinja2 expressions ?

15 views
Skip to first unread message

ishan jain

unread,
Jun 30, 2017, 10:09:22 AM6/30/17
to Ansible Project
For some servers in an inventory, i assign a range of ports. I want to use these ports in my playbooks while keeping them portable and compatible with any configuration. I am thinking of using variable for ports whose values are resolved via some script in inventory. Something like this:

--In Playbooks--
portValueUser: p1
hostName
: localhost:p2
someURL
: http://hostname:p3



--For first inventory, values of p1, p2, p3....---
p1: 5101
p2
: 5102
p3
5103
...
...
p100
:  5200


--For seconds inventory, values of p1, p2, p3....---
p1: 6201
p2
: 6202
p3
6203
...
...
p100
:  6300



This way, i can use a series of port values in my playbook which are defined by inventory(host vars). I am trying to figure out a way to really apply some logic in constructing these vars
Something like, in inventory/group_vars/all/load.yaml.j2
(please ignore the syntax errors, this is for illustration)

{% if a > b %}

{% for i = 1 to 100 and val = 5101 to 5200 %}

p{{i}} = val
{% endfor %}

{% else %}

{% for i = 1 to 100 and val = 6201 to 6300 %}

p{{i}} = val
{% endfor %}


{% endif %}

Remember the 2 main questions here:
1 - Can i really construct a large number of variables with loop like this ?
2 - How can i load or rather resolve a vars file like above via the inventory ?

Cev Ing

unread,
Jun 30, 2017, 11:10:00 AM6/30/17
to Ansible Project
I do something similar in a role by generating a YML file, which gets included later on by include_vars.

This are the includes in the main.yml of the role:

- include: generate_vars.yml
- include_vars: generated_vars.yml

And this is the task in generate_vars.yml:

shell: |-
  exec >generated_vars.yml
  echo ---
  output_some_data
run_once: true
check_mode: false

I do the generation just once and disable check_mode to avoid errors by undefined variables during checks, because in check mode shell scripts are not executed.
Reply all
Reply to author
Forward
0 new messages