senthil Kumar B.K
senthil Kumar B.K

Reputation: 35

Ansible: How to Filter a few element from list of dictionary

I have yaml file as below,

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa
  namespace: default
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: job-master

---  
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: job-master-1
  namespace: namespace1
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: job-master
subjects:
- kind: ServiceAccount
  name: sa
  namespace: default

So i converted this yaml file to list of dictionary with below code,

value: "{{ lookup('file','a.yml') | from_yaml_all | list }}"

Now my requirement is that if metadata does not have element namespace , it has to fail at same time ,it should skip whole dictoanry when kind: ClusterRole

any idea how to do it in ansible?

i try with below code, it is not giving expected output.

    - name: Check if namespace is defined or not in yaml file
  fail:
    msg: "{{ item.metadata.namespace }} namespace is not defined"
  when: not item.metadata.namespace
  loop: "{{ value   }}"
  loop_control:
    label: "{{ item.metadata }}"
  when: item.kind!='ClusterRole' 

Upvotes: 0

Views: 159

Answers (1)

Zeitounator
Zeitounator

Reputation: 44605

In a nutshell:

- name: Fail if any entry does not have a namespace for kind <> ClusterRole
  vars:
    # List of problematic entries in your value list
    problem_list: "{{ value | rejectattr('kind', '==', 'ClusterRole') | rejectattr('metadata.namespace', 'defined') | list }}"
  fail:
    msg: "One or more entries do not have a namespace defined in metadata"
  when: problem_list | length > 0

Upvotes: 2

Related Questions