import json import logging import os import dotmap import sh import sys fmt = logging.Formatter('[%(levelname)s]%(asctime)s %(filename)s:%(lineno)d: %(message)s') hdlr = logging.StreamHandler(sys.stdout) hdlr.setFormatter(fmt) hdlr2 = logging.StreamHandler(open('./deleting-network-vpc-info.log', 'w')) hdlr2.setFormatter(fmt) logger = logging.getLogger("main") logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) def delete_vpc(vpc, output_file): logger.debug(f'try to delete vpc: {vpc}') # install aws-delete-vpc by running `go install github.com/ideascf/aws-delete-vpc` aws_delete_vpc = sh.Command('aws-delete-vpc') env = os.environ.copy() env.update({ 'AWS_PROFILE': vpc.account_id, }) running_cmd = aws_delete_vpc( '--vpc-id', vpc.vpc, '--region', vpc.region, # '--dry-run', _env=env, _out=output_file, _err=output_file, _return_cmd=True) print(type(running_cmd), running_cmd, type(aws_delete_vpc), aws_delete_vpc) running_cmd.wait() logger.debug(f"running cmd: {running_cmd}, exit_code: {running_cmd.exit_code}") def main(): # get data from 'inspect_on_networks_result.json' # cat inspect_on_networks_result.json | jq '[.[] | {vpc:.info.vpc, account_id:.info.account_id, provider:.info.provider, region:.info.region, phase:.phase}]' > deleting-network-vpc-info.json # vpcs = json.load(open('./deleting-network-vpc-info.json', 'r')) with open('./deleting-network-vpc-output.log', 'a+') as output_file: for each in vpcs: vpc = dotmap.DotMap(each) if vpc.provider != 'eks': continue output_file.write('####' + json.dumps(each) + '\n') output_file.flush() delete_vpc(vpc, output_file) if __name__ == '__main__': main()