2

I have an Ansible Playbook where I have two JSON arrays:

List1:

[
  {
    "DistinguishedName": "CN=Warren\\, Oscar J.,OU=Users,OU=Finance Division,OU=Departments,DC=domain,DC=local",
    "Name": "Warren, Oscar J.",
    "ObjectClass": "user",
    "mail": "[email protected]"
  },
  {
    "DistinguishedName": "CN=Bodden\\, John B.,OU=Users,OU=Finance Division,OU=Departments,DC=domain,DC=local",
    "Name": "Bodden, John B.",
    "ObjectClass": "user",
    "mail": "[email protected]"
  }
]

List2:

[
  {
    "id": "ABC123",
    "userName": "[email protected]"
  },
  {
    "id": "DEF456",
    "userName": "[email protected]"
  }
]

I want to loop through the userName attribute of each user in List2, and if there is no object in List1 with a matching mail value, then I want to perform a task.

I really don't know how even to get started on doing this. I've tried the example below, which is producing errors:

- debug:
    var: "{{ item }}"
  loop: "{{ List2 }}"
  when: "{{ List1 | selectattr('mail', 'equalto', item.userName) }}"

How do I perform a simple loop with the "match" condition I am looking for?

3
  • Is it case-sensitive or not? Commented Sep 30, 2022 at 10:51
  • That's a good question. No, because we're matching email addresses, case insensitive is preferred. Commented Sep 30, 2022 at 13:21
  • I got it. The answer is no. But, JFYI, the reasoning is wrong. The part before the "@" could be case-sensitive. See Are email addresses case sensitive?. Commented Sep 30, 2022 at 13:44

1 Answer 1

1

Put the below declarations into the vars

mails: "{{ list1|map(attribute='mail')|map('lower')|list }}"
names: "{{ list2|map(attribute='userName')|map('lower')|list }}"

Q: "Perform task if no mail from list1 is matching userName from list2."

A: Iterate the difference between the lists

    - debug:
        msg: "Perform task: {{ item }}"
      loop: "{{ names|difference(mails) }}"

Example of a complete playbook for testing (data simplified, see mre)

- hosts: localhost

  vars:

    list1:
      - {DN: 'CN=Warren,OU=Users,OU=Finance', mail: [email protected]}
      - {DN: 'CN=Bodden,OU=Users,OU=Finance', mail: [email protected]}

    list2:
      - {id: ABC123, userName: [email protected]}
      - {id: DEF456, userName: [email protected]}
      - {id: GHI789, userName: [email protected]}

    mails: "{{ list1|map(attribute='mail')|map('lower')|list }}"
    names: "{{ list2|map(attribute='userName')|map('lower')|list }}"

  tasks:

    - debug:
        msg: "Perform task: {{ item }}"
      loop: "{{ names|difference(mails) }}"

gives (abridged)

  msg: 'Perform task: [email protected]'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.