bash 在ansible中检查shell命令的输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38851931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:01:14  来源:igfitidea点击:

Checking output of a shell command in ansible

bashshellansible

提问by Omri

I'm trying to write an Ansible script that runs a shell pipeline, and determines whether to terminate the playbook's execution based on that pipeline's output.

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

Here is the problematic code:

这是有问题的代码:

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

Here is the error:

这是错误:

{  
   "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"
}

Can someone tells me what could be the issue?

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

回答by Charles Duffy

Consider doing the comparison in your shell command:

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

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

You don't need to use registerat all here, since the default failedWhenis when the exit status of a command is nonzero.

您根本不需要register在这里使用,因为默认值failedWhen是命令的退出状态为非零时。



If you didwant to use register, however:

但是,如果您确实想使用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 

Note the use of failed_wheninstead of when: A whenclause determines if a command is going to be run at all, whereas a failed_whenclause determines whether that command is determined to have failed.

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