ansible/yaml:从dict获取字符串形式的值

2024-05-23 16:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些变量需要循环:

mariadb_grants:
  "*.*":
    - user1: "ALL, SELECT"
    - user2: "ALL"
  "toto":
    - user1: "ALL"
    - user23: "GRANT"

当然,userX不是预先定义的,我可以使用user1233等。 我可以很容易地使用以下代码循环dict:

  tasks:
    - debug:
        msg: "Key is {{ item }} and value is {{ mariadb_grants[item] }}"
      loop: "{{ mariadb_grants.keys() }}"

我明白了:

ok: [localhost] => (item=*.*) => {}

MSG:

Key is *.* and value is [{'user1': 'ALL, SELECT'}, {'user2': 'ALL'}]
ok: [localhost] => (item=toto) => {}

MSG:

Key is toto and value is [{'user1': 'ALL'}, {'user23': 'GRANT'}]

我想做的就是获取userx的键和值,基本上我想要这样:

My key is *.* I'm user1 and my value is "ALL, SELECT"
My key is *.* I'm user2 and my value is ALL
My key is "toto" I'm user1 and my value is ALL
[...]

似乎我无法循环我的子元素:(


Tags: andkeyisvaluemyallitemselect
1条回答
网友
1楼 · 发布于 2024-05-23 16:06:52

可以在中使用dict2items和\u子元素循环,例如

  - debug:
      msg: 'My key is {{ item.0.key }} I am {{ key }} and my value is "{{ val }}"'
    with_subelements:
      - "{{ mariadb_grants|dict2items }}"
      - value
    vars:
      key: "{{ item.1.keys()|first }}"
      val: "{{ item.1.values()|first }}"

给予

  msg: My key is *.* I am user1 and my value is "ALL, SELECT"
  msg: My key is *.* I am user2 and my value is "ALL"
  msg: My key is toto I am user1 and my value is "ALL"
  msg: My key is toto I am user23 and my value is "GRANT"

相关问题 更多 >