需要注册循环的结果(task #1
)并检查相对于循环项何时command.results
stderr
不为空(task #2
),这样我就可以在新任务中使用此条件。
问题是:
when
条件task #2
不起作用,因为我不明白如何划分command.results
相对循环项。
有解决办法吗?
---
- name: "CHECK IF EXIST OPENVZ CONTAINER"
hosts: "projectname-OPENVZHOSTS"
gather_facts: yes
remote_user: root
vars:
openvz_check: "yes"
openvz_instances:
opwnvz_instance_1:
vmid: "119"
opwnvz_instance_2:
vmid: "118"
tasks:
- name: "Ping my hosts"
ping:
- name: "1. Register exist containers"
shell: echo $(vzlist -a {{ item.value.vmid }})
register: command
when: openvz_check == "yes"
loop: "{{ lookup('dict', openvz_instances) }}"
ignore_errors: yes
- name: "2. Create variable from command"
debug: msg="{{ command.results | map(attribute='stderr_lines') | list }}"
when:
- openvz_check == "yes"
- command.results | map(attribute='stderr') | list != ""
loop: "{{ lookup('dict', openvz_instances) }}"
ignore_errors: yes
- debug: msg="{{ command.results | map(attribute='stderr_lines') |list }}"
调试command.results | map(attribute='stderr') | list
:
ok: [projectname-OPENVZHOST-S1] => {
"msg": [
[],
[]
]
}
请根据您所见提出建议或解决方案。或者我需要研究什么。
问候
PS:有一个想法,创建文件夹,然后检查它是否存在,但不知道如何将字典与结果关联起来
答案1
您想使用长度筛选。
- command.results | map(attribute='stderr') | list | length != 0
或者更好的是,直接访问 stderr。
- command.stderr != ""
我使用的完整剧本在这里:
---
- name: test playbook
hosts: all
vars:
my_list_var: []
tasks:
- name: debug
debug:
msg: "list is empty"
when:
- my_list_var | list | length == 0
- name: ls command
command: "ls -l /tmp"
register: result
- name: debug 2
debug:
msg: "no errors"
when: result.stderr == ""