How to check whether an item is present in an Ansi

2019-04-21 23:54发布

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",
"user.email=foo@example.com"
]

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.

标签: ansible
3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-22 00:30

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=[^|]+")
查看更多
做自己的国王
3楼-- · 2019-04-22 00:33

With select and match (extend answer of udondan):

git_config_list.stdout_lines | select('match', 'user\.name=.+') | list
查看更多
Rolldiameter
4楼-- · 2019-04-22 00:50

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
查看更多
登录 后发表回答