Ansible:将字符串转换为字典

Ansible:将字符串转换为字典

我从 Tower 启动 Ansible,然后以文本形式填充新用户:

{ name: user1, uid: 5000 }
{ name: user2, uid: 5001 }

我想将这些用户迭代为一本字典,如下所示:

- name: Print vars
  debug:
    var: "{{ item.name }}"
  with_items: "{{ users.split('\n') }}"

但它不起作用:

TASK [Print vars] *********************************************************************************************************************
ok: [lx-test] => (item={ name: user1, uid: 5000 }) => {
    "ansible_loop_var": "item",
    "item": "{ name: user1, uid: 5000 }",
    "{ name: user1, uid: 5000 }": "VARIABLE IS NOT DEFINED!"
}
ok: [lx-test] => (item={ name: user2, uid: 5001 }) => {
    "ansible_loop_var": "item",
    "item": "{ name: user2, uid: 5001 }",
    "{ name: user2, uid: 5001 }": "VARIABLE IS NOT DEFINED!"
}

知道如何将该字符串转换为真正的字典吗?提前致谢!

答案1

更新

下面的表达式

users_list: "{{ users_str.splitlines()|map('from_yaml')|list }}"

给出

users_list:
  - name: user1
    uid: 5000
  - name: user2
    uid: 5001

将变量声明为合适的


完整测试剧本的示例

- hosts: localhost

  vars:

    users_str: |
      {name: user1, uid: 5000}
      {name: user2, uid: 5001}

    users_list: "{{ users_str.splitlines()|map('from_yaml')|list }}"

  tasks:

    - debug:
        var: users_list

(可选)将数据放入 CSV 文件中

shell> cat /tmp/users.csv 
name,uid
user1,5000
user2,5001

并使用社区.general.read_csv阅读它

- hosts: localhost

  tasks:

    - community.general.read_csv:
        path: /tmp/users.csv
      register: users
    - debug:
        var: users.list

给出(节选)

  users.list:
  - name: user1
    uid: '5000'
  - name: user2
    uid: '5001'

原始答案

该文本既不是有效的 JSON,也不是 YAML。您必须拆分行并逐行阅读字典。例如,给定文本

users_str: |
  {name: user1, uid: 5000}
  {name: user2, uid: 5001}

下面的任务

    - set_fact:
        users_list: "{{ users_list|d([]) + [item|from_yaml] }}"
      loop: "{{ users_str.splitlines() }}"

创建字典列表

users_list:
  - name: user1
    uid: 5000
  - name: user2
    uid: 5001

现在迭代很简单

    - debug:
        var: item.name
      loop: "{{ users_list }}"

给出

  item.name: user1
  item.name: user2

相关内容