如何测试 stderr 是否非空::
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: not test_myscript.stderr
所以如果没有错误我可以阅读::
TASK: [deploy | debug msg='critp is Ok] *******
ok: [vagrant] => {
"msg": "myscritp is Ok"
}
如果 stderr 不为空,则会发生 FATAl
错误。
最佳答案
(ansible 2.9.6 ansible-lint 5.3.2)
参见 ansible-lint rules 。以下条件会导致错误:'empty-string-compare:不要与空字符串进行比较
'
when: test_myscript.stderr != ""
正确的语法是
when: test_myscript.stderr | length > 0
引用自source code
<小时/>Use
when: var|length > 0
rather thanwhen: var != ""
(or ' 'converselywhen: var|length == 0
rather thanwhen: var == ""
)
注释
- 测试空的裸变量,例如
- debug:
msg: "Empty string '{{ var }}' evaluates to False"
when: not var
vars:
var: ''
- debug:
msg: "Empty list {{ var }} evaluates to False"
when: not var
vars:
var: []
给予
msg: Empty string '' evaluates to False
msg: Empty list [] evaluates to False
- 但是,测试非空裸变量字符串取决于 CONDITIONAL_BARE_VARS 。设置
ANSIBLE_CONDITIONAL_BARE_VARS=false
条件可以正常工作,但设置ANSIBLE_CONDITIONAL_BARE_VARS=true
条件将失败
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var
vars:
var: 'abc'
给出
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check 'var' failed. The error was: error while
evaluating conditional (var): 'abc' is undefined
显式转换为 bool 值可防止错误,但计算结果为 False,即始终会被跳过(除非 var='True'
)。使用过滤器 bool
时,选项 ANSIBLE_CONDITIONAL_BARE_VARS=true
和 ANSIBLE_CONDITIONAL_BARE_VARS=false
无效
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var|bool
vars:
var: 'abc'
给出
skipping: [localhost]
- include_tasks: teardown.yml
when: teardown
- include_tasks: provision.yml
when: not teardown
" based on a variable you define as a string (with quotation marks around it):"
在 Ansible 2.7 及更早版本中,如果拆解:'true',则上述两个条件分别评估为 True 和 False
在 Ansible 2.7 及更早版本中,如果拆解:'false',则这两个条件都被评估为 False
在 Ansible 2.8 及更高版本中,您可以选择禁用条件裸变量,因此when:teardown 始终评估为 True,当teardown 是非空字符串(包括“真”或“假”)
Expect that this setting eventually will be deprecated after 2.12
关于Ansible:如何测试注册变量不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912726/