“我的Ansible任务”在出现条件时失败,错误为false(仅当“当”条件为true时任务才失败)
我的剧本
- name: 'Check if any task is existing'
command: aws ecs list-tasks --cluster mycluster --query length(taskArns[*])
register: ecs_tasks
- name: 'Fail playbook if some task is already existing in cluster'
fail:
msg: "There is already an existing task in mycluster"
when: ecs_tasks.stdout != 0
- name: 'Create Ranger task'
command: create ECS task
register: ecs_task
输出
"stderr": "",
"stderr_lines": [],
"stdout": "0",
"stdout_lines": [
"0"
]
}
TASK [Fail playbook if some task is already existing in cluster] ***************
task path: /home/somepath/Task.yml:35
fatal: [127.0.0.1]: FAILED! => {
"changed": false,
"msg": "There is already an existing task in mycluster"
}
PLAY RECAP *********************************************************************
09:09:38 127.0.0.1 : ok=5 changed=4 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
我的Condition条件格式是否存在问题,因为我尝试了各种条件,例如> 0和> = 1,但是运气不好,因为它仍然失败(我的ECS群集中没有任务),并且 AWS CLI命令返回
aws ecs list-tasks --cluster mycluster --query length(taskArns[*])
0
答案 0 :(得分:2)
问题是您正在将string
(在您的注册输出中)与int
(在when子句中)进行比较。您应该将when
的条件更改为:
when: ecs_tasks.stdout != "0"
此外,您不需要第二项任务来验证是否失败,因为您可以在第一项任务中轻松使用failed_when
条件:
- name: 'Check if any task is existing'
command: aws ecs list-tasks --cluster mycluster --query length(taskArns[*])
register: ecs_tasks
failed_when: ecs_tasks.stdout != "0"
旁注:
通常,最好还是检查命令返回代码是否仍然有意义,以免不必要地解析可能被误解的输出。就您而言,我想您可以轻松地将条件更改为(请注意,rc
是int
):
failed_when: ecs_tasks.rc != 0 or ecs_tasks.stdout != "0"
如果您的命令有多个返回代码可以被视为成功(例如0
和2
),则可以更改为
failed_when: ecs_tasks.rc not in [0,2] or ecs_tasks.stdout != "0"
您可能会想将输出比较强制转换为int
,例如:
ecs_tasks.stdout | int != 0
这应该可以,但是请注意,sdtout
中任何不能作为整数解析的字符串值都将导致O
,例如:
$ ansible localhost -m debug -a msg="{{ 'whatever' | int }}"
localhost | SUCCESS => {
"msg": "0"
}
答案 1 :(得分:0)
以下任何一种都可以工作:
- name: 'Fail playbook if some task is already existing in cluster'
fail:
msg: "There is already an existing task in mycluster"
when: ecs_tasks.stderr | length > 0
或
- name: 'Fail playbook if some task is already existing in cluster'
fail:
msg: "There is already an existing task in mycluster"
when: ecs_tasks.stderr != ""
在此处详细介绍:How to test that a registered variable is not empty?