On Wed, 25 Mar 2020 23:54:57 -0700 (PDT) Davide Scrimieri <[email protected]> wrote:
> I want to convert "my_other_var" to an object only if it is
> passed as as string, otherwise I don't want to touch the object, and leave
> it as it is.
>
> - set_fact:
> my_var: "{{ ( my_other_var | type_debug == 'str' ) | ternary
> (my_other_var | from_json, my_other_var }}"
I'd rather use "from_yaml". JSON is a subset of YAML. How to test types see
https://jinja.palletsprojects.com/en/master/templates/#list-of-builtin-tests
For example
vars:
my_other_var1: "'my': {'other': {'var1': 'var1'}}"
my_other_var2:
my:
other:
var2: var2
tasks:
- debug:
msg: "{{ item is string|ternary(item|from_yaml, item) }}"
loop:
- "{{ my_other_var1 }}"
- "{{ my_other_var2 }}"
gives
ok: [localhost] => (item='my': {'other': {'var1': 'var1'}}) => {
"msg": {
"my": {
"other": {
"var1": "var1"
}
}
}
}
ok: [localhost] => (item={u'my': {u'other': {u'var2': u'var2'}}}) => {
"msg": {
"my": {
"other": {
"var2": "var2"
}
}
}
}
HTH,
-vlado
--
You received this message because you are subscribed to the Google Groups
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/ansible-project/20200326091302.150b60ad%40gmail.com.
pgpLS1bWwMVxu.pgp
Description: OpenPGP digital signature
