Ansible任务在条件为时失败

Ansible任务在条件为时失败,ansible,jinja2,amazon-ecs,Ansible,Jinja2,Amazon Ecs,我的Ansible任务因false when条件而失败(仅当“when”条件为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

我的Ansible任务因false when条件而失败(仅当“when”条件为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    
我的when条件格式是否有问题,因为我已经尝试了各种条件,如>0和>=1,但运气不佳,因为它仍然失败(我的ECS群集中没有任务),而且 AWS CLI命令返回

aws ecs list-tasks --cluster mycluster --query length(taskArns[*])
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


请参阅此处的更多信息:

问题在于您正在将
字符串(在注册输出中)与
int
(在when子句中)进行比较。您应该将
when
条件更改为:

when:ecs\u tasks.stdout!="0"
此外,您不需要第二个任务来验证失败,因为在第一个任务的
条件为:

-name:“检查是否存在任何任务”
命令:aws ecs列表任务--cluster mycluster--查询长度(taskArns[*])
注册:ecs_任务
失败时:ecs_tasks.stdout!="0"
旁注

  • 如果命令返回代码仍然有意义,通常最好还是检查它,这样就不会不必要地解析可能被误解的输出。在您的情况下,我想您可以轻松地将条件更改为(注意,
    rc
    是一个
    int
    ):

    当:ecs_tasks.rc!=0或ecs_tasks.stdout!="0" 如果您的命令有多个可被视为成功的返回代码(例如
    0
    2
    ),则可以更改为

    当:ecs_tasks.rc不在[0,2]或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"
    }
    

OP不想检查注册的var是否为空,但它不包含“0”。
$ ansible localhost -m debug -a msg="{{ 'whatever' | int }}"
localhost | SUCCESS => {
"msg": "0"
}