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": "Oscar.Warren@domain.local"
  },
  {
    "DistinguishedName": "CN=Bodden\\, John B.,OU=Users,OU=Finance Division,OU=Departments,DC=domain,DC=local",
    "Name": "Bodden, John B.",
    "ObjectClass": "user",
    "mail": "John.Bodden@domain.local"
  }
]

List2:

[
  {
    "id": "ABC123",
    "userName": "john.bodden@domain.local"
  },
  {
    "id": "DEF456",
    "userName": "oscar.warren@domain.local"
  }
]

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?

user1913559
  • 301
  • 1
  • 13
  • Is it case-sensitive or not? – Vladimir Botka Sep 30 '22 at 10:51
  • That's a good question. No, because we're matching email addresses, case insensitive is preferred. – user1913559 Sep 30 '22 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?](https://stackoverflow.com/questions/9807909/are-email-addresses-case-sensitive). – Vladimir Botka Sep 30 '22 at 13:44

1 Answers1

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: Oscar.Warren@domain.local}
      - {DN: 'CN=Bodden,OU=Users,OU=Finance', mail: John.Bodden@domain.local}

    list2:
      - {id: ABC123, userName: john.bodden@domain.local}
      - {id: DEF456, userName: oscar.warren@domain.local}
      - {id: GHI789, userName: foo.bar@domain.local}

    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: foo.bar@domain.local'
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63