Example #1
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='us-west-2')

        my_vpc = Vpc(
            self,
            'MyVpc',
            name='my-vpc',
            cidr='10.0.0.0/16',
            azs=['us-west-2a', 'us-west-2b', 'us-west-2c'],
            private_subnets=['10.0.1.0/24', '10.0.2.0/24', '10.0.3.0/24'],
            public_subnets=['10.0.101.0/24', '10.0.102.0/24', '10.0.103.0/24'],
            enable_nat_gateway=True)

        my_eks = Eks(self,
                     'MyEks',
                     cluster_name='my-eks',
                     subnets=Token().as_list(my_vpc.private_subnets_output),
                     vpc_id=Token().as_string(my_vpc.vpc_id_output),
                     manage_aws_auth=False,
                     cluster_version='1.17')

        TerraformOutput(self,
                        'cluster_endpoint',
                        value=my_eks.cluster_endpoint_output)

        TerraformOutput(self,
                        'create_user_arn',
                        value=DataAwsCallerIdentity(self, 'current').arn)
Example #2
0
 def _eks_cluster(self):
     return Eks(self,
                'TestEksCluster',
                cluster_name='test-eks-cluster',
                subnets=Token().as_list(
                    self.eks_cluster_vpc.private_subnets_output),
                vpc_id=Token().as_string(
                    self.eks_cluster_vpc.vpc_id_output),
                manage_aws_auth=False,
                cluster_version=CLUSTER_VERSION,
                node_groups=self._node_groups(),
                tags=TAGS)
Example #3
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # define resources here
        loca = "West Europe"
        add_space = ["10.12.0.0/27"]
        rg_name = "example-rg"
        tag = {"ENV": "Dev", "PROJECT": "AZ_TF"}


        AzurermProvider(self, "Azurerm",\
            features=[{}]
            )

        example_rg = ResourceGroup(self, 'example-rg',\
            name=rg_name,
            location = loca,
            tags = tag
            )

        example_vnet = VirtualNetwork(self, 'example_vnet',\
            depends_on =[example_rg],
            name="example_vnet",
            location=loca,
            address_space=add_space,
            resource_group_name=Token().as_string(example_rg.name),
            tags = tag
            )

        TerraformOutput(self, 'vnet_id', value=example_vnet.id)
Example #4
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # define resources here
        instanceUserData = '#!/bin/bash\r\n' \
                            'echo "Hello, World From Python Form Terraform CDK " > index.html\r\n'\
                            'nohup busybox httpd -f -p 80 &\r\n'

        AwsProvider(self, 'Aws', region='us-east-1')
        ingress_allow = SecurityGroupIngress(cidr_blocks=['0.0.0.0/0'],
                                             ipv6_cidr_blocks=[],
                                             protocol='tcp',
                                             from_port=80,
                                             to_port=80,
                                             description="Allow",
                                             prefix_list_ids=[],
                                             security_groups=[],
                                             self_attribute=False)

        egress_allow = SecurityGroupEgress(cidr_blocks=['0.0.0.0/0'],
                                           ipv6_cidr_blocks=[],
                                           protocol='-1',
                                           from_port=0,
                                           to_port=0,
                                           prefix_list_ids=[],
                                           security_groups=[],
                                           self_attribute=False)

        secGroup = SecurityGroup(self,
                                 'web_server',
                                 name="allow_web_traffic",
                                 ingress=[ingress_allow],
                                 egress=[egress_allow])
        instance = Instance(
            self,
            "hello",
            ami="ami-2757f631",
            instance_type="t2.micro",
            vpc_security_group_ids=[Token.as_string(secGroup.id)],
            user_data=instanceUserData,
            tags=["Name", "Terraform-CDK WebServer"])

        TerraformOutput(self, 'public_dns', value=instance.public_dns)
Example #5
0
    def __init__(self, scope, id):
        super().__init__(scope, id)
        edge.EdgeProvider(self,
                          "edge",
                          reqstr="reqstr",
                          reqnum=123,
                          reqbool=True)

        res = edge.OptionalAttributeResource(self, "test")
        list = edge.ListBlockResource(self,
                                      "list",
                                      req=[{
                                          "reqbool": True,
                                          "reqnum": 1,
                                          "reqstr": "reqstr"
                                      }, {
                                          "reqbool": False,
                                          "reqnum": 0,
                                          "reqstr": "reqstr2"
                                      }],
                                      singlereq={
                                          "reqbool": False,
                                          "reqnum": 1,
                                          "reqstr": "reqstr"
                                      })
        map = edge.MapResource(self,
                               "map",
                               opt_map={"key1": "value1"},
                               req_map={"key1": True})
        set = edge.SetBlockResource(self,
                                    "set_block",
                                    set=[{
                                        "reqbool": True,
                                        "reqnum": 1,
                                        "reqstr": "reqstr"
                                    }, {
                                        "reqbool": False,
                                        "reqnum": 0,
                                        "reqstr": "reqstr2"
                                    }])

        # plain values
        edge.RequiredAttributeResource(self,
                                       "plain",
                                       bool=res.bool,
                                       str=res.str,
                                       num=res.num,
                                       str_list=res.str_list,
                                       num_list=res.num_list,
                                       bool_list=res.bool_list)

        # required values FROM required single item lists
        edge.RequiredAttributeResource(self,
                                       "from_single_list",
                                       bool=list.singlereq.reqbool,
                                       str=list.singlereq.reqstr,
                                       num=list.singlereq.reqnum,
                                       str_list=[list.singlereq.reqstr],
                                       num_list=[list.singlereq.reqnum],
                                       bool_list=[list.singlereq.reqbool])

        # required values FROM required multi item lists
        edge.RequiredAttributeResource(
            self,
            "from_list",
            bool=Token().as_any(
                Fn.lookup(Fn.element(list.req, 0), "reqbool", False)),
            str=Token().as_string(
                Fn.lookup(Fn.element(list.req, 0), "reqstr", "fallback")),
            num=Token().as_number(
                Fn.lookup(Fn.element(list.req, 0), "reqnum", 0)),
            str_list=[
                Token().as_string(
                    Fn.lookup(Fn.element(list.req, 0), "reqstr", "fallback"))
            ],
            num_list=[
                Token().as_number(
                    Fn.lookup(Fn.element(list.req, 0), "reqnum", 0))
            ],
            bool_list=[
                Token().as_any(
                    Fn.lookup(Fn.element(list.req, 0), "reqbool", False))
            ])

        # passing a reference to a complete list
        edge.ListBlockResource(self,
                               "list_reference",
                               req=list.req,
                               singlereq=list.singlereq)

        # passing a literal array with references for a list
        edge.ListBlockResource(self,
                               "list_literal",
                               req=[list.singlereq],
                               singlereq=list.singlereq)

        # required values FROM map
        edge.RequiredAttributeResource(
            self,
            "from_map",
            bool=Token().as_any(Fn.lookup(map.req_map, "key1", False)),
            str=Token().as_string(Fn.lookup(map.opt_map, "key1", "missing")),
            num=Token().as_number(Fn.lookup(map.computed_map, "key1", 0)),
            str_list=[
                Token().as_string(Fn.lookup(map.opt_map, "key1", "missing"))
            ],
            num_list=[
                Token().as_number(Fn.lookup(map.computed_map, "key1", 0))
            ],
            bool_list=[Token().as_any(Fn.lookup(map.req_map, "key1", False))])

        # passing a reference to a complete map
        edge.MapResource(self,
                         "map_reference",
                         opt_map=map.opt_map,
                         req_map=map.req_map)

        # passing a list ref into a set
        edge.SetBlockResource(self, "set_from_list", set=list.req)

        # passing a set ref into a list
        edge.ListBlockResource(self,
                               "list_from_set",
                               req=set.set,
                               singlereq={
                                   "reqbool": True,
                                   "reqnum": 1,
                                   "reqstr": "reqstr"
                               })
Example #6
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AzurermProvider(self, "Azurerm", features={})

        resource_group = ResourceGroup(self,
                                       vars.rg_name,
                                       name=vars.rg_name,
                                       location=vars.location,
                                       tags=vars.tag)

        aks_cluster = KubernetesCluster(self,
                                        vars.k8s_cluster_name,
                                        name=vars.k8s_cluster_name,
                                        location=vars.location,
                                        resource_group_name=Token().as_string(
                                            resource_group.name),
                                        dns_prefix=vars.stack_name,
                                        default_node_pool={
                                            "name": "default",
                                            "node_count": 2,
                                            "vm_size": "standard_d2_v4"
                                        },
                                        identity={"type": "SystemAssigned"},
                                        tags=vars.tag)

        cog_account = CognitiveAccount(self,
                                       vars.cog_name,
                                       name=vars.cog_name,
                                       location=vars.location,
                                       resource_group_name=Token().as_string(
                                           resource_group.name),
                                       kind="TextAnalytics",
                                       sku_name="F0",
                                       custom_subdomain_name=vars.cog_name,
                                       public_network_access_enabled=True,
                                       tags=vars.tag)

        container = ContainerRegistry(self,
                                      vars.container_reg_name,
                                      name=vars.container_reg_name,
                                      location=vars.location,
                                      resource_group_name=Token().as_string(
                                          resource_group.name),
                                      sku="Basic")

        client_config = DataAzurermClientConfig(self, "current")

        key_vault = KeyVault(
            self,
            vars.key_vault_name,
            name=vars.key_vault_name,
            location=vars.location,
            resource_group_name=Token().as_string(resource_group.name),
            tenant_id=client_config.tenant_id,
            sku_name="premium",
            access_policy=[
                KeyVaultAccessPolicy(tenant_id=client_config.tenant_id,
                                     object_id=client_config.object_id,
                                     key_permissions=[
                                         "Create",
                                         "Get",
                                     ],
                                     secret_permissions=[
                                         "Set", "Get", "Delete", "Purge",
                                         "Recover"
                                     ])
            ])

        cognitive_endpoint_secret = KeyVaultSecret(self,
                                                   vars.secret_endpoint,
                                                   name=vars.secret_endpoint,
                                                   value=cog_account.endpoint,
                                                   key_vault_id=key_vault.id)

        cognitive_key_secret = KeyVaultSecret(
            self,
            vars.secret_key,
            name=vars.secret_key,
            value=cog_account.primary_access_key,
            key_vault_id=key_vault.id)

        TerraformOutput(self, 'resource_group', value=resource_group.id)
        TerraformOutput(
            self,
            'container_id',
            value=container.id,
        )
        TerraformOutput(
            self,
            'container_url',
            value=container.login_server,
        )
        TerraformOutput(self,
                        'cognitive_endpoint_secret_id',
                        value=cognitive_endpoint_secret.id)
        TerraformOutput(self,
                        'cognitive_key_secret_id',
                        value=cognitive_key_secret.id)
Example #7
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='us-east-1')

        tags = {
            "CreateBy": "cdktf-samples-python",
            "SampleFrom": "https://github.com/shazi7804/cdktf-samples-python"
        }

        armAmi = DataAwsAmi(self,
                            'amazon-arm-linux',
                            most_recent=True,
                            owners=["amazon"],
                            filter=[{
                                "name": "root-device-type",
                                "values": ["ebs"]
                            }, {
                                "name": "virtualization-type",
                                "values": ["hvm"]
                            }, {
                                "name":
                                "name",
                                "values":
                                ["amzn2-ami-hvm-2.0.20200722.0-arm64*"]
                            }])

        # define resources here
        vpc = Vpc(self,
                  'vpc',
                  enable_dns_hostnames=True,
                  cidr_block='10.0.0.0/16',
                  tags=tags)

        igw = InternetGateway(self,
                              'internetGateway',
                              vpc_id=Token().as_string(vpc.id),
                              tags=tags)

        subnet = Subnet(self,
                        'subnet',
                        vpc_id=Token().as_string(vpc.id),
                        cidr_block="10.0.0.0/24",
                        availability_zone="us-east-1a",
                        map_public_ip_on_launch=True,
                        tags=tags)

        routeTable = DefaultRouteTable(
            self,
            'routeTable',
            default_route_table_id=Token().as_string(
                vpc.default_route_table_id),
            tags=tags)

        route = Route(self,
                      'route',
                      route_table_id=Token().as_string(routeTable.id),
                      destination_cidr_block="0.0.0.0/0",
                      gateway_id=Token().as_string(igw.id))

        # instance resources
        sg = SecurityGroup(self,
                           'bastionSecurityGroup',
                           name="bastion-sg",
                           vpc_id=Token().as_string(vpc.id),
                           tags=tags)

        sgInboundRule = SecurityGroupRule(self,
                                          'bastionInbound',
                                          type="ingress",
                                          cidr_blocks=["0.0.0.0/0"],
                                          from_port=22,
                                          to_port=22,
                                          protocol="ssh",
                                          security_group_id=Token().as_string(
                                              sg.id))

        sgOutboundRule = SecurityGroupRule(self,
                                           'bastionOutbound',
                                           type="egress",
                                           cidr_blocks=["0.0.0.0/0"],
                                           from_port=0,
                                           to_port=65535,
                                           protocol="-1",
                                           security_group_id=Token().as_string(
                                               sg.id))

        # reading JSON policy to create sts assuume role
        with open('templates/ec2_assume_role_policy.json') as data:
            sts_assume_policy = json.load(data)
            role = IamRole(self,
                           'bastionRole',
                           assume_role_policy=str(
                               json.dumps(sts_assume_policy)))

        # iterating through config to create policy attachment objects
        manage_policies = {
            "ssm": 'arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM',
            "s3": 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
        }

        for policy, arn in manage_policies.items():
            IamRolePolicyAttachment(self,
                                    'bastion-{0}-attachment'.format(policy),
                                    role=role.id,
                                    policy_arn=arn)

        instance_profile = IamInstanceProfile(self,
                                              'instanceProfile',
                                              role=role.id)

        bastion = Instance(self,
                           'bastion',
                           ami=armAmi.id,
                           instance_type="t4g.nano",
                           subnet_id=Token().as_string(subnet.id),
                           vpc_security_group_ids=[Token().as_string(sg.id)],
                           iam_instance_profile=instance_profile.id,
                           tags=tags)

        TerraformOutput(self, 'bastion_public_ip', value=bastion.public_ip)
Example #8
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AzurermProvider(self, "Azurerm", features={})

        resource_group = ResourceGroup(self,
                                       vars.rg_name,
                                       name=vars.rg_name,
                                       location=vars.location,
                                       tags=vars.tag)

        storage_acount = StorageAccount(self,
                                        vars.storage_name,
                                        name=vars.storage_name,
                                        location=vars.location,
                                        resource_group_name=Token().as_string(
                                            resource_group.name),
                                        account_tier="Standard",
                                        account_kind="Storage",
                                        account_replication_type="LRS")

        containers = [
            "azure-webjobs-hosts", "azure-webjobs-secrets", "scm-releases"
        ]
        for container in containers:
            StorageContainer(self,
                             container,
                             name=container,
                             storage_account_name=storage_acount.name,
                             container_access_type="private")

        app_insights = ApplicationInsights(
            self,
            vars.ap_name,
            name=vars.ap_name,
            location=vars.location,
            resource_group_name=Token().as_string(resource_group.name),
            application_type="web")

        service_plan = AppServicePlan(self,
                                      vars.sp_name,
                                      name=vars.sp_name,
                                      location=vars.location,
                                      resource_group_name=Token().as_string(
                                          resource_group.name),
                                      kind="FunctionApp",
                                      reserved=True,
                                      sku={
                                          "tier": "Dynamic",
                                          "size": "Y1"
                                      })

        FunctionApp(
            self,
            vars.function_name,
            name=vars.function_name,
            location=vars.location,
            resource_group_name=Token().as_string(resource_group.name),
            app_service_plan_id=service_plan.id,
            storage_account_name=Token().as_string(storage_acount.name),
            storage_account_access_key=storage_acount.primary_access_key,
            https_only=True,
            version="~4",
            os_type="linux",
            app_settings={
                "FUNCTIONS_WORKER_RUNTIME": "python",
                "APPINSIGHTS_INSTRUMENTATIONKEY":
                f"{app_insights.instrumentation_key}",
                "AzureWebJobsStorage": storage_acount.primary_access_key,
                "AZURE_LANGUAGE_ENDPOINT": vars.azure_language_endpoint,
                "AZURE_LANGUAGE_KEY": vars.azure_language_key
            },
            site_config={
                "linux_fx_version": "Python|3.8",
                "ftps_state": "Disabled"
            })

        cog_account = CognitiveAccount(self,
                                       vars.cog_name,
                                       name=vars.cog_name,
                                       location=vars.location,
                                       resource_group_name=Token().as_string(
                                           resource_group.name),
                                       kind="TextAnalytics",
                                       sku_name="F0",
                                       custom_subdomain_name=vars.cog_name,
                                       public_network_access_enabled=True,
                                       tags=vars.tag)

        TerraformOutput(self, 'cognitive_endpoint', value=cog_account.endpoint)