How to assign a computed variable from one yml file to another yml file in Ansible?

Viewed 81

I have an yml file, all.yml which has a dictionary defined as,

my_dict:
variable1: true
variable2: some_string
variable3: "dummy"

From another yml file, I am computing the variable3. Here, how do I assign the newly computed variable3 to the one defined in all.yml?

my_dict.variable3: "{{ new_variable3 }}" 

The above statement throws an error, "The variable name 'my_dict.variable3' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."

2 Answers

EDIT

this way to do does the job:

# file 1.yml
my_dict:
  variable1: true
  variable2: some_string
  variable3: "dummy"

# file 2.yml
my_dict:
  variable3: "newdummy"

- name: test 
  hosts: localhost
  vars_files:
    - 1.yml
  tasks:
    - name: display my_dict before modification
      debug:
        var: my_dict

    - name: apply modification to my_dict
      set_fact:
        my_dict: "{{ my_dict | combine(_temp.my_dict) }}"
      vars:
        _temp: "{{ lookup('file','2.yml') | from_yaml }}"

    - name: display my_dict after modification
      debug:
        var: my_dict

result:

TASK [display my_dict before modification] *********************************************************
ok: [localhost] => 
  my_dict:
    variable1: true
    variable2: some_string
    variable3: dummy


TASK [display my_dict before modification] **********************************************
ok: [localhost] => 
  my_dict:
    variable1: true
    variable2: some_string
    variable3: newdummy

For my problem, I tried the below method and it worked. so, to modify or re-assign the variable3 in one yml file from another yml file, I need to do

-name: assign variable3
 set_fact:
   my_dict:
      variable3: "{{ new_variable3 }}"
Related