2

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....

Bogdan Stoica
  • 4,349
  • 2
  • 23
  • 38

1 Answers1

4

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 %}

larsks
  • 277,717
  • 41
  • 399
  • 399
  • OMG! I've been trying to do this for over 2 hours now and was not able to figure it out. It worked like a charm! You saved my day! Thank you so much! – Bogdan Stoica Sep 29 '20 at 20:24