user8888888888888888
user8888888888888888

Reputation: 43

How to update variables of ansible roles through jinja2 template

I am learning ansible roles and I am trying to set the variables of the roles using Jinja2 template. But the variable values are not being updated.

Here's the working directory sample

sample
├── README.md
├── defaults
│   └── main.yml
├── files
│   └── main.out
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── tasks
│   └── main.yml
├── templates
│   └── main.j2
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

The contents of the vars/main.yml folder are

a: 2
b: 3
c: 0

The Contents of the tasks/main.yml are

---
 - name: Jagadish Sagi
   template:
           src: "sample2/templates/main.j2"
           dest: "sample2/files/main.out"
 - name: Printing value of c
   debug:
           var: c

The Contents of the templates/main.j2 are

{% if a > b %}
{% set c = a %}
{% else %}
{% set c = b %}
{% endif %}
The Value of C : {{c}}

The Code for executing the role is

---
 - hosts: localhost
   roles:
         - sample2

In files/main.out file I am getting output

The Value of C : 3

But in the ansible playbook while printing it to the console it gives

ok: [localhost] => {
    "c": 0
}

I know that i can do it using ansible only with the help of set_fact and if else conditions. but how can I do it using Jinja2 Template too??

Upvotes: 2

Views: 5379

Answers (2)

Zeitounator
Zeitounator

Reputation: 44615

The set you are using in you template will only be valid inside your template. The value of c remains unchanged for ansible itself. If you need to use that value later for other tasks, you cannot do it this way.

The order of precedence of role vars is still lower than set_fact so this could do the trick.

Meanwhile, if c is always a calculated var that can change depending on a and b, this is what I would do.

  • declare a and b in role's default so that they are easily overloaded in any situation
---
# defaults/main.yml
a: 2
b: 3
  • declare c in role vars depending on a and b values
---
# vars/main.yml
c: "{{ (a > b) | ternary(a, b) }}"

You can now use c wherever you like in your tasks with its correct value without having to calculate anything else.

Upvotes: 0

mdaniel
mdaniel

Reputation: 33203

I know that i can do it using ansible only with the help of set_fact and if else conditions. but how can I do it using Jinja2 Template too??

You cannot; Jinja2 templates do not mutate their environment, since Jinja2 isn't a programming language, it's template markup.

You must use set_fact: to alter the hostvars of your playbook run

Upvotes: 1

Related Questions