我需要解析 terraform 文件,以 JSON 格式编写。我必须提取两个数据resource
,id
这是示例文件:
{
"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 中编写它:id
aws_security_group.vpc-xxxxxxx-test-1
sg-xxxxxxxxxxxxxx
aws_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
,任何帮助表示赞赏,也可以使用其他方法
谢谢