ansibleansible-2.xansible-facts

Ansible: Remove item from dict


I have a situation where i am trying to remove the item from a list. but i am not getting expected result. Please help me what I am doing wrong here?

here is the list :

    "get_ec2_id.instances[0].tags": {
    "Name": "test-db-system-2",
    "aws:cloudformation:logical-id": "DBInstance",
    "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-1:123456789012:stack/test-db-system-2/0115v0a0-5d44-17e8-a024-503ama4a5qd1",
    "aws:cloudformation:stack-name": "test-db-system-2",
    "dbsystem:stack": "test-db-system-2",
    "dbsystem:type": "db"
}

}

I am trying to remove the all "aws:cloudformation" tags from a list using below filter:

    "{{ get_ec2_id.instances[0].tags | reject('search','aws:') | list }}"

I am getting the below result:

    ok: [10.52.8.101] => {
"instances_tags": [
    "dbsystem:type",
    "dbsystem:stack",
    "Name"
]
    }

but I am expected below result :

      "instances_tags": [
    "dbsystem:stack": "test-db-system-2",
    "dbsystem:type": "db"
    "Name" : "test-db-system-2",
]
  }

Help me to solve the issue.


Solution

  • More generic solution where input is a dict and blacklist is a list:

    ---
    - set_fact:
        blacklist:
          - bad1
          - bad2
    - set_fact:
        output: {}
    - name: remove blacklisted items from input
      set_fact:
        output: "{{ output | combine({item.key: item.value}) }}"
      when: item.key not in blacklist
      loop: "{{ input | dict2items }}"