1
votes

I have variables in the yaml file and jinja2 template as below.

#consul_common.yml

preprod:
 config_token: "SomeTestToken"

#config.env.j2

service_config_token={{ config_token }}

playbook is like below:

---
- hosts: all
  gather_facts: yes
  tasks:
    - include_vars: consul_common.yml
      
    - set_fact:
        config_token: "{{ (deploy_environment | lower) }}['config_token']"
    
    - debug:
        var: "{{ config_token }}"  
        

    - template: 
        src: config.env.j2
        dest:  /apps/account-service/config.env   

When I run the playbook passing extra env variable deploy_environment=PREPROD , debug is giving the right variable value i.e. "SomeTestToken" but when its templated out in jinja2 template, this is what I am getting in /apps/account-service/config.env

service_config_token=preprod['consul_config_token']

I was expecting the content to be : service_config_token=SomeTestToken

tried with this "{{ (deploy_environment | lower)['config_token'] }}", did not work either.

1

1 Answers

1
votes

Actually the variable config_token that is being set by set_fact contains the dictionary reference "config_token": "preprod['consul_config_token']", and not the value.

Example (notice the missing Jinja delimiters {{ .. }}):

  - debug:
      var: config_token

Also, in your vars file consul_common.yml, you are setting preprod['config_token']. Whereas in your set_fact, you trying to refer to preprod['consul_config_token'], which ideally should not give you the value of SomeTestToken.

So with corrections made to the above issues, the playbook like below should do the job:

  tasks:
  # include vars with a variable name, so that we can access the sub-dict "preprod"
  - include_vars:
      file: consul_common.yml
      name: consul_vars

  # I have used the shorter "deploy_env" variable
  - set_fact:
      config_token: "{{ consul_vars[deploy_env|lower]['config_token'] }}"

  - template:
      src: config.env.j2
      dest:  /apps/account-service/config.env

Above playbook run with -e "deploy_env=PREPROD", renders the template as:

service_config_token=SomeTestToken