Reputation: 673
Let's say the df command return the following.
[john.doe@localhost ~]# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 372607 170989 177862 50% /boot
/dev/sda2 129774 6994 122780 6% /
With Ansible, I can use the shell module to capture the available value for /dev/sda1 (177862).
---
- hosts: localhost
tasks:
- name: df command
shell: df | grep sda1 | awk '{print $4}'
register: out
- name: standard out
debug:
msg: "{{ out.stdout }}"
- name: type
debug:
msg: "{{ out.stdout | type_debug }}"
Which will show the type is AnsibleUnsafeText. If I do the same with gather_facts, AnsibleUnsafeText is also returned. I can't figure out how to get the type to be an integer instead of AnsibleUnsafeText.
TASK [standard out]
ok: [localhost] => {
"msg": "122780"
}
TASK [type]
ok: [localhost] => {
"msg": "AnsibleUnsafeText"
}
I tried using the int filter.
---
- hosts: localhost
tasks:
- name: df command
shell: df | grep sda1 | awk '{print $4}'
register: out
- name: int filter
set_fact:
foo: "{{ out.stdout | int }}"
- name: type
debug:
msg: "{{ foo | type_debug }}"
But even with the int filter, the type remains AnsibleUnsafeText.
TASK [type]
ok: [localhost] => {
"msg": "AnsibleUnsafeText"
}
The reason I want to the type to be int is so that I can compare integers, like this.
- name: do something
debug:
msg: do something
when: df_available > '123456'
Upvotes: 9
Views: 12868
Reputation: 4554
This "{{ out.stdout | int }}"
will cast out.stdout
to an int
, but as it is a template, it will then cast it back to string
, as a template always returns a string.
That is just what templates do. They evaluate the template code and then generate text and return it.
If you want to use the variable to compare it as int
, you need to cast it every time, you use it:
- name: do something
debug:
msg: do something
when: (df_available | int) > 123456
Upvotes: 13