JSON file list in ansible

Viewed 47

There is a way to have a list of JSON files, each of them representing a specific user in the vars.yml file in Ansible.

Example:

-users:

- username: jsmith
  project_role: administrators
  full_name: John Smith
  email: johnsmith@mail.com
- username: pmorrison
  project_role: developer
  full_name: Paul Morrison
  email: paulmorrison@mail.com

in particular I want to design the single users as single json files, for example. One json file for John smith that contains all his information, one json file for paul morrison that contains all his information, and so on.

Thank you

1 Answers

This can be easily solved with the data in the dictionaries. For example

shell> cat user.d/jsmith.yml
jsmith:
  project_role: administrators
  full_name: John Smith
  email: johnsmith@mail.com

shell> cat user.d/pmorrison.yml 
pmorrison:
  project_role: developer
  full_name: Paul Morrison
  email: paulmorrison@mail.com

the playbook

shell> cat pb.yml 
- hosts: localhost
  tasks:
    - include_vars:
        dir: user.d
        name: users
    - debug:
        var: users

gives

    "users": {
        "jsmith": {
            "email": "johnsmith@mail.com",
            "full_name": "John Smith",
            "project_role": "administrators"
        },
        "pmorrison": {
            "email": "paulmorrison@mail.com",
            "full_name": "Paul Morrison",
            "project_role": "developer"
        }
    }

If needed, the list can be created. For example

    - set_fact:
        users_list: "{{ users_list|d([]) +
                        [{'username': item.0}|combine(item.1)] }}"
      with_together:
        - "{{ users.keys()|list }}"
        - "{{ users.values()|list }}"
    - debug:
        var: users_list

gives

    "users_list": [
        {
            "email": "johnsmith@mail.com",
            "full_name": "John Smith",
            "project_role": "administrators",
            "username": "jsmith"
        },
        {
            "email": "paulmorrison@mail.com",
            "full_name": "Paul Morrison",
            "project_role": "developer",
            "username": "pmorrison"
        }
    ]
Related