pythonansiblejinja2ansible-filter

ansible filter to map array and put in json template


I have an array variable as following

registries:
- type: primary
  host: r1.example.com
- type: secondary
  host: r2.example.com

I want to render the host attribute only from each array item inside a json.j2 template. I tried the following in the template :

{ 
  "insecure-registries": {{ registries | map(attribute='host') | to_json }}
}

Unfortunately , it does not work but it throw this error while running the playbook :

AnsibleError: Unexpected templating type error occurred on ({ \n \"graph\": \"{{ docker_home }}\",\n \"insecure-registries\" : {{ registries | map(attribute='host') | to_json }}\n}): Object of type 'generator' is not JSON serializable"}


Solution

  • map returns a particular object type which is not a list. You need to transform that to a list before you feed it to to_json with the list filter

    { 
      "insecure-registries": {{ registries | map(attribute='host') | list | to_json }}
    }