首页 > 解决方案 > Ansible:如何根据列表中的特定单词将列表转换/过滤为字典

问题描述

我有一个列表,需要根据列表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"
 ]

字典:输出

{
[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"
}

是否可以在 Ansible 中实现

标签: ansible

解决方案


试试这个

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

给定变量list1中的列表,创建一个键列表。例如,使用mapregex_replace创建列表。然后使用dictzip创建字典。


推荐阅读