gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:31:11 26 4
gpt4 key购买 nike

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

这是有问题的代码:

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

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

最佳答案

考虑在你的 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的使用而不是 when : A when子句确定是否要运行命令,而 failed_when子句确定该命令是否被确定为失败。

关于bash - 在ansible中检查shell命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851931/

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