I have a python script below which loads a yaml file. Arguments are passed in as a list so I can loop through them to add values to the dictionary. The code below adds the parameters but the json is not properly formatted as displayed in the current and desired json result. Any help in the right direction is appreciated. Thanks.
YAML File
policies:
- name: ec2age
resource: ec2
filters:
- State.Name: running
- "tag:ResourceCreatedBy": present
- and:
- type: instance-age
days: 30
op: ge
Python script:
#!/usr/bin/python
import sys
import argparse
import json
import yaml
parser = argparse.ArgumentParser()
parser.add_argument("-y", "--yaml_file", type=str)
parser.add_argument("-b", "--business_unit", type=str)
parser.add_argument("-p", "--platform", type=str)
parser.add_argument("-c", "--client", type=str)
args = parser.parse_args()
with open(args.yaml_file, 'r') as stream:
data = yaml.load(stream)
inner_dict = [args.business_unit, args.platform, args.client]
for item in list(inner_dict):
data['policies'][0]['filters'][0]['tag:BUSINESS_UNIT'] = args.business_unit
data['policies'][0]['filters'][1]['tag:PLATFORM'] = args.platform
print json.dumps(data)
Current Result:
{
"policies": [
{
"resource": "ec2",
"name": "ec2age",
"filters": [
{
"tag:BUSINESS_UNIT": "TEST_FLITE",
"State.Name": "running"
},
{
"tag:ResourceCreatedBy": "present"
},
{
"and": [
{
"type": "instance-age",
"days": 30,
"op": "ge"
}
]
}
]
}
]
}
Desired Result:
{
"policies": [
{
"resource": "ec2",
"name": "ec2age",
"filters": [
{
"tag:BUSINESS_UNIT": "TEST_FLITE"
},
{
"tag:PLATFORM": "Android"
},
{
"State.Name": "running"
},
{
"tag:ResourceCreatedBy": "present"
},
{
"and": [
{
"type": "instance-age",
"days": 30,
"op": "ge"
}
]
}
]
}
]
}