Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Creating dictionary from a list

Tags:

ansible

i am trying to follow this thread but my output is not what was expected. every previous item is getting overwritten with the new item being added.

my input is a list that i am loading into my accounts_list variables is as follows:

account:
  - PR_user1
  - PR_user2

There are no passwords in the input file. i need to create random passwords for each of the user account, use them in setting up various services, and then dump them into a text file for human use.

my first task on which i am stuck is that once i have read them into a list, i want to iterate over them, create password for each account, and then store it inside a dictionary as key value pairs.

i have tried both of the techniques mentioned to add an item to an existing dictionary, using combine as well as '+'.

my input is a simple list called 'accounts'.

 - set_fact:
 #  domain_accounts: "{{ domain_accounts|default({}) | combine({item|trim: lookup(...)} ) }}"
  domain_accounts: "{{ domain_accounts|default([]) + [{item|trim:lookup('...)}]  }}"
with_items: "{{account_list.accounts}}"

My output is as follows:

TASK [set account passwords] 
******************************************************************
ok: [localhost] => (item=PR_user1) => {"ansible_facts": {"domain_accounts": [{"PR_user1": "u]oT,cU{"}]}, "changed": false, "item": "PR_user1"}
ok: [localhost] => (item=PR_user2) => {"ansible_facts": {"domain_accounts": [{"PR_user2": "b>npKZdi"}]}, "changed": false, "item": "PR_user2"}
like image 540
Ali Khawaja Avatar asked May 13 '18 08:05

Ali Khawaja


2 Answers

Supposing that the variable lists is as follows (That I guess it's not your case):

accounts:
  - user: PR_user1
    password: "u]oT,cU{"
  - user: PR_user2
    password: "b>npKZdi"

With:

- name: debug
  debug:
    var: accounts

and

- name: Populate dict
  set_fact:
    domain_accounts: "{{ domain_accounts|default({}) | combine( {item.user: item.password} ) }}"
  with_items:
    - "{{ accounts }}"

plus:

- name: debug
  debug:
    var: domain_accounts

You will get:

ok: [localhost] => {
    "domain_accounts": {
        "PR_user1": "u]oT,cU{", 
        "PR_user2": "b>npKZdi"
    }
}

But I guess you have something like:

accounts:
  - PR_user1: "u]oT,cU{"
  - PR_user2: "b>npKZdi"

So:

- name: Create dict
  set_fact:
    domain_accounts: "{{ domain_accounts|default({}) |  combine(item.1) }}"
  with_indexed_items: "{{accounts}}"

- name: debug
  debug:
    var: domain_accounts

Will get:

ok: [localhost] => {
    "domain_accounts": {
        "PR_user1": "u]oT,cU{", 
        "PR_user2": "b>npKZdi"
    }
}

This is the whole play for your reference:

---
- hosts: localhost
  gather_facts: False


  vars:

    accounts:
      - user: PR_user1
        password: "u]oT,cU{"
      - user: PR_user2
        password: "b>npKZdi"

    accountslist:
      - PR_user1: "u]oT,cU{"
      - PR_user2: "b>npKZdi"

  tasks:
    - name: Debug Accounts
      debug:
        var: accounts

    - name: Debug Accounts List
      debug:
        var: accountslist

    - name: Populate dict
      set_fact:
        domain_accounts: "{{ domain_accounts|default({}) | combine( {item.user: item.password} ) }}"
      with_items:
        - "{{ accounts }}"

    - name: Debug Domain Accounts
      debug:
        var: domain_accounts

    - name: indexed loop demo
      debug: 
        msg: "{{ item.1 }}"
      with_indexed_items: "{{accountslist}}"

    - name: Create Local Dict
      set_fact:
        local_accounts: "{{ local_accounts|default({}) |  combine(item.1) }}"
      with_indexed_items: "{{accountslist}}"

    - name: Debug Local Accounts
      debug:
        var: local_accounts

And the results:

PLAY [localhost] *********************************************************************************************************************

TASK [Debug Accounts] ****************************************************************************************************************
ok: [localhost] => {
    "accounts": [
        {
            "password": "u]oT,cU{", 
            "user": "PR_user1"
        }, 
        {
            "password": "b>npKZdi", 
            "user": "PR_user2"
        }
    ]
}

TASK [Debug Accounts List] ***********************************************************************************************************
ok: [localhost] => {
    "accountslist": [
        {
            "PR_user1": "u]oT,cU{"
        }, 
        {
            "PR_user2": "b>npKZdi"
        }
    ]
}

TASK [Populate dict] *****************************************************************************************************************
ok: [localhost] => (item={u'password': u'u]oT,cU{', u'user': u'PR_user1'})
ok: [localhost] => (item={u'password': u'b>npKZdi', u'user': u'PR_user2'})

TASK [Debug Domain Accounts] *********************************************************************************************************
ok: [localhost] => {
    "domain_accounts": {
        "PR_user1": "u]oT,cU{", 
        "PR_user2": "b>npKZdi"
    }
}

TASK [indexed loop demo] *************************************************************************************************************
ok: [localhost] => (item=None) => {
    "msg": {
        "PR_user1": "u]oT,cU{"
    }
}
ok: [localhost] => (item=None) => {
    "msg": {
        "PR_user2": "b>npKZdi"
    }
}

TASK [Create Local Dict] *************************************************************************************************************
ok: [localhost] => (item=(0, {u'PR_user1': u'u]oT,cU{'}))
ok: [localhost] => (item=(1, {u'PR_user2': u'b>npKZdi'}))

TASK [Debug Local Accounts] **********************************************************************************************************
ok: [localhost] => {
    "local_accounts": {
        "PR_user1": "u]oT,cU{", 
        "PR_user2": "b>npKZdi"
    }
}

PLAY RECAP ***************************************************************************************************************************
localhost                  : ok=7    changed=0    unreachable=0    failed=0 
like image 104
imjoseangel Avatar answered Sep 30 '22 17:09

imjoseangel


The cleanest solution might be to create your own ansible filter:

  • Create a folder filter_plugins in your ansible directory.
  • Create a file called to_dict.py.

Add the following content.

class FilterModule(object):
    def filters(self):
    return {'to_dict': lambda _list: {key: value for key, value in [value.split('=') for value in _list]}}

Ansible vars:

account:
  - PR_user1=value1
  - PR_user2=value2

Task:

"{{ account | to_dict }}"
like image 44
Tobias Ernst Avatar answered Sep 30 '22 17:09

Tobias Ernst