Search code examples
jinja2salt-project

Insert Environment Variable using Jinja in SaltStack


I am trying to read a JSON file inside a folder. using import_json. Here is my code

{% set instance_id = grains['INSTANCE_ID'] %}
INSTANCE_ID Env Var:
  environ.setenv:
    - name: INSTANCE_ID
    - value: {{ grains['INSTANCE_ID'] }}
    - update_minion: True

{% import_json "/tmp/$INSTANCE_ID/conf.json" as config_properties %}

But I am getting this error

Data failed to compile:
Rendering SLS 'base:cloud.steps.conf' failed: Jinja error: /tmp/$INSTANCE_ID/conf.json.

Although when I insert the INSTANCE_ID manually it works as expected.

What I want is to be able to insert either $INSTANCE_ID or directly the grain value {{ grains['INSTANCE_ID'] }}

Can someone please help me with this? Thanks.


Solution

  • {% import_json "/tmp/$INSTANCE_ID/conf.json" as config_properties %}
    

    I imagine you are trying to evaluate the variable $INSTANCE_ID in the above statement. Jinja template evaluates the variables in expression statements.

    In this case, the variable is set in the first line, using set

    {% set instance_id = grains['INSTANCE_ID'] %}
    

    So, you can use it in expression along with string appends, like

    {% import_json "/tmp/" ~ instance_id ~ "/conf.json" as config_properties %}
    

    The above statement should resolve your error.

    Also, I would suggest using a variable to evaluate the value of the string expression above, like

    {% set conf_json_path = "/tmp/" ~ instance_id ~ "/conf.json" %}
    

    and use it like this

    {% import_json conf_json_path as config_properties %}
    

    Hope this help!


    In case, you wish to use grains dictionary directly, you can use the value like so

    {% set conf_json_path = "/tmp/" ~ grains['INSTANCE_ID'] ~ "/conf.json" %}