Gerald Shyti
Gerald Shyti

Reputation: 51

JSON file list in ansible

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: [email protected]
- username: pmorrison
  project_role: developer
  full_name: Paul Morrison
  email: [email protected]

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

Upvotes: 2

Views: 78

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

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: [email protected]

shell> cat user.d/pmorrison.yml 
pmorrison:
  project_role: developer
  full_name: Paul Morrison
  email: [email protected]

the playbook

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

gives

    "users": {
        "jsmith": {
            "email": "[email protected]",
            "full_name": "John Smith",
            "project_role": "administrators"
        },
        "pmorrison": {
            "email": "[email protected]",
            "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": "[email protected]",
            "full_name": "John Smith",
            "project_role": "administrators",
            "username": "jsmith"
        },
        {
            "email": "[email protected]",
            "full_name": "Paul Morrison",
            "project_role": "developer",
            "username": "pmorrison"
        }
    ]

Upvotes: 2

Related Questions