Search code examples
ansiblejinja2ansible-2.x

How can I replace a value of dictionary based on a key condition in the same YAML file?


I have a YAML values file and I want to update the particular value of a dictionary based on its key via Ansible playbooks.

input.yaml

operator:
  operator:
    replicaCount: 1
    env:
      - name: namespace1
        value: abc
      - name: namespace2
        value: xyz
    resources:
      requests:
        cpu: 200m
        memory: 256Mi
        ephemeral-storage: 500Mi
  console:
    replicaCount: 1

I want update the value of namespace1 as test under env array in the input.yaml.

Expected Result in input.yaml

operator:
  operator:
    replicaCount: 1
    env:
      - name: namespace1
        value: test
      - name: namespace2
        value: xyz
    resources:
      requests:
        cpu: 200m
        memory: 256Mi
        ephemeral-storage: 500Mi
  console:
    replicaCount: 1

Solution

  • According your description I wonder if you could use the update_fact module – Update currently set facts? It is intended for updating variables and one of the documented Examples seems to be similar to yours.

    Based on the former (or already) given answer and Ansible: How to update or change a value in a nested dictionary?, a minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - include_vars:
          file: input.yaml
          name: input
    
      - ansible.utils.update_fact:
          updates:
            - path: input.operator.operator.env[0]
              value: { name: namespace1, value: test}
        register: updated
    
      - debug:
          var: updated
    
      - copy:
          dest: output.yaml
          content: "{{ updated.input | to_nice_yaml(indent=2) }}"
    

    will result into the requested output.yaml file

    operator:
      console:
        replicaCount: 1
      operator:
        env:
        - name: namespace1
          value: test
        - name: namespace2
          value: xyz
        replicaCount: 1
        resources:
          requests:
            cpu: 200m
            ephemeral-storage: 500Mi
            memory: 256Mi
    

    Please take note that even if using update_fact module – Update currently set facts

    Variables are not modified in place, instead they are returned by the module.

    and that is the expected behavior.

    Further Q&A