给定以下剧本:
---
- name: Check if log directory exists - Step 1
stat: path="{{ wl_base }}/{{ item.0.name }}/{{ wl_dom }}/servers/{{ item.1 }}/logs" get_md5=no
register: log_dir
with_subelements:
- wl_instances
- servers
- name: Check if log directory exists - Step 2
fail: msg="Log directory does not exists or it is not a symlink."
failed_when: >
log_dir.results[0].stat.islnk is not defined
or log_dir.results[0].stat.islnk != true
or log_dir.results[0].stat.lnk_source != "{{ wl_base }}/logs/{{ wl_dom }}/{{ item.1 }}"
with_subelements:
- wl_instances
- servers
使用以下变量:
---
wl_instances:
- name: aservers
servers:
- AdminServer
- name: mservers
servers:
- "{{ ansible_hostname }}"
第二个任务当前仅使用两个可能结果之一(
results[0]
)。我的问题是:如何遍历
log_dir.results
中存储的所有可用项目?输出
debug:hostvars[inventory_hostname]
的示例如下: "log_dir": {
"changed": false,
"msg": "All items completed",
"results": [
{
"changed": false,
"invocation": {
"module_args": "path=\"/path/to/servers/aservers/domain/AdminServer/logs\" get_md5=no",
"module_name": "stat"
},
"item": [
{
"name": "aservers"
},
"AdminServer"
],
"stat": {
...
"lnk_source": "/path/to/logs/domain/AdminServer",
...
}
},
{
"changed": false,
"invocation": {
"module_args": "path=\"/path/to/servers/mservers/domain/servers/some_hostname/logs\" get_md5=no",
"module_name": "stat"
},
"item": [
{
"name": "mservers"
},
"some_hostname"
],
"stat": {
...
"lnk_source": "/path/to/logs/domain/some_hostname",
...
最佳答案
将结果循环到数组(由[]表示)中,方法如下:
with_items: somelist
或者如果它是一个包含列表的字典,在这种情况下
with_items: log_dir.results
请注意,这也可以写成
with_items: log_dir['results']
所以在你的任务中
- name: Check if log directory exists - Step 2
fail: msg="Log directory does not exists or it is not a symlink."
failed_when: >
item.stat.islnk is not defined
or item.stat.islnk != true
or item..stat.lnk_source != "{{ wl_base }}/logs/{{ wl_dom }}/{{ item.1 }}"
with_items: log_dir.results
http://docs.ansible.com/playbooks_loops.html#standard-loops中提供了更多信息和示例。
这里最主要的是您只想访问注册变量的一部分。
关于loops - ansible:如何遍历所有已注册的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27015721/