Still working on my first playbook. I'm running into a problem when i try to access a JSON object.
I have a little script that checks for 2 groups to exist or not:
- name: Verify if the groups already exists in AD
register: lookupResult
win_shell: |
$groups = @()
Try{
$group = Get-ADGroup {{ GroupNameUpper }} | Select Name, DistinguishedName
$groups += [PSCustomObject]@{
Name = $group.Name
DistinguishedName = $group.DistinguishedName
Message = "Group already exists"
}
} catch {
$groups += [PSCustomObject]@{
Name = "{{ GroupNameUpper }}"
DistinguishedName = ""
Message = "Does not exist"
}
} Try {
$group = Get-ADGroup "{{ GroupNameUpper }}_GrpMgmt" | Select Name, DistinguishedName
$groups += [PSCustomObject]@{
Name = $group.Name
DistinguishedName = $group.DistinguishedName
Message = "Group already exists"
}
} catch {
$groups += [PSCustomObject]@{
Name = "{{ GroupNameUpper }}_GrpMgmt"
DistinguishedName = ""
Message = "Does not exist"
}
}
$Json = $groups | convertTo-Json
$Json
When i display the output, it looks like nicely formed JSON
- name: Show output
debug:
msg: "{{ lookupResult.stdout_lines|list }}"
It looks like so:
TASK [Show output] *************************************************************
ok: [server] => {
"msg": [
"[",
" {",
" \"Name\": \"R_UC_APP_Testapp\",",
" \"DistinguishedName\": \"\",",
" \"Message\": \"Does not exist\"",
" },",
" {",
" \"Name\": \"R_UC_APP_Testapp_GrpMgmt\",",
" \"DistinguishedName\": \"CN=R_UC_APP_testapp_GrpMgmt,whatever,DC=com\",",
" \"Message\": \"Group already exists\"",
" }",
"]"
]
}
In the UI, i can look at the JSON with the next task and it shows up fine there too:
- name: Process win_shell output
set_fact:
testOutput: "{{ lookupResult.stdout | from_json }}"
According to this page i should be able to access my object testoutput https://www.jonathanmedd.net/2019/07/returning-data-from-powershell-scripts-to-be-consumed-by-ansible-playbooks.html
- name: Inform that group already exists
debug:
msg: "Group {{ testOutput.Name }} ."
when: "'already exists' in lookupResult.stdout"
But it doesn't work and returns the error
"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'Name'
The only difference between my code and the example-code on the website, is the fact that my JSON-object has 2. But that shouldn't be an issue right?
I have tried many different things but i've come to a stall. Anyone can help me out please?
Thanks so much in advance!
EDIT: So i'm a bit closer thanks to the loop suggestion. However, this prints too much information. I just want to see the msg.
- name: Debug Loop
debug:
msg: "Group : {{ item.Name }} , {{ item.Message }} in domain {{ domainName }}"
loop: "{{ testOutput }}"