senthil Kumar B.K
senthil Kumar B.K

Reputation: 35

Ansible: How to convert/filter list into dictionary based on specific word from list

I have one list and need to convert/filter that list into dictionary based on specific word from list List:input

 [
        "[profile appdev]\r\nArn: aaa.dev:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
        "[profile applead]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
        "[profile appprod]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
        "[profile apppadmin]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
        "[profile appsupport]\r\nArn: aaa.dev:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
        "[profile appguest]\r\nArn: aaa.techlead:433:iam\r\nRegion: ap.southeast3"
 ]

dictionary :output

{
[profile appdev]:"profile appdev]\r\nArn: aaa.dev:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
[profile applead]:"[profile applead]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n"
[profile appprod]:"[profile appprod]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
[profile apppadmin]:"[profile apppadmin]\r\nArn: aaa.techlead:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
[profile appsupport]:"[profile appsupport]\r\nArn: aaa.dev:333:iam\r\nRegion: ap.southeast2\r\n\r\n",
[profile appguest]:"[profile appguest]\r\nArn: aaa.techlead:433:iam\r\nRegion: ap.southeast3"
}

Is it possible to achieve in Ansible

Upvotes: 0

Views: 462

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67984

Try this

    - set_fact:
        dict1: "{{ dict(keys|zip(list1)) }}"
      vars:
        regex: '(\[.*\])(.*)'
        replace: '\1'
        keys: "{{ list1|map('regex_replace', regex, replace)|list }}"

Given the list in the variable list1 create a list of keys. For example, use map and regex_replace to create the list keys. Then use dict and zip to create the dictionary.

Upvotes: 1

Related Questions