如何在Ansible中将多行字符串转换为dict?

时间:2018-05-07 15:03:02

标签: ansible

我使用query('env', 'VARIABLE')

的环境变量在Ansible中设置了一个事实

我的VARIABLE是多行字符串(采用YAML格式):

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

当我使用Ansible打印VARIABLE时,我将其作为单行字符串,行之间有\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 }}"但没有成功。

1 个答案:

答案 0 :(得分:1)

an important note in the docs

  

lookupquery之间的区别主要在于 query将始终返回列表

所以:

  • query('env', 'VARIABLE')替换为lookup('env', 'VARIABLE')

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

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