josh
josh

Reputation: 45

Replacing value in set_fact

below is my sample yaml file

student:
  faculty: "Information Technology"
  code: "FC1412"
  abraham:
    country: "UK"
    age: "56"
  aaron:
    country: "UK"
    age: "56"
  chin:
    country: "UK"
    age: "56"

Below is my Ansible code

- slurp:
    src: {{ yaml_file_directory }}
  register: registerValue

- debug:
    msg: {{ registerValue['content'] | b64decode | from_yaml }}

It wil lgive output as below

student: {
  faculty: "Information Technology",
  code: "FC1412",
  abraham: {
    country: "UK",
    age: "56"
  },
  aaron:
    country: "UK",
    age: "56",
  },
  jamess: {
    country: "UK",
    age: "56"
  }
}

Is it possible to replace a value like aaron age 56 to 57. I wish your guys advice

Upvotes: 0

Views: 1294

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68064

The dictionaries are immutable in Ansible. You'll have to overwrite the whole dictionary. For example, put the updates into a dictionary

        update:
          aaron:
            age: "57"

and use the filter combine. Set recusive=True to keep all attributes

    - set_fact:
        student: "{{ student|combine(update, recursive=True) }}"
      vars:
        update:
          aaron:
            age: "57"

gives

  student:
    aaron:
      age: '57'
      country: UK
    abraham:
      age: '56'
      country: UK
    code: FC1412
    faculty: Information Technology
    jamess:
      age: '56'
      country: UK

Upvotes: 1

Related Questions