Marek
Marek

Reputation: 126

How to handle output which can be string or list in Ansible

Hello i got the following issue. Basically i run the query on AD using the PS command to get the list of OUs. Then i want to compare my variable with that list. this is PS command :

- name: PS - Pull SITE Sub OUs from AD for specific application 
  win_command: powershell - 
  args:
    stdin: "Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchScope 1  -SearchBase 'OU=SITES,DC=xxx,DC=int' -Server domain.int | select-object name | ConvertTo-Json"
  become: yes
  register: ou_site_out

output when only single OU exists: changed: [host] => {"changed": true, "cmd": "powershell -", "delta": "0:00:00.913282", "end": "2020-02-13 04:04:26.289368", "rc": 0, "start": "2020-02-13 04:04:25.376086", "stderr": "", "stderr_lines": [], "stdout": "{\r\n \"name\": \"OU1\"\r\n}\r\n", "stdout_lines": ["{", " \"name\": \"OU1\"", "}"]}

output when multiple OUs exist:

changed: [host] => {"changed": true, "cmd": "powershell -", "delta": "0:00:00.875002", "end": "2020-02-13 04:25:49.409360", "rc": 0, "start": "2020-02-13 04:25:48.534358", "stderr": "", "stderr_lines": [], "stdout": "[\r\n {\r\n \"name\": \"OU1\"\r\n },\r\n {\r\n \"name\": \"OU2\"\r\n },\r\n {\r\n \"name\": \"OU3\"\r\n }]"

then i set the fact from the stdout as follows:

- name: Set list of  OUs as facts
   set_fact:
      ou_site_list: "{{ ou_site_out.stdout | from_json }}"

Problem starts here. If the ou_site_out contains only single item ( only 1 OU exists ) then ou_site_list will return string

TASK [debug] *******************************************************************
ok: [host] => {
    "ou_site_list": {
        "name": "OU1"

but if there are multiple OUs i get the list :

TASK [debug] *******************************************************************
ok: [host] => {
    "ou_site_list": [
        {
            "name": "OU1"
        },
        {
            "name": "OU2"
        },
        {
            "name": "OU3"}]

How can i then handle the ou_site_list if i dont know whether it will be a list of string ?

Thanks for any help

Upvotes: 0

Views: 304

Answers (1)

mdaniel
mdaniel

Reputation: 33203

Based solely on the examples you provided, you can know that by looking at the leading character of the output: if it is [, then list, else it needs to be repackaged into a list. The type_debug filter is probably the more portable way of approaching that problem:

- set_fact:
    ou_site_list: ["a","b"]
  # then you can comment that one and uncomment this one
  # to see how it behaves in each case:
  # ou_site_list: "alpha"
- set_fact:
    ou_site_type: '{{ ou_site_list | type_debug }}'
- debug:
    msg: it's a list
  when: ou_site_type == 'list'
- debug:
    msg: it is not a list, and needs to be wrapped in one
  when: ou_site_type != 'list'
  # it's type is 'AnsibleUnicode' but for your purposes
  # just "not a list" is probably good enough

Upvotes: 2

Related Questions