How to get an env var inside a jinja2 template in ansible

6.5k Views Asked by At

So I have this bash script:

#!/bin/bash

echo -ne "Enter stack name: "
read -r STACK
echo -ne "Enter node type (Compute/Storage): "
read -r NODE_TYPE

export STACK
export NODE_TYPE

ansible-playbook -i inventory -l "$AC_STACK" node-exporter-install.yml -e "stack=$STACK"

Inventory file is as simple as defining a group:

[SERVERS]
ip-address-1
ip-address-2
...

Then I have this Jinja2 template which is used by the ansible playbook:

{% for node in groups.getenv('STACK') -%}
  - job_name: '{{ lookup('env', 'STACK') }}-{{ lookup('env', 'NODE_TYPE') }}-{{ node }}'
    static_configs:
    - targets: ['{{ node }}:9100']
{% endfor %}

How do I get the ENV variable STACK defined in the bash script inside the template?!

If I manually define inside the jinja2 template {{ for noe in groups.SERVERS %} it works just fine.

So basically I need that groups.SERVERS to be whatever ENV var I define when executing the bash script....

1

There are 1 best solutions below

1
On BEST ANSWER

I had a hard time figuring out what you were asking, but I think you want this:

{% for node in groups[lookup('env', 'STACK')] -%}
  - job_name: '{{ lookup('env', 'STACK') }}-{{ lookup('env', 'NODE_TYPE') }}-{{ node }}'
    static_configs:
    - targets: ['{{ node }}:9100']
{% endfor %}

You could simplify that a bit like this, which keeps us from having to look up STACK multiple times:

{% set stack = lookup('env', 'STACK') %}
{% for node in groups[stack] -%}
  - job_name: '{{ stack }}-{{ lookup('env', 'NODE_TYPE') }}-{{ node }}'
    static_configs:
    - targets: ['{{ node }}:9100']
{% endfor %}