I have a JSON structure where I need to substitute the value if a key named secured
is set to the value 1
. I’m doing this in jinja. An example of the JSON is this:
{
"OperatingSystems":{
"Ubuntu":{
"Cores":{
"value":"4",
"secured":0
},
"Memory":{
"value":"8",
"secured":0
},
"Storage":{
"value":"500",
"secured":0
},
"Accounts":{
"Test":{
"Name":{
"value":"aabb",
"secured":0
},
"Password":{
"value":"1231",
"secured":1
}
}
},
"Testttt":{
"Cores":{
"value":"4",
"secured":0
},
"Memory":{
"value":"8",
"secured":0
}
}
}
},
"Services":{
"AVX-AADDSS":{
"Accounts":{
"AWX":{
"Admin":{
"value":"admin",
"secured":0
},
"Password":{
"value":"1231",
"secured":1
}
},
"lawip":{
"Name":{
"value":"admin",
"secured":0
},
"Password":{
"value":"33111",
"secured":1
}
}
}
}
}
}
The JSON is dynamic. And when for example the “OperationgSystems.Ubuntu.Accounts.Test.Password” has the secured
property set to 1
I want to change the value
property 1231
to abc
.
I have tried the following but this just outputs the same format and exact same data as the input. Do you have any idea on how to solve this problem?
{%- macro build_model(data, model_path) %}
{%- for key, value in data.items() %}
{%- if value is mapping %}
{%- set _ = model_path.update({key: {}}) -%}
{{ build_model(value, model_path[key]) }}
{%- else %}
{%- if value is mapping and 'secured' in value and value['secured'] == 1 %}
{%- set _ = model_path.update({key: 'abc'}) -%}
{%- elif value is mapping and 'value' in value %}
{%- set _ = model_path.update({key: value['value']}) -%}
{%- else %}
{%- set _ = model_path.update({key: value}) -%}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- endmacro %}
{%- set inventory_model = {} %}
{{ build_model(props, inventory_model) }}
{{ inventory_model | tojson(indent=4) }}