在ansible中检查shell命令的输出

时间:2016-08-09 13:18:32

标签: bash shell ansible

我正在尝试编写一个运行shell管道的Ansible脚本,并根据该管道的输出确定是否终止playbook的执行。

以下是有问题的代码:

  - name: Check if the number of HITACHI devices is equal to 1
    shell: lsscsi | grep HITACHI | awk '{print $6}' | wc -l
    register: numOfDevices
    when: numOfDevices|int  == 1

这是错误:

{  
   "failed":true,
   "msg":"The conditional check 'numOfDevices|int  == 1' failed.  
The error was: error while evaluating conditional (numOfDevices|int  == 1): 'numOfDevices' is undefined\n\nThe error appears to have been in '/etc/ansible/config/test.yml': line 14, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Check if the number of HITACHI devices is equal to 1\n    ^ here\n"
}

有人能告诉我可能是什么问题吗?

1 个答案:

答案 0 :(得分:6)

考虑在shell命令中进行比较:

  - name: Check if the number of HITACHI devices is equal to 1
    shell: test "$(lsscsi | awk '/HITACHI/ { count++ } END { print count }')" -eq 1

此处根本不需要使用register,因为默认failedWhen是指令的退出状态非零。

如果你 想要使用register,那么:

  - name: Check if the number of HITACHI devices is equal to 1
    shell: lsscsi | awk '/HITACHI/ { count++ } END { print count }'
    register: countHitachiDevices
    failed_when: int(countHitachiDevices.stdout) != 1 

请注意使用failed_when而不是whenwhen子句确定是否要运行命令,而failed_when子句确定是否命令确定已失败。