Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an item is present in an Ansible array?

Tags:

ansible

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

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

Ansible stores the result of this command in the git_config_list variable, and one of the items is stdout_lines, containing the output of the command in an array of entries, e.g.

[
"user.name=Foo Bar",
"[email protected]"
]

How can I check whether a certain value is already set, e.g. for verifying that user.name has a value?

Is there a way to call something like contains on the array, combined with a regular expression, allowing me to find the value I'm looking for? Or do I have to loop over the stdout_lines entries to find what I'm looking for?

An example on how to do something like this would be appreciated.

like image 598
nwinkler Avatar asked Mar 20 '15 07:03

nwinkler


3 Answers

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
like image 148
Kashyap Avatar answered Nov 16 '22 08:11

Kashyap


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=[^|]+")
like image 6
udondan Avatar answered Nov 16 '22 07:11

udondan


With select and match (extend answer of udondan):

git_config_list.stdout_lines | select('match', 'user\.name=.+') | list
like image 4
simohe Avatar answered Nov 16 '22 07:11

simohe