2

I need to conditionally transform a list of objects defined in a JSON file. The problem with the playbook is that I need the transformation to yield either the value of docker.network or id. Simply put, I need to figure out some kind of ternary operator for transforming lists. The playbook results in:

"msg": "['baz', AnsibleUndefined]"

I need

"msg": "['baz', 'bar']"

Playbook:

vars:
  daemons: "{{ lookup('file','./test.json') | from_json }}"

  tasks:
    - name: Transform
      debug:
        msg: "{{ daemons | map(attribute='docker.network')  }}"

test.json:

[
  {
    "id": "foo",
    "docker": {
      "network": "baz"
    }
  },
  {
    "id": "bar",
    "docker": {
    }
  }
]
Daniel
  • 7,684
  • 7
  • 52
  • 76
Oliver Weichhold
  • 10,259
  • 5
  • 45
  • 87

2 Answers2

3

For example

    - debug:
        msg: "{{ _list }}"
      vars:
        _list: "{{ _list_str|from_yaml }}"
        _list_str: |
          [
          {% for i in daemons %}
          {% if i.docker.network is defined %}
          {{ i.docker.network }},
          {% else %}
          {{ i.id }},
          {% endif %}
          {% endfor %}
          ]

gives

  msg:
  - baz
  - bar
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
1

You should process your file test.json for example using jq

jq 'map(. |= if .docker.network then . else . + {"docker":{"network": .id}} end)' test.json

will print

[
  {
    "id": "foo",
    "docker": {
      "network": "baz"
    }
  },
  {
    "id": "bar",
    "docker": {
      "network": "bar"
    }
  }
]

You can read more in pages:

https://kaijento.github.io/2017/03/26/json-parsing-jq-simplifying-with-map/ https://stedolan.github.io/jq/manual/#Math Add new element to existing JSON array with jq

And test your command on page:

https://jqplay.org/

Daniel
  • 7,684
  • 7
  • 52
  • 76