📚

ローカルJsonからCDKに読み込む

2021/05/25に公開

JSONファイル

{
    "name":"vpc",
    "vpc_cidr": "10.16.0.0/16",
    "max_azs": 1,
    "nat_gateways":1,
    "ec2.SubnetConfiguration": [{
            "subnet_type": "PUBLIC",
            "name": "PUBLIC",
            "cidr_mask": 24
        },
        {
            "subnet_type": "PRIVATE",
            "name": "PRIVATE",
            "cidr_mask": 24
        }
    ]
}

ローカルのJSONファイルを呼び出す

def loadjson(filename): 
        filename = os.path.dirname(__file__) + '\\' +filename
        json_load = json.load(open(filename, 'r'))
        return json_load

VpcStackという関数

from aws_cdk import core
import aws_cdk.aws_ec2 as ec2
#vpcというパスにutils.pyというファイルをというloadjson関数を保管
from vpc.utils import loadjson 

class VpcStack(core.Stack):
    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs) 
        
        json=loadjson('test.json')
        loadconf = json["ec2.SubnetConfiguration"]
        i = 0
        subnet = list()
        while i < len(loadconf):
            if loadconf[i]["subnet_type"] == "PRIVATE" :
                    type = ec2.SubnetType.PRIVATE
            elif loadconf[i]["subnet_type"] == "PUBLIC" :
                    type = ec2.SubnetType.PUBLIC
            elif loadconf[i]["subnet_type"] == "ISOLATED" :
                    type = ec2.SubnetType.ISOLATED
            
            subnet.append(
                              ec2.SubnetConfiguration
                            (
                               subnet_type=type,
                               name=loadconf[i]["name"],
                               cidr_mask=loadconf[i]["cidr_mask"]
                            )
            )
            i += 1

        self.vpc = ec2.Vpc(self, "VPC",
                           max_azs=json["max_azs"],
                           cidr=json["vpc_cidr"],
                           subnet_configuration=subnet,
                           nat_gateways=json["nat_gateways"]                        
                           )
        core.CfnOutput(self, "Output",
                       value=self.vpc.vpc_id)

Discussion