Karl
Karl

Reputation: 3113

How can I dynamically change an Ansible variable?

I have this in vars:

var1: "test1"
var2: "test2"
var3: "{{var1}}"

Now I want to dynamically change var3: "{{var2}}".

I can assign var3: "test2". But how can I assign var3: "{{var2}}"?

Upvotes: 20

Views: 45264

Answers (1)

techraf
techraf

Reputation: 68489

My attempt at the interpretation of the phrase "dynamically change Ansible variable" based on your question:

---
- hosts: localhost
  connection: local
  vars:
    var1: "test1"
    var2: "test2"
    var3: "{{var1}}"
  tasks:
    - debug: var=var3
    - set_fact:
        var3: "{{var2}}"
    - debug: var=var3

Regarding the comment:

i was thinking set_fact makes vars as hostvars which don't have precedence over playbook vars

Variables assigned through a set_fact module are in their own class of variables which has a lower priority only to block vars, task vars and extra vars. See Variable Precedence.

Upvotes: 24

Related Questions