问题
How can I test that stderr is non empty::
- 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
So if there is no error I could read::
TASK: [deploy | debug msg='critp is Ok] *******
ok: [vagrant] => {
"msg": "myscritp is Ok"
}
In case the stderr is not empty a FATAl error occurs.
回答1:
You can check for empty string (when stderr is empty)
- 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: test_myscript.stderr == ""
If you want to check for fail:
- debug: msg='myscritp has error: {{test_myscript.stderr}}'
when: test_myscript.stderr != ""
Also look at this stackoverflow question
回答2:
See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string
when: test_myscript.stderr != ""
Correct syntax and also "Ansible Galaxy Warning-Free" option is
when: test_myscript.stderr | length > 0
Update 1. Test bare variable
Quoting from Current rule says:
Use
when: varrather thanwhen: var != ""(or ' 'converselywhen: not varrather than ``when: var == ""`
For example
- 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: []
give
"msg": "Empty string '' evaluates to False"
"msg": "Empty list [] evaluates to False"
Update 2. Remove bare var handling from conditionals
See Ansible 2.8 Release notes
Since Ansible 2.8 bare variables don't work in conditionals anymore. For example
- debug:
msg: "The string '{{ my_var }}' evaluates to True"
when: my_var
vars:
my_var: 'abcde'
gives
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'my_var' failed. The error was: error while evaluating conditional (my_var): 'abcde' is undefined
See CONDITIONAL_BARE_VARS
$ ansible-config dump | grep BARE
CONDITIONAL_BARE_VARS(default) = True
回答3:
when: myvar | default('', true) | trim != ''
I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.
来源:https://stackoverflow.com/questions/36912726/how-to-test-that-a-registered-variable-is-not-empty