Converting string to integer in Ansible Playbook
here's what I did to make it work:
---
- name: answer serverfault
hosts: all
become: yes
tasks:
- name: Get message_count
shell: ls /tmp/empty | wc -l
register: tmp_count
delegate_to: localhost
- debug: var=tmp_count.stdout
- name: do something else when tmp_count.stdout == 0
shell: echo "I am doing it"
delegate_to: localhost
when: tmp_count.stdout | int == 0
and here's the playbook run result:
ripper@mini-ripper:~/Devel/ansible$ ansip ./test_playbook.yml -i localhost,
PLAY [answer serverfault] **************************************************************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
[WARNING]: Platform linux on host localhost is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
ok: [localhost]
TASK [Get message_count] ******************************************************************************************************************************************************************************************
changed: [localhost -> localhost]
TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
"tmp_count.stdout": "0"
}
TASK [do something else when tmp_count.stdout == 0] ***************************************************************************************************************************************************************
changed: [localhost -> localhost]
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
so to recap:
- you should check if the register variable isn't more complex structure - it usually is
- you don't need another custom fact
- you need to convert your variable without using
{{ }}
inwhen
condition