gpt4 book ai didi

Ansible 任务因 when 条件而失败

转载 作者:行者123 更新时间:2023-12-04 15:25:13 24 4
gpt4 key购买 nike

我的 Ansible 任务在条件为 false 时失败(只有当“when”条件为真时任务才应该失败)

我的剧本

    - 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

我的 when Condition 格式有问题吗,因为我已经尝试了各种条件,比如 >0 和 >=1,但运气不好,因为它仍然失败(我的 ECS 集群中不存在任务),而且AWS CLI 命令返回

aws ecs list-tasks --cluster mycluster --query length(taskArns[*])
0

最佳答案

问题是您正在将 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"

    如果你的命令有多个可以认为是成功的返回码(例如02),你可以改为

    failed_when: ecs_tasks.rc not in [0,2] or ecs_tasks.stdout != "0"
  • 您可能想将输出比较转换为 int,例如:

    ecs_tasks.stdout | int != 0

    这应该可行,但请注意 sdtout 中的任何字符串值不能作为 int 解析将导致 O,例如:

    $ ansible localhost -m debug -a msg="{{ 'whatever' | int }}"
    localhost | SUCCESS => {
    "msg": "0"
    }

关于Ansible 任务因 when 条件而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62400819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com