I want to minimize my efforts when adding content to my hosts/vars groups.
For example, I have a variable that looks like this:
blue_items:
- name: ocean
color: blue
- name: sky
color: blue
- name: umbrella
color: blue
result with a debug:
root@debian:/opt/ansible# ansible -m "debug msg="{{blue_items}}"" client1 client1 | SUCCESS => { "msg": [ { "color": "blue", "name": "ocean" }, { "color": "blue", "name": "sky" }, { "color": "blue", "name": "umbrella" } ] }
I tried to use a "for" parsing into a list:
my host_vars:
list_blue_items: ['ocean', 'sky', 'umbrella']
blue_items:
{% for item in list_blue_items %}
- name: "{{ item }}"
color: blue
{% endfor %}
result with a debug:
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)
Syntax Error while loading YAML.
found character that cannot start any token
The error appears to be in '/opt/ansible/host_vars/client1/nginx.yml': line 4, column 2, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
blue_items:
{% for item in list_blue_items %}
^ here
I also tried adding a pipe in front of the variable like this :
list_blue_items: ['ocean', 'sky', 'umbrella']
blue_items: |
{% for item in list_blue_items %}
- name: "{{ item }}"
color: blue
{% endfor %}
But the result isn’t like i want, all the content is written on a single line and don’t return my items:
client1 | SUCCESS => { "msg": "- name: "ocean"n color: bluen- name: "sky"n color: bluen- name: "umbrella"n color: bluen" }
3
Answers
Thank you for your answer :)
I tried your first solution but it doesn't seem to work :'(
I have a more complex exemple:
In my host_vars file:
output:
I need to manipulate all of these data like "nginx__vhost.name, nginx__vhost.tls, nginx__vhost.file_conf" and a lot of other...
I also tried to use "{% filter from_yaml %}"
but it provides me an error
I think i have to use the "from_yaml" functionnality but idk why the "{% filter from_yaml %}" doesn't work :/
For example, given the data in group_vars
gives what you want
gives
If you need the list of the dictionaries use the filter dict2items
also gives what you want
Example of a complete project for testing
There are plenty of other options on how to use the data. For example, declare color_items
and use it in the tasks
gives
Use the dictionary in a loop
gives
If you use item in the declaration instead of color
you can iterate the colors
gives
I finally succeeded in creating a new variable:
Wouldn’t it be possible to keep only my "nginx__vhost" list, I don’t think it’s a good way to create a variable just to filter another one, I’d rather be able to filter directly on the 1st variable.