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": {
    }
  }
]

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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/

2 Comments

test.json is the input data not the expect result. The result should only consist of the value of either docker.network or id.
So you can use jq to transform streams not files. ( with linux pilelines )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.