Reputation: 123
In my case, I have a playbook similar to below one to get the list of profiles, to display the list of profiles and fail the task when a profile specified by the user through survey/ as extra variable (var name is: userinput ) exists in the available profiles.
---
- hosts: localhost
gather_facts: no
become: true
tasks:
- name: Getting the list of Profiles
shell: some command to get the list of profiles
register: output
- name: Printing the list of profiles
debug:
msg: "{{output.stdout_lines}}"
- name: Failing the task when the specified profile already exists
fail:
msg: The Profile {{userinput}} already exists
when: 'Profile={{userinput}}' in output.stdout
...
Let us say the list of profiles displayed is as follows.
"msg":[
"Profiles_List"
" Profile=TESTPROFILE1",
" Profile=TESTPROFILE2",
" Profile=TESTPROFILE3"
]
The problem here is, even when userinput is given as "TESTPROFILE", it is finding the match (partially) and failing the last task of the playbook.
The requirement is that the last task in the playbook should fail when the exact match is found (that is when one of exact values avaible in the list is specified by the user)
Can someone please let me know how to achieve this ?
Upvotes: 1
Views: 563
Reputation: 68034
In your code, output.stdout
is very probably a string not a list. This is the reason the condition doesn't work. Parse the list of the profiles first. Given the list of the profiles
Profiles_List:
- Profile=TESTPROFILE1
- Profile=TESTPROFILE2
- Profile=TESTPROFILE3
the condition below works as expected
- name: Fail when profile already exists
fail:
msg: "The Profile {{ userinput }} already exists"
when: _profile in Profiles_List
vars:
_profile: "Profile={{ userinput }}"
Q: "Parse the list of profiles."
A: Given the data
output.stdout_lines:
- Profiles_List
- ' Profile=TESTPROFILE1'
- ' Profile=TESTPROFILE2'
- ' Profile=TESTPROFILE3'
Profiles: "{{ output.stdout_lines[1:]|map('trim')|list }}"
gives
Profiles:
- Profile=TESTPROFILE1
- Profile=TESTPROFILE2
- Profile=TESTPROFILE3
Profiles_List: "{{ Profiles|map('split', '=')|map('last')|list }}"
gives
Profiles_List:
- TESTPROFILE1
- TESTPROFILE2
- TESTPROFILE3
Profiles_Dict: "{{ Profiles_List|map('community.general.dict_kv', 'profile')|list }}"
gives
Profiles_Dict:
- profile: TESTPROFILE1
- profile: TESTPROFILE2
- profile: TESTPROFILE3
Upvotes: 2