Construct a Distinguished Name with Ansible

Viewed 40

In my ansible playbook I have a variable defining the OU DN I'd like to create.

my_ou: "OU=win10,OU=workstations,OU=mycompany"
domain_root: "DC=example,DC=com"

I'd like to convert my_ou to a list and create each OU. The problem is that the loop does not know the path for each OU because it is an aggregation of the previous elements in the loop.

If I split my_ou on ',' and reverse the loop, I can print each OU in order of creation. I can set the name by using regex_replace. However, I don't know how to construct the path.

For example:

- name: create required OU's
  win_domain_ou: 
    name: "{{ my_ou | regex_replace('^OU=') }}"
    path: ???? should be all items to the right of the current {{ item }},{{ domain_root }}
    state: present
  loop: "{{ my_ou.split(',') | reverse | list }}"

So, to be clear, the path for OU=win10 should be OU=workstations,OU=mycompany,DC=example,DC=com

The OU=workstations path should be OU=mycompany,DC=example,DC=com

And so forth.

Thanks!

1 Answers

Declare the list of elements

elements: "{{ my_ou.split(',') + domain_root.split(',') }}" 

gives

elements:
  - OU=win10
  - OU=workstations
  - OU=mycompany
  - DC=example
  - DC=com

and use extended loop variables. For example,

    - debug:
        msg: "item: {{ item }} path: {{ elements[idx|int:]|join(',') }}"
      loop: "{{ my_ou.split(',')|reverse }}"
      loop_control:
          extended: true
      vars:
        idx: "{{ my_ou.split(',')|length - ansible_loop.index0 }}"

gives (abridged)

msg: 'item: OU=mycompany path: DC=example,DC=com'
msg: 'item: OU=workstations path: OU=mycompany,DC=example,DC=com'
msg: 'item: OU=win10 path: OU=workstations,OU=mycompany,DC=example,DC=com'

Example of a complete playbook for testing
- hosts: localhost

  vars:

    my_ou: "OU=win10,OU=workstations,OU=mycompany"
    domain_root: "DC=example,DC=com"
    elements: "{{ my_ou.split(',') + domain_root.split(',') }}"

  tasks:

    - debug:
        msg: "item: {{ item }} path: {{ elements[idx|int:]|join(',') }}"
      loop: "{{ my_ou.split(',')|reverse }}"
      loop_control:
          extended: true
      vars:
        idx: "{{ my_ou.split(',')|length - ansible_loop.index0 }}"
Related