Exemple #1
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)
        resourcedetails = parseresourceyaml()
        print(" after readding from the yaml", resourcedetails)
        print("resorce region is", resourcedetails["customerName"]["region"])

        #AwsProvider(self, 'Aws', region='us-east-1')
        AwsProvider(self,
                    'Aws',
                    region=resourcedetails["customerName"]["region"])

        helloInstance = Instance(self,
                                 'hello',
                                 ami="ami-2757f631",
                                 instance_type="t2.micro",
                                 tags={
                                     "Name": "Provisioned by Python",
                                     "Creator": "CDKTF-Python"
                                 })

        Vpc(self,
            'CustomVpc',
            name='custom-vpc',
            cidr='10.0.0.0/16',
            azs=["us-east-1a", "us-east-1b"],
            public_subnets=["10.0.1.0/24", "10.0.2.0/24"])

        TerraformOutput(self, 'hello_public_ip', value=helloInstance.public_ip)
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='eu-central-1')

        # bucketname = 'cdktest-wiwa'
        # TerraformAwsModulesS3BucketAws(self, 'bucket', bucket = bucketname)

        my_vpc = TerraformAwsModulesVpcAws(self,
                                           id='vpc',
                                           name="test-vpc",
                                           cidr="10.0.0.0/16",
                                           azs=["eu-central-1a"],
                                           public_subnets=["10.0.101.0/24"])

        newInstance = Instance(self,
                               'pythondemo',
                               ami="ami-0a02ee601d742e89f",
                               instance_type="t2.micro",
                               availability_zone="eu-central-1a",
                               associate_public_ip_address=True,
                               tags={"Name": "Python-Demo-updated"},
                               user_data=user_data,
                               subnet_id=my_vpc.public_subnets_output)

        TerraformOutput(self,
                        'pythondemo_public_ip',
                        value=newInstance.public_ip)
Exemple #3
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

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

        # create EC2 instance
        helloInstance = Instance(self,
                                 'hello',
                                 ami="ami-0742b4e673072066f",
                                 instance_type="t2.micro",
                                 tags={
                                     "Name": "Provisioned by CDKTF",
                                     "user": "******"
                                 })
        # create S3 bucket
        bucket = S3Bucket(self, 'my_bucket', bucket="nathan.bekenov.labs")

        # Outputs
        public_ip = TerraformOutput(self,
                                    'hello_public_ip',
                                    value=helloInstance.public_ip)

        bucket_name = TerraformOutput(self,
                                      'hello_bucket_name',
                                      value=bucket.bucket)
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'AWS', region='us-east-1')
        Instance(self,
                 "Hello World From Terraform Class via Python",
                 ami="ami-2757f631",
                 instance_type="t2.micro")
Exemple #5
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='us-west-1')
        helloInstance = Instance(
            self,
            'hello',
            ami="ami-031b673f443c2172c",
            instance_type="t2.micro",
        )

        TerraformOutput(self, 'hello_public_ip', value=helloInstance.public_ip)
Exemple #6
0
  def __init__(self, scope: Construct, ns: str):
    super().__init__(scope, ns)

    AwsProvider(self, 'Aws', region='us-east-1')
    helloInstance = Instance(self, 'hello',
      ami="ami-2757f631",
      instance_type="t2.micro",
      subnet_id= "subnet-0a9820d8725d1ca85"
    )

    TerraformOutput(self, 'hello_public_ip',
      value=helloInstance.public_ip
    )
    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)
    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)
Exemple #9
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        devopsKeyPair = KeyPair(
            self,
            "DevopsKeyPair",
            public_key="",
            key_name="",
        )

        devopsEC2 = Instance(
            self,
            "DevopsEC2",
            count=1,
            ami="ami-0f2c95e9fe3f8f80e",
            instance_type="t2.micro",
            # Instance Configuration
            ## if want spot instance, use "spot_instance_request" resource
            subnet_id="${variable.pub_subnet_id[0]}",
            ## Public IP associate
            associate_public_ip_address=False,
            ## IAM name
            ############################## iam_instance_profile="",
            ## Shutdown case : stop or terminate
            instance_initiated_shutdown_behavior="terminate",
            ## 종료우발 방지
            disable_api_termination=True,
            ## Monitoring using CloudWatch
            monitoring=False,
            ## Tenancy:
            ### tenancy = ,
            ## Detail Option
            metadata_options=[
                InstanceMetadataOptions(
                    http_endpoint="enabled",
                    http_put_response_hop_limit=1,
                    http_tokens="optional",
                )
            ],
            ## User Data
            # user_data = "",
            # Add Storage
            root_block_device=[
                ## Root Device
                InstanceRootBlockDevice(
                    volume_type="gp2",
                    # size: GiB
                    volume_size=8,
                    # Only valid for volume_type is io1, io2, gp3
                    ## iops = ,
                    # Only valid for volume_type is gp3
                    ## throughput = ,
                    delete_on_termination=True,
                    # KMS 암호화
                    ## encrypted = ,
                    ## kms_key_id = ,
                )
            ],
            ## ebs_block_device = [],
            ## ebs_optimized =
            # Add Tag
            # Config Security Group
            security_groups=["${var.sg_id}"],
            #
            key_name=devopsKeyPair.key_name,
            # Tag
            tags={"Name": "devopsEC2"},
        )

        TerraformVariable(
            self,
            # default=
            "vpc_id",
            description="VPC ID",
            type="string",
        )

        TerraformVariable(self, "pub_subnet_id", type="list(string)")

        TerraformVariable(self, "sg_id", type="string")