0
votes

I need to create a single ansible playbook that will loop through multiple vars files in a single directory and use each configuration individually in a rest API POST.

Ideally, with the following vars files...

/my/vars/dir
  - my_pen.yml
      pen:
        color: "blue"

  - her_pen.yml
      pen:
        color: "red"

  - his_pen.yml
      pen:
        color: "green"

...my playbook would execute a POST for each pen. Unfortunately, all files contain a configuration for the same object type so an include_vars task would only retain the configuration for "his_pen".

I've been able to get a list of all files in the directory using find:

- name: "find config files"
  find:
    paths: /path/to/config/files
    patterns: '*.yml'
  register: config_files

I have a task that can do the POST:

- name: Do post
  uri:
    url: "{{ rest_api_endpoint }}"
    method: POST
    user: "{{ username }}"
    password: "{{ password }}"
    body: "{{ pen }}"
    body_format: json
    return_content: yes
    status_code: 200
  register: post_result

Now I just need to fuse the two. Is this possible? I can't change the file structure, so I have to use what's in place.

Thoughts?

1

1 Answers

1
votes

Let's create the list of pens first and then loop the list. The play below

- set_fact:
    pens: "{{ pens|default([]) + [ lookup('file', item)|from_yaml ] }}"
  loop: "{{ lookup('fileglob', 'vars/*.yml', wantlist=True) }}"
- debug:
    msg: "{{ item }}"
  loop: "{{ pens }}"

gives (abridged):

ok: [localhost] => (item={'pen': {'color': u'blue'}}) => {
    "msg": {
        "pen": {
            "color": "blue"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'green'}}) => {
    "msg": {
        "pen": {
            "color": "green"
        }
    }
}
ok: [localhost] => (item={'pen': {'color': u'red'}}) => {
    "msg": {
        "pen": {
            "color": "red"
        }
    }
}