Ansible过滤器/解析输出到json

2024-06-16 13:14:50 发布

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

我正在尝试将ansible playbook输出过滤为有效的json输出,以便使用它。 我得到的输出是:

ok: [r-sw01] => {
    "configlets | selectattr(\"name\", \"eq\", \"r-sw01\")": [
        {
            "config": "hostname r-sw01\n\ninterface Management1\n   ip address 10.10.24.10/24\n\ninterface Port-Channel20\n   description USR\n   switchport mode trunk\n\ninterface Ethernet99-100\n   description  USR_Po20\n   speed forced 25gfull\n",
            "containerCount": 0,
            "containers": [],
            "dateTimeInLongFormat": 1615984781483,
            "devices": [
                "r-sw01"
            ],
            "editable": true,
            "isAutoBuilder": "",
            "isDefault": "no",
            "isDraft": false,
            "key": "configlet_71ef71",
            "name": "r-sw01",
            "netElementCount": 0,
            "note": "",
            "reconciled": false,
            "sslConfig": false,
            "type": "Static",
            "typeStudioConfiglet": false,
            "user": "chal",
            "visible": true
        }
    ]
}

从本手册中:

---
- name: Playbook to demonstrate cv_container module.
  hosts: cvp_servers
  connection: local
  gather_facts: no
  collections:
    - arista.cvp
  tasks:
    - name: "Gather CVP facts from {{inventory_hostname}}"
      arista.cvp.cv_facts:
        facts:
          configlets
    - debug:
        var: configlets | selectattr("name", "eq", "{{ tag }}")

已尝试使用python对其进行过滤:

configlet_settings = subprocess.Popen(["ansible-playbook", "configlets.yml", "-e", tag ,"-i", "inventory.ini"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = configlet_settings.communicate()
out = out.decode()
out = out.split('\n')
r = re.search(r"configlets.*\[(.*?)\]", str(out))
r = r.group(1)
my_lst = re.findall(r"\w+", r)

但我只得到 (['r', 'sw01'],)

或者“无”当我试图更改正则表达式时,如何获得此输出的有效json?我不需要| selectattr(\"name\", \"eq\", \"r-sw01\")"只需要后面的东西

编辑- 正在尝试将输出重定向到文件:

  ---
- name: Playbook to demonstrate cv_container module.
  hosts: cvp_servers
  connection: local
  gather_facts: no
  collections:
    - arista.cvp
  vars:
    var: var
    vars_files:
            - vars.yml
  tasks:
    - name: "Gather CVP facts from {{inventory_hostname}}"
      arista.cvp.cv_facts:
        facts:
          configlets
    - debug:
        var: configlets | selectattr("name", "eq", "{{ tag }}")

    - name: write JSON to a file
      copy:
         content: "{{ var|to_nice_json }}"
         dest: somefile.json

出现错误:

FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'var' is undefined

Tags: tonamejsonfalsevaroutcvhostname
1条回答
网友
1楼 · 发布于 2024-06-16 13:14:50

如果要将Ansible变量的JSON序列化写入文件,可以执行以下操作:

- name: write JSON to a file
  copy:
    content: "{{ var|to_nice_json }}"
    dest: somelog.json

然后将其导入Python代码中:

import json

with open('somelog.json') as fd:
  data = json.load(fd)

相关问题 更多 >