How to Generate a Diagram Function in Python

Viewed 32

So I have a task, whereby which I am trying to generate a diagram for all of the VPC(s) in an AWS account and include their cidr_block as pertaining information. I have this one block in Python that returns the diagram for the account as well as two functions that return the vpc_id and the cidr_blocks. The block and two functions are as followed:

def parse_vpc_id_payload():
    with open('vpc_payload.json', 'r') as f:
        data = json.load(f)
        for i in data:
            print(i['VpcId'])

def parse_vpc_cidr_block_payload():
    with open('vpc_payload.json', 'r') as f:
        data = json.load(f)
        for i in data:
            print(i['CidrBlock'])

def companynetcluster():
    with Diagram(filename="images/net", show=False, direction="LR", graph_attr=graph_attr):
        with Cluster("impinjnet", graph_attr={"margin": "40", "fontsize": "18"}):
            companynet = OrganizationsAccount("Company-Net")                
            with Cluster("vpc-id1", graph_attr={"margin": "40", "fontsize": "18"}):
                net_subnet1 = PrivateSubnet("10.XXX.Y.Z/16")
            with Cluster("vpc-id2", graph_attr={"margin": "40", "fontsize": "18"}):
                net_subnet2 = PrivateSubnet("192.XXX.YYY.Z/24")
            companynet

The functions work, and so does the diagram block, the problem is I want to dynamically create the diagram block using some kind of a for loop and I do not know where to begin. Basically I need to create this block from the outputs I get from the two functions:

with Cluster("vpc-id1", graph_attr={"margin": "40", "fontsize": "18"}):
    net_subnet1 = PrivateSubnet("10.XXX.Y.Z/16")
with Cluster("vpc-id2", graph_attr={"margin": "40", "fontsize": "18"}):
    net_subnet2 = PrivateSubnet("192.XXX.YYY.Z/24")

So I would basically iterate over all VPCs and for each VPC make a cluster dynamically set the ID of the VPC and then for each additional VPC append the subnet value to the next net_subnet1 or net_subnet2 and I need the net_subnet to also be generated. I need a little help on how to get started on this...any advice would be greatly appreciated.

1 Answers

So I did the following to make it work, I made a diagram_block function that I could call in the cluster function:


def diagram_block():
    with open('vpc_payload.json', 'r') as f:
        data = json.load(f)
        for i in data:
            with Cluster(i['VpcId'], graph_attr={"margin": "40", "fontsize": "18"}):
                subnet = PrivateSubnet(i['CidrBlock'])

def accountcluster():
    with Diagram(filename="images/account", show=False, direction="LR", graph_attr=graph_attr):
        with Cluster("account", graph_attr={"margin": "40", "fontsize": "18"}):
            account = OrganizationsAccount("account")
            diagram_block()
            account

accountcluster()
Related