Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically change an Ansible variable?

Tags:

ansible

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}}"?

like image 756
Karl Avatar asked Aug 22 '16 05:08

Karl


People also ask

How do you specify variables in Ansible?

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.

What does Set_fact do in Ansible?

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.

What is variable precedence in Ansible?

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.


Video Answer


1 Answers

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.

like image 137
techraf Avatar answered Oct 21 '22 18:10

techraf