如何在ansible中以dict形式存储寄存器值?

2024-04-23 10:05:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着转换一个字符串

来自"{ip: 10.213.151.76, mask: 255.255.252.0},{ip: 10.213.151.799, mask: 255.255.252.0}"

[{ip: 10.213.151.76, mask: 255.255.252.0}, {ip: 10.213.151.76, mask: 255.255.252.0}]。在

剧本代码

- hosts: localhost
  vars:
    - vari: "[{ip: 10.213.151.76, mask: 255.255.252.0},{ip: 10.213.151.799, mask: 255.255.252.0}]"
    - foo: []
  tasks:
    - set_fact: testing={{vari[1:-1] | regex_findall('\{(.*?)\}')}}
#    - set_fact: testing={{vari[1:-1]}}
    - debug: var=testing
    - name: run my script!
      command: python ../test.py  "{{item}}"
      delegate_to: 127.0.0.1
      register: hash
      with_items: "{{testing}}"
    - debug: var=hash
    - set_fact: foo={{foo + item.stdout_lines}}
      with_items: "{{hash.results}}"
    - debug: var=foo

将字符串转换为字典的pyhon脚本。在

^{pr2}$

当前foo变量值如下所示。在

ok: [localhost] => {
    "foo": [
        "{'ip': '10.213.151.76', 'mask': '255.255.252.0'}",
        "{'ip': '10.213.151.799', 'mask': '255.255.252.0'}"
    ]
}

基本上,我希望这个值出现在散列格式列表中:[{ip:10.213.151.76,mask:255.255.252.0},{ip:10.213.151.76,mask:255.255.252.0}]。在

Python脚本将返回值作为字典,但register将其存储为字符串。不能把它转换成口述语。在

有什么帮助吗?提前谢谢。在


Tags: 字符串debugipregisterlocalhostfoovarwith
1条回答
网友
1楼 · 发布于 2024-04-23 10:05:21

如果是这么复杂,我想你应该考虑重新设计。然而。。。在

你可以在一个剧本里写一个变量文件,然后在下一个剧本里读它。在

- name: dynamic vars file write test
  hosts: localhost
  gather_facts: no
  tasks:
    - name: write it
      shell: ' echo "foo: bar">tst.yml '

- name: dynamic vars file read test
  hosts: localhost
  gather_facts: no
  vars_files:
   - tst.yml
  tasks:
   - name: read it
     debug:
       msg: "{{foo}}"

哪些输出:

^{pr2}$

这使得格式化和解析变得非常容易,至少对我来说是这样。在

相关问题 更多 >