How to check whether an item is present in an Ansible array?
In theory this should be possible by combining the filters match
and select
. The latter returns only those list elements which pass another filter. Then you could test for the length of the result.
In theory. I just tested it and I can't get it to work. In general the select
(as well as the reject
) filter returns a string like <generator object _select_or_reject at 0x10531bc80>
even with simple filters like the example from the docs with odd
. Wasn't able to find a solution yet. Maybe you have more success.
Though you could simply join
your list to a string and then search in the string with match
. While it's ugly, it works.
git_config_list.stdout_lines | join("|") | match("user.name=[^|]+")
With select and match (extend answer of udondan):
git_config_list.stdout_lines | select('match', 'user\.name=.+') | list
Simple python in
would do just fine, NOTE I use stdout
instead of stdout_lines
:
- debug: git_config_list contains user.name
when: "'user.name=' in '{{git_config_list.stdout}}'"
All in all ansible
is horrible for programming. Try to do as much as you can outside the playbook and write only the orchestration logic inside the playbook. Here are a few examples how you can do it using --get
option of git
.
- hosts: localhost
tags: so
gather_facts: False
tasks:
- shell: git config --global --get user.name
register: g
changed_when: False
failed_when: False
- debug: msg="config has user.name"
when: "0 == {{g.rc}}"
- hosts: localhost
tags: so
gather_facts: False
tasks:
- name: assert user.name is set
shell: git config --global --get user.name
changed_when: False
# git config --global --unset user.name
# ansible pb.yml -t so
# git config --global --add user.name 'Kashyap Bhatt'
# ansible pb.yml -t so