簡體   English   中英

將列表轉換為字典 - Ansible YAML

[英]Convert a list to dictionary - Ansible YAML

我有一本劇本,我收到一條錯誤消息

fatal: [localhost]: FAILED! => {"ansible_facts": {"tasks": {}}, "ansible_included_var_files": [], "changed": false, "message": "/home/user/invoke_api/automation/tmp/task.yml must be stored as a dictionary/hash"}

任務.yml

文件task.yml是動態創建的,並且一直從另一個來源過濾,以提供下面的 output。

-   key: gTest101
    value:
        Comments: FWP - Testing this
        IP: 10.1.2.3
        Name: gTest101
-   key: gTest102
    value:
        Comments: FWP - Applying this
        IP: 10.1.2.4
        Name: gTest102

問題:如何將 task.yml 中的列表轉換為字典? 從列表轉換為字典的代碼是什么

劇本.yml

---
- name: Global Objects
  hosts: check_point
  connection: httpapi
  gather_facts: False
  vars_files:
    - 'credentials/my_var.yml'
    - 'credentials/login.yml'
  tasks:
  - name: read-new-tmp-file
    include_vars:
      file: tmp/task.yml
      name: tasks
    register: new_host

  - name: add-host-object-to-group
    check_point.mgmt.cp_mgmt_host:
      name: "{{ item.value.Name | quote }}"          
      ip_address: "{{ item.value.IP | quote }}"      
      comments: "{{ item.value.Comments }}"
      groups: gTest1A
      state: present
      auto_publish_session: yes
    loop: "{{ new_host.dict | dict2items }}"  
    delegate_to: Global
    ignore_errors: yes


Ansible 內核 2.9.13 python 版本 = 2.7.17

vars 文件是 yaml dict 文件,因此您的列表必須是 vars 的字段:

 my_vars: - Comments: FWP - Testing this IP: 10.1.2.3 Name: gTest101 - Comments: FWP - Applying this IP: 10.1.2.4 Name: gTest102

而且您不需要注冊 include_vars 任務。 只需循環列表變量名稱(此處為 my_vars)。

 --- - name: Global Objects hosts: check_point connection: httpapi gather_facts: False vars_files: - 'credentials/my_var.yml' - 'credentials/login.yml' tasks: - name: read-new-tmp-file include_vars: file: tmp/task.yml - name: add-host-object-to-group check_point.mgmt.cp_mgmt_host: name: "{{ item.Name }}" ip_address: "{{ item.IP }}" comments: "{{ item.Comments }}" groups: gTest1A state: present auto_publish_session: yes loop: "{{ my_vars }}" delegate_to: Global ignore_errors: yes

問: 如何將 task.yml 中的列表轉換為字典?

答:使用items2dict 例如,讀取文件並創建列表

    - set_fact:
        l1: "{{ lookup('file', 'task.yml')|from_yaml }}"

    l1:
      - key: gTest101
        value:
          Comments: FWP - Testing this
          IP: 10.1.2.3
          Name: gTest101
      - key: gTest102
        value:
          Comments: FWP - Applying this
          IP: 10.1.2.4
          Name: gTest102

然后,下面的任務

    - set_fact:
        d1: "{{ l1|items2dict }}"

創建字典

  d1:
    gTest101:
      Comments: FWP - Testing this
      IP: 10.1.2.3
      Name: gTest101
    gTest102:
      Comments: FWP - Applying this
      IP: 10.1.2.4
      Name: gTest102

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM