How to check if an element is present in an Ansible array?

Let's say I have the following example storing all git config values ​​in Ansible variable:

 - shell: git config --global --list register: git_config_list 

Ansible stores the result of this command in the variable git_config_list , and one of the elements is stdout_lines , containing the output of the command in an array of records, for example

 [ "user.name=Foo Bar", "user.email=foo@example.com" ] 

How to check if a specific value is set, for example. to verify that user.name matters?

Is there a way to call something like contains in an array in combination with a regular expression that allows me to find the value I'm looking for? Or do I need to stdout_lines over stdout_lines entries to find what I'm looking for?

It's nice to appreciate an example of how to do something like this.

+8
ansible
source share
2 answers

In theory, this should be possible by combining match and select filters. The latter returns only those list items that pass another filter. Then you can check the length of the result.

In theory. I just tested it, and I can't get it to work. In general, the select filter (as well as the reject filter) returns a string of the type <generator object _select_or_reject at 0x10531bc80> even with simple filters, such as an example from documents with odd . So far, no solution has been found. You may have more success.

Although you could just join add your list to the string and then do a string search using match . Although it is ugly, it works.

 git_config_list.stdout_lines | join("|") | match("user.name=[^|]+") 
+5
source share

Simple python in will work 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}}'" 

Overall ansible terrible for programming. Try to do as much as you can outside the textbook, and write only the logic of orchestration inside the textbook. Here are some examples of how you can do this using the --get git option.

 - 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 
+15
source share

All Articles