Kucharsky
Kucharsky

Reputation: 263

Append variable to each dictionary in list

I have got multiple files. One of them:

kind: Deployment
name: pr1-dep
---
kind: Ingress
name: pr1-ing

My Ansible role:

- name: "Cat command result to list of dictionary"
  set_fact:
      objects: '{{ objects | default([]) + [ object ] | flatten }}'
  vars:
    object: { 'items': "{{ item.stdout | from_yaml_all | list }}", 'filename': "{{ item.item.dest }}" }
  loop: "{{ cat.results }}"

The results above role:

- filename: srv.yaml
  items: [
    {kind: Deployment, name: pr1-dep},
    {kind: Ingress, name: pr1-ing}
  ]

I would like to have filename in each dictionary. Expected result:

- [
    {kind: Deployment, name: pr1-dep, filename: srv.yaml},
    {kind: Ingress, name: pr1-ing, filename: srv.yaml}
  ]

How could I achieve this result?

Upvotes: 1

Views: 650

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

Use the map filter to apply the combine filter to each list element with your single key dict containing the file name.

- name: "Cat command result to list of dictionary"
  set_fact:
      objects: '{{ objects | default([]) + [ object ] | flatten }}'
  vars:
    file_addition:
      filename: "{{ item.item.dest }}"
    object:
      items: "{{ item.stdout | from_yaml_all | list | map('combine', file_addition) }}"
  loop: "{{ cat.results }}"

Forward note: Using cat in shell/command to get a yaml file content is a bad practice in ansible. You can use the file lookup if the file is local or the slurp module if you need to read a remote file.

Upvotes: 1

Related Questions