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}}"
?
Ansible has a strict set of rules to create valid variable names. Variable names can contain only letters, numbers, and underscores and must start with a letter or underscore. Some strings are reserved for other purposes and aren't valid variable names, such as Python Keywords or Playbook Keywords.
This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.
In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope. Variables in the defaults folder inside a role are easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in the namespace.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With