1

I have a json file structure, and I would like to iterate over an array inside of that file structure. In a way that it fails if a given string isn't found.

"datasource": [
  {
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "black",
    value: "#000"
  }
]

This is my try.

  vars:
    color: "red"

- name: Fetch json_data
  uri:
    url: example.com/json_data
  register: color_data

- name: Loop over data and continue if string was found.
  fail:
    msg: "The color '{{ color }}' was not found.
  when: color not in item
  loop: "{{ color_data['datasource'] }}"

What I want to achieve is, if there is a match it should not fail. E.g. it would be nice to break the loop on match and continue but that doesn't seem to be possible.

Like it should find that there is a match and as long as there are >=1 matches, it should be happy and continue.

1 Answer 1

1

You don't need to iterate over the array items in that case; just map the array attribute, and use when:

tasks:
 - name: Loop over data and continue if string was found.
   fail:
     msg: "The color '{{ color }}' was not found."
   when: color not in color_data | map(attribute='color')

color_data here is initially a list of objects; the map filter is applied to it, to extract an attribute (color), returning another list (of strings, in this case, the colors). Finally, the not in in the expression given a string and list of strings, will return True when none of the items in the list matches the string.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow that was easy, thank you so much! Is there a bit of documentation which explains what is happening here?
Check out the filters docpage for map and the Conditionals docpage for when

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.