postgresql 合并两个字典并创建具有更新凭据的字典列表

busg9geu  于 2023-05-28  发布在  PostgreSQL
关注(0)|答案(1)|浏览(136)

我想帮助创建一个新的数据结构,比较两个字典,
然后用字典创建一个列表。这个想法是,在更改的情况下,保留旧版本,并添加修改后的用户名/密码。
目标:

list: [{"username": "a1", "password": "apass1"}, {"username": "a2", "password": "apass2"}, {"username": "b1", "password": "bpass1"}, {"username": "c1", "password": "cpass1"}, {"c_username": "c1", "c_password" : "cpass1"} , {"c_username": "c2", "c2_password" : "cpass1"}]
---
name: "Username/Password version 1"
set_fact:
  dict1: {"a_username": "a1", "a_password" : "apass1", "b_username": "b1", "b_password" : "bpass1", "c_username": "c1", "c_password" : "cpass1"}

name: "Username/Password version 2"
set_fact:
  dict2: {"a_username": "a2", "a_password" : "apass2", "b_username": "b1", "b_password" : "bpass1", "c_username": "c2", "c2_password" : "cpass1"}

我希望这对管理我的PostgreSQL数据库中的服务中断有用。我还从Vault中检索用户名/密码数据

monwx1rj

monwx1rj1#

鉴于字典

dict1:
      a_username: a1
      a_password: apass1
      b_username: b1
      b_password: bpass1
      c_username: c1
      c_password: cpass1
      
    dict2:
      a_username: a2
      a_password: apass2
      b_username: b1
      b_password: bpass1
      c_username: c2
      c_password: cpass1

Q:***“保留旧版本,添加修改后的用户名/密码。”***
A:下面的模板

list1: |
      {% filter from_yaml %}
      {% for i in dict1.keys()|batch(2) %}
      - {username: {{ dict1[i.0] }}, password: {{ dict1[i.1] }}}
      {% if dict1[i.0] != dict2[i.0] or dict1[i.1] != dict2[i.1] %}
      - {username: {{ dict2[i.0] }}, password: {{ dict2[i.1] }}}
      {% endif %}
      {% endfor %}
      {% endfilter %}

给予

list1:
      - {password: apass1, username: a1}
      - {password: apass2, username: a2}
      - {password: bpass1, username: b1}
      - {password: cpass1, username: c1}
      - {password: cpass1, username: c2}

下一个选项是获取唯一的用户名/密码对并创建字典

dict3: "{{ dict((dict1.values()|list + dict2.values()|list)|
                    batch(2)|unique) }}"

给予

dict3:
      a1: apass1
      a2: apass2
      b1: bpass1
      c1: cpass1
      c2: cpass1

把字典转换成列表,你会得到同样的结果

list1: "{{ dict3|
               dict2items(key_name='username', value_name='password')|
               sort(attribute='username') }}"

相关问题