I'm new to ansible and I'm having a problem reading a value from json file in ansible role. my variable has a value like the following:
{
"queue": {
"first": {
"car": "bmw",
"year": "1990",
"model": "x3",
"color": "blue"
},
"second": {
"car": "bmw",
"year": "2000",
"model": "318",
"color": "red"
}
}
}
I'm trying to print the color's value only to compare it with some other variable. I used with_dict
to iterate over the json object (stored in variable called jsonVar) like the following:
- name: test loop
with_dict: "{{jsonVar}}"
shell: |
if echo "blue" | grep -q "${{item.value.color}}" ; then
echo "success"
so far there is no luck in getting the comparison of color's value from json to "blue" from the if statement. I was wondering if I'm doing something wrong? thanks in advance!
You can read a json file using a lookup plugin called file
and pass it to the from_json
jinja2 filter. You also had mistake in the with_dict
loop, since you have to loop over the jsonVar['queue']
, not just jsonVar
. Here is a complete code which works:
---
- hosts: your_host
vars:
jsonVar: "{{ lookup('file', 'var.json') | from_json }}"
tasks:
- name: test loop
with_dict: "{{ jsonVar['queue'] }}"
shell: |
if echo "blue" | grep -q "{{ item.value.color }}" ; then
echo "success"
fi