0

我需要解析 terraform 文件,以 JSON 格式编写。我必须提取两个数据resourceid这是示例文件:

    {
      "version": 1,
      "serial": 1,
      "modules": [
        {
          "path": [
            "root"
          ],
          "outputs": {
          },
          "resources": {
            "aws_security_group.vpc-xxxxxxx-test-1": {
              "type": "aws_security_group",
              "primary": {
                "id": "sg-xxxxxxxxxxxxxx",
                "attributes": {
                  "description": "test-1",
                  "name": "test-1"
                }
              }
            },
            "aws_security_group.vpc-xxxxxxx-test-2": {
              "type": "aws_security_group",
              "primary": {
                "id": "sg-yyyyyyyyyyyy",
                "attributes": {
                  "description": "test-2",
                  "name": "test-2"
                }
              }
            }
          }
        }
      ]
    }

在这种情况下,我需要导出 anyresources的第一个键和值,并且 我尝试在 python 中编写它:idaws_security_group.vpc-xxxxxxx-test-1 sg-xxxxxxxxxxxxxxaws_security_group.vpc-xxxxxxx-test-2 sg-yyyyyyyyyyyy

#!/usr/bin/python3.6

import json
import objectpath

with open('file.json') as json_file:
    data = json.load(json_file)
    json_tree = objectpath.Tree(data['modules'])
    result = tuple(json_tree.execute('$..resources[0]'))

result

('aws_security_group.vpc-xxxxxxx-test-1','aws_security_group.vpc-xxxxxxx-test-2')

没关系,但我无法提取id,任何帮助表示赞赏,也可以使用其他方法

谢谢

4

1 回答 1

1

我不知道objectpath,但我认为你需要:

tree.execute('$..resources[0]..primary.id')

甚至只是

tree.execute('$..resources[0]..id')
于 2019-04-03T08:18:37.407 回答