Пример #1
0
    def __create_iam_role(self):
        """
        Private helper method to create IAM role for AWS Config
        """
        # use default region for provider since IAM is a global resource
        region = "us-gov-west-1" if "gov" in self.partition else "us-east-1"
        AwsProvider(self,
                    f"iam-aws-{region}",
                    region=region,
                    profile=self.profile_name)
        assume_role_policy = {
            "Version":
            "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": {
                    "Service": ["config.amazonaws.com"]
                },
                "Action": ["sts:AssumeRole"],
            }],
        }
        managed_policy_arn = (
            f"arn:{self.partition}:iam::aws:policy/service-role/AWS_ConfigRole"
        )

        aws_config_role = IamRole(
            self,
            "aws_config_role",
            name=f"{self.resource_prefix}-global-awsconfig-role",
            path="/",
            assume_role_policy=json.dumps(assume_role_policy),
            managed_policy_arns=[managed_policy_arn],
        )
        print(f"IAM role for AWS Config was creted in region = {region} ")
        return aws_config_role.arn
Пример #2
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)
Пример #3
0
    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)
Пример #4
0
    def create_region_policy(self, policy_name, rules_file, region, remediate: bool):
        """
        Create AWS Firewall Manager policy
        region scope -> ALB, ApiGateway
        remediate - if set True then auto remediate any noncompliant resources
        """
        aws = AwsProvider(self, f"aws-fms-{region}",
            region=region,
            profile=self.profile_name,
            alias = f"aws-{region}"
        )
        rules = self.__parse_rule(rules_file)

        region_policy = FmsPolicy(self,f"fms-regionpolicy-{policy_name}",
            name=policy_name,
            exclude_resource_tags=False,
            resource_type_list = [
                "AWS::ElasticLoadBalancingV2::LoadBalancer",
                "AWS::ApiGateway::Stage"
            ],
            security_service_policy_data = [
                FmsPolicySecurityServicePolicyData(
                    type="WAFV2",
                    managed_service_data = json.dumps(rules)
                )
            ],
            remediation_enabled=remediate,
            provider = aws
        )
        region_policy.override_logical_id(f"fms-regionpolicy-{policy_name}")
Пример #5
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)
Пример #6
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)
Пример #7
0
    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")
Пример #8
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region=AWS_REGION)

        self.eks_cluster_vpc = self._eks_cluster_vpc()
        self.eks_cluster = self._eks_cluster()
        self.tf_outputs = self._tf_outputs()
Пример #9
0
    def enable_awsconfig_in_region(
        self,
        region,
        bucket_name,
        include_global_resources,
        create_role=True,
        iam_role_arn=None,
        topic_arn=None,
        frequency="Six_Hours",
    ):
        """
        Enables AWS config in specified region for a particular account
        """
        aws_provider = AwsProvider(
            self,
            f"aws-{region}",
            region=region,
            profile=self.profile_name,
            alias=f"aws-{region}",
        )
        if create_role:
            iam_role_arn = self.__create_iam_role()
        print(f"enabling AWS Config for region = {region} ...")

        recorder = ConfigConfigurationRecorder(
            self,
            f"recorder-{region}",
            role_arn=iam_role_arn,
            recording_group=[
                ConfigConfigurationRecorderRecordingGroup(
                    all_supported=True,
                    include_global_resource_types=include_global_resources,
                )
            ],
            provider=aws_provider,
        )
        delivery_channel = ConfigDeliveryChannel(
            self,
            f"delivery_channel-{region}",
            s3_bucket_name=bucket_name,
            snapshot_delivery_properties=[
                ConfigDeliveryChannelSnapshotDeliveryProperties(
                    delivery_frequency=frequency)
            ],
            sns_topic_arn=topic_arn,
            depends_on=[recorder],
            provider=aws_provider,
        )
        recorder_status = ConfigConfigurationRecorderStatus(
            self,
            f"recorder_status-{region}",
            is_enabled=True,
            name=recorder.name,
            depends_on=[delivery_channel],
            provider=aws_provider,
        )
        recorder_status.override_logical_id(f"recorder_status-{region}")
Пример #10
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='ap-northeast-2')

        Vpc(self, 'CustomVpc',
            name='custom-vpc',
            cidr='10.10.0.0/16',
            azs=["ap-northeast-1a", "ap-northeast-1c"],
            public_subnets=["10.10.1.0/24", "10.10.2.0/24"]
        )
Пример #11
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)
Пример #12
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

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

        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"]
            )
        SnsTopic(self, 'Topic', display_name='my-first-sns-topic')
Пример #13
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
    )
Пример #14
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

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

        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"]
            )
        SnsTopic(self, 'Topic', display_name='my-first-sns-topic')
        role = IamRole(self, 'Role', name='lambda-role', assume_role_policy='{}')
        LambdaFunction(self, 'Lambda', function_name='my-first-lambda-function', role=role.arn, handler='index.handler', runtime='python3.6')
Пример #15
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        AwsProvider(self, 'Aws', region='eu-central-1')
        topic = SnsTopic(self, 'Topic', display_name='overwritten')
        topic.add_override('display_name', 'my-first-sns-topic')

        self.add_override('terraform.backend', {
            'remote': {
                'organization': 'test',
                'workspaces': {
                    'name': 'test'
                }
            }
        })
Пример #16
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # Defining my provider
        AwsProvider(self, "AWS", region="us-west-2")

        # Creating the ECS Cluster
        ecs_cluster = EcsCluster(self,
                                 "CftC",
                                 name="ContainersFromTheCouchLive")

        # Creating a task definition for the nginx service
        task_definition = EcsTaskDefinition(
            self,
            "TaskDef",
            container_definitions="""[
              {
                "name": "nginx",
                "image": "nginx:latest",
                "essential": true,
                "portMappings": [
                  {
                    "containerPort": 80,
                    "hostPort": 80
                  }
                ]
              }
            ]""",
            family="cfclatest",
            requires_compatibilities=["FARGATE"],
            network_mode="awsvpc",
            cpu="512",
            memory="2048")

        # Creating an ECS service
        EcsService(self,
                   "NginxService",
                   cluster=ecs_cluster.id,
                   name="nginx-service-latest",
                   desired_count=1,
                   task_definition=task_definition.arn,
                   network_configuration=[
                       EcsServiceNetworkConfiguration(
                           subnets=['<REPLACE>', '<REPLACE>'],
                           assign_public_ip=True,
                           security_groups=['<REPLACE>'])
                   ],
                   launch_type="FARGATE")
Пример #17
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # define resources here

        awsProvider = AwsProvider(self, "Aws", region="ap-northeast-2")
        vpcModule = TerraformHclModule(self, "VpcModule", source=".\\vpc")
        ec2Module = TerraformHclModule(
            self,
            "Ec2Module",
            source=".\\ec2",
            variables={
                "vpc_id": "${module.VpcModule.vpc_id}",
                "pub_subnet_id": "${module.VpcModule.pub_subnet_id}",
                "sg_id": "${module.VpcModule.sg_id}",
            },
        )
Пример #18
0
    def __init__(self, scope=Construct, ns=str):
        super().__init__(scope, ns)

        user_id = DataAwsCallerIdentity(self, "userId")
        AwsProvider(self, 'Aws', region=region)
        role = IamRole(
            self,
            "basic_lambda_role",
            description="Basic Lambda Execution Role",
            name=f"{stack_prefix}lambda_role",
            assume_role_policy=
            '{"Version": "2012-10-17", "Statement": [{"Action": "sts:AssumeRole", "Principal": {"Service": "lambda.amazonaws.com"}, "Effect": "Allow", "Sid": ""}]}'
        )
        api = ApiGatewayRestApi(self, "api-gateway", name="rest-api")
        resource = ApiGatewayResource(self,
                                      f"api-gateway-resource",
                                      rest_api_id=api.id,
                                      parent_id=api.root_resource_id,
                                      path_part="notes")

        get_notes = add_gateway_method(self, "GET", "get_notes_handler", api,
                                       resource, role.arn, user_id)
        add_note = add_gateway_method(self, "POST", "add_note_handler", api,
                                      resource, role.arn, user_id)
        delete_note = add_gateway_method(self, "DELETE", "delete_note_handler",
                                         api, resource, role.arn, user_id)

        deployment = ApiGatewayDeployment(
            self,
            f"{stack_prefix}api-gateway-deployment",
            rest_api_id=api.id,
            stage_name="dev",
            stage_description="Production Environment",
            depends_on=get_notes + add_note + delete_note)

        bucket_name = 'eladr-terraform-cdk-demo-bucket'
        bucket = S3Bucket(self,
                          's3_bucket',
                          bucket=bucket_name,
                          force_destroy=True)
        bucket.policy = f'{{"Version": "2012-10-17", "Statement": [{{"Action": "s3:*", "Resource" : "arn:aws:s3:::{bucket_name}/*", "Principal": {{"AWS": "{role.arn}"}}, "Effect": "Allow", "Sid": ""}}]}}'

        TerraformOutput(self, "endpoint", value=f"{deployment.invoke_url}")
        TerraformOutput(self, "bucket-arn", value=bucket.arn)
Пример #19
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)
Пример #20
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

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

        allow = SecurityGroupIngress(cidr_blocks=['8.8.8.8/32'],
                                     ipv6_cidr_blocks=[],
                                     protocol='tcp',
                                     from_port=5432,
                                     to_port=5432,
                                     description="Allow",
                                     prefix_list_ids=[],
                                     security_groups=[],
                                     self_attribute=False)

        sec_group_name = 'cdktf-sg-test'
        vpc_id = 'your-vpc-id'
        SecurityGroup(self, sec_group_name, vpc_id=vpc_id, ingress=[allow])
Пример #21
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        config = ConfigParser()
        config.read('bento.properties')

        bentoProvider = AwsProvider(
            self,
            'Aws',
            region=config[ns]['region'],
            profile=config[ns]['profile'],
            shared_credentials_file="/bento/creds/credentials")
        bentoTags = json.loads(config[ns]['tags'])

        # VPC
        bentoVPC = vpc.VPCResources.createResources(self, ns, config,
                                                    bentoTags)

        # IAM
        bentoIAM = iam.IAMResources.createResources(self, ns, bentoTags)

        # ECR
        bentoECR = ecr.ECRResources.createResources(self, ns, bentoTags)
Пример #22
0
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # define resources here
        AwsProvider(self, 'Aws', region='us-east-1')

        # SNS Topic
        BlogTopic = SnsTopic(self, 'Topic', display_name='panong-blog-cdktf')

        # CloudWatch Alarm
        CloudwatchMetricAlarm(self, 'PAnongBlogAlarm',
                                actions_enabled     = True,
                                alarm_actions       = [BlogTopic.arn],
                                alarm_name          = 'panong-blog-cdktf',
                                comparison_operator = 'GreaterThanOrEqualToThreshold',
                                evaluation_periods  = 1,
                                metric_name         = 'VpcEventCount',
                                namespace           = 'CloudTrailMetrics',
                                period              = 300,
                                statistic           = 'Sum',
                                threshold           = 1,
                                treat_missing_data  = 'notBreaching'
                              )
Пример #23
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)
Пример #24
0
    def __init__(self, scope: Construct, ns: str, profile_name, partition):
        super().__init__(scope, ns)

        self.profile_name = profile_name if profile_name else "default"
        region = "us-gov-west-1" if "gov" in partition else "us-east-1"
        AwsProvider(self, f"aws-{region}", region=region, profile=profile_name)