Ansible

Ansible:將字元串轉換為字典

  • April 19, 2022

我正在從 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!"
}

知道如何將該字元串轉換為真正的字典嗎?提前致謝!

更新

下面的表達式

users_list: "{{ users_str.splitlines()|map('from_yaml')|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

引用自:https://serverfault.com/questions/1085067