Reputation: 455
I need to convert a string "1933" to integer
in Ansible PB.
Code:
- set_fact:
parent_region2: "1933"
- debug:
msg: "{{ parent_region2 | int }}"
Expected Output:
"msg": 1933
Actual Output:
"msg": "1933"
Though the Actual Output have braces, it still shows as int when passing a type_debug
into the code
Code with type_debug
:
- set_fact:
parent_region2: "1933"
- debug:
msg: "{{ parent_region2 | int | type_debug}}"
Output:
"msg": "int"
Please help
Upvotes: 2
Views: 15412
Reputation: 68034
It's an integer when type_debug tells you so. The quotes are not part of the integer, of course. The format of the output depends on the callback plugin. For example, the default callback plugin (see ansible-doc -t callback default
) gives JSON by default
shell> ANSIBLE_STDOUT_CALLBACK=default ansible-playbook test.yml
ok: [localhost] => {
"msg": "1933"
}
and the yaml callback plugin (see ansible-doc -t callback yaml
) gives single-quoted YAML
shell> ANSIBLE_STDOUT_CALLBACK=yaml ansible-playbook test.yml
ok: [localhost] =>
msg: '1933'
If you want to be sure write a filter e.g.
shell> cat filter_plugins/python_type.py
def python_type(s):
return type(s)
class FilterModule(object):
def filters(self):
return {
'python_type': python_type,
}
Then the tasks
- debug:
msg: "{{ parent_region2|python_type }}"
- debug:
msg: "{{ parent_region2|int|python_type }}"
should give
msg: <class 'ansible.parsing.yaml.objects.AnsibleUnicode'>
msg: <class 'int'>
Q: "Won't Jinja2 just cast it to the string after evaluating the template?"
A: Yes, the output of the Jinja template is a string. It's up to you how you format the output. For example, given the template
shell> cat test.txt.j2
{{ parent_region2|type_debug }} {{ parent_region2 }}
{{ parent_region2|int|type_debug }} {{ parent_region2|int }}
the task
- template:
src: test.txt.j2
dest: test.txt
gives
shell> cat test-094.txt
AnsibleUnicode 1933
int 1933
Upvotes: 2