首页 > 解决方案 > 如何在 Ansible 中将多行字符串转换为 dict?

问题描述

我在 Ansible 中使用环境变量设置了一个事实query('env', 'VARIABLE')

MyVARIABLE是多行字符串(YAML 格式):

device: eth0
bootproto: static
address: 192.168.x.x
netmask: 255.255.255.0 
gateway: 192.168.x.x

当我VARIABLE用 Ansible 打印时,我把它作为一个字符串,在行\n之间

"msg": ["device: eth0\nbootproto: static\naddress: 
        192.168.x.x\nnetmask: 255.255.255.0\ngateway: 192.168.x.x"]

有没有方便的方法将其转换为dict?我需要稍后在我的任务中使用它,在配置机器的 NIC 时加载参数。

我尝试使用 Jinja2 过滤器- debug: msg="{{ network_settings | from_yaml }}"但没有成功。

标签: ansible

解决方案


文档中有一个重要说明

lookup和之间的区别query主要在于query总是返回一个列表

所以:

  • 要么替换query('env', 'VARIABLE')lookup('env', 'VARIABLE')

    - debug:
        msg: "{{ lookup('env', 'VARIABLE') | from_yaml }}"
    
  • 或相应地处理列表(内容将在第一个也是唯一的元素中):

    - debug:
        msg: "{{ query('env', 'VARIABLE') | first | from_yaml }}"
    

推荐阅读