def __init__(self, scope: core.Construct, id: str, backup_bucket,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ubuntu_lts = ec2.MachineImage.generic_linux(
            {'eu-west-2': 'ami-0917237b4e71c5759'})
        vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id="vpc-60d9ad08")

        security_group = ec2.SecurityGroup(
            self,
            "MinecraftServer",
            vpc=vpc,
            description="minecraft server security group",
            allow_all_outbound=True)
        security_group.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22),
                                        "Allow ssh access")
        security_group.add_ingress_rule(ec2.Peer.any_ipv4(),
                                        ec2.Port.tcp(25565), "Spigot port")
        security_group.add_ingress_rule(ec2.Peer.any_ipv4(),
                                        ec2.Port.tcp(8123), "Dynmap")

        role = iam.Role(self,
                        "MinecraftServerRole",
                        assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
        role.add_to_policy(
            iam.PolicyStatement(resources=[
                backup_bucket.bucket_arn, backup_bucket.bucket_arn + "/*"
            ],
                                actions=[
                                    "s3:GetObject", "s3:ListBucket",
                                    "s3:PutObject", "s3:DeleteObject"
                                ]))

        instance = ec2.Instance(self,
                                "MinecraftEC2",
                                instance_type=ec2.InstanceType("t3.medium"),
                                machine_image=ubuntu_lts,
                                vpc=vpc,
                                security_group=security_group,
                                key_name="carwyn",
                                role=role)
        setup_file = open("./configure_minecraft.sh", "rb").read()
        instance.user_data.add_commands(str(setup_file, 'utf-8'))

        ec2.CfnEIPAssociation(self,
                              "MinecraftIp",
                              allocation_id="eipalloc-002456c0178e856c1",
                              instance_id=instance.instance_id)
Beispiel #2
0
    def createServer(self):
        volume = ec2.Volume(self, 'serverVolume2a',
            removal_policy=cdk.RemovalPolicy.RETAIN,
            volume_type=ec2.EbsDeviceVolumeType.GP3,
            availability_zone='us-west-2a',
            snapshot_id='snap-0ca71aed81fe73771',
            size=cdk.Size.gibibytes(16),
        )
        instance = ec2.Instance(self, 'serverVpcInstance',
            instance_type=ec2.InstanceType('t3a.small'),
            vpc=self.vpc,
            machine_image=ec2.MachineImage.generic_linux({
                'us-west-2': 'ami-03d5c68bab01f3496'
            }),
            role=self.serverRole,
            availability_zone='us-west-2a',
            key_name='tipbotkey', # must be created in advance
        )
        instance.apply_removal_policy(cdk.RemovalPolicy.RETAIN)

        instance.node.default_child.volumes = [
            ec2.CfnInstance.VolumeProperty(
                device='/dev/sda2',
                volume_id=volume.volume_id,
            )
        ]

        ec2.CfnEIPAssociation(self, 'serverVpcEIPAssociation',
            eip=ec2.CfnEIP(self, 'serverVpcEIP',
                domain='vpc',
                instance_id=instance.instance_id,
            ).ref,
            instance_id=instance.instance_id
        )

        cfnInstance = typing.cast(typing.Optional[ec2.CfnInstance], instance.node.default_child)
        cfnInstance.ipv6_addresses = [
            ec2.CfnInstance.InstanceIpv6AddressProperty(ipv6_address='2600:1f14:0741:4a00:fedc:ba98:7654:3210')
        ]
        # Need to attach this manually since we have a CfnSecurityGroup, not a SecurityGroup
        cfnInstance.security_group_ids = [
            cdk.Fn.get_att(self.securityGroup.logical_id, 'GroupId').to_string()
        ]
    def __init__(self, scope: core.Construct, construct_id: str,
                 imaging_sg: ec2.ISecurityGroup, imaging_ec2_role: iam.IRole,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # elastic ip
        eip = ec2.CfnEIP(self, "Imaging Server IP")

        core.Tags.of(eip).add(key="Name", value="Imaging Server EIP")

        # imaging ec2 instance

        #ami_id=ssm.StringParameter.value_from_lookup(self,"/linux/production/ami_id")

        itype = ec2.InstanceType("t3.nano")
        iami = ec2.MachineImage.from_ssm_parameter(
            "/linux/production/ami_id", os=ec2.OperatingSystemType.LINUX)
        default_vpc = ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True)

        imaging_ec2 = ec2.Instance(self,
                                   "ec2-instance",
                                   instance_type=itype,
                                   machine_image=iami,
                                   vpc=default_vpc,
                                   security_group=imaging_sg,
                                   role=imaging_ec2_role)

        # add tags
        core.Tags.of(imaging_ec2).add(key="Name",
                                      value="Linux-Prod-Imaging-Server")
        core.Tags.of(imaging_ec2).add(key="ami_id_parameter",
                                      value="/linux/production/ami_id")
        core.Tags.of(imaging_ec2).add(key="OS", value="linux")
        core.Tags.of(imaging_ec2).add(key="ServerGroup", value="production")
        core.Tags.of(imaging_ec2).add(key="Type", value="imaging_server")

        # attach eip
        ec2.CfnEIPAssociation(self,
                              "EIP Attachment",
                              eip=eip.ref,
                              instance_id=imaging_ec2.instance_id)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # get vpc used vpc-id
        vpc = ec2.Vpc.from_lookup(self, "EKSNode", vpc_id=vpc_id)

        subnets = []
        if len(vpc.private_subnets) > 0:
            subnets.extend(vpc.private_subnets)
        elif len(vpc.public_subnets) > 0:
            subnets.extend(vpc.public_subnets)
        else:
            print("Not any subnets found,")
            return

        # add a worker node role
        workerRole = iam.Role.from_role_arn(self,
                                            'nodeRole',
                                            role_arn=nodes_role_arn)

        #node_sg=ec2.SecurityGroup.from_security_group_id(self,"nodeSG",security_group_id='sg-0461d7bdfb942d0ef')

        # add iam instance profile
        instanceProfile = iam.CfnInstanceProfile(
            self,
            'kopsNodeProfile',
            roles=[workerRole.role_name],
            instance_profile_name='eks-cluster-workerNodeProfile')

        # read and base64 encode userdata file
        data = open('nodeup.sh', 'rb').read()
        encodedBytes = base64.encodebytes(data)
        encodedStr = str(encodedBytes, "utf-8")

        # add worker instances and associate EIPs
        for i in range(0, 1):
            # add a network interface
            eni0 = ec2.CfnNetworkInterface(
                self,
                'eni-' + str(i),
                subnet_id='subnet-040455b57b16a4cc9',
                group_set=['sg-0461d7bdfb942d0ef', 'sg-0b3ae225b27e04679'])

            # add worker instances
            instance = ec2.CfnInstance(
                self,
                "kops-node-" + str(i),
                image_id=ami_id,
                instance_type="t2.medium",
                block_device_mappings=[
                    {
                        'deviceName': '/dev/xvda',
                        'ebs': {
                            'deleteOnTermination': True,
                            'volumeSize': 40,
                            'volumeType': 'gp2',
                            'encrypted': False,
                        },
                    },
                    {
                        'deviceName': '/dev/sdb',  # for /var/lib/docker
                        'ebs': {
                            'deleteOnTermination': True,
                            'volumeSize': 100,
                            'volumeType': 'gp2',
                            'encrypted': False,
                        },
                    },
                    {
                        'deviceName': '/dev/sdc',  # for data volume
                        'ebs': {
                            'deleteOnTermination': True,
                            'volumeSize': 200,
                            'volumeType': 'gp2',
                            'encrypted': False,
                        },
                    },
                ],
                key_name=key_name,
                network_interfaces=[{
                    'deviceIndex': '0',
                    'networkInterfaceId': eni0.ref,
                }],
                iam_instance_profile=instanceProfile.ref,
                #iam_instance_profile=nodes_role_arn,
                tags=[
                    core.CfnTag(key="KubernetesCluster",
                                value="eks-asgfleet-01"),
                    core.CfnTag(key="Name", value="test-01"),
                    core.CfnTag(key="k8s.io/role/node", value="1"),
                    core.CfnTag(key="CDK/manual", value="singlenode"),
                ],
                user_data=encodedStr)

            #associate EIP with the instance
            eip = ec2.CfnEIP(self, "eip-" + str(i))
            ec2.CfnEIPAssociation(self,
                                  "eip-ass-i" + str(i),
                                  allocation_id=eip.attr_allocation_id,
                                  network_interface_id=eni0.ref)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        
        #create S3 access role for ec2 
        ec2Role = iam.Role(
            self, 
            "ec2role",
            assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"),
            managed_policies=[
                iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3ReadOnlyAccess")
            ]
        )

        instanceProfile = iam.CfnInstanceProfile(
            self,
            "ec2Profile",
            roles=[ec2Role.role_name],
            instance_profile_name="aws-cdk-handson-ec2Profile",

        )

        #create new VPC for lab02
        vpc= ec2.Vpc(self,id="aws-cdk-handson-vpc",cidr="172.30.0.0/16",nat_gateways=0,
        subnet_configuration=[ 
             { "cidrMask": 24,"name": "subnet-1-", "subnetType": ec2.SubnetType.PUBLIC },
             { "cidrMask": 24,"name": "subnet-2-", "subnetType": ec2.SubnetType.PUBLIC },
             { "cidrMask": 24,"name": "subnet-3-", "subnetType": ec2.SubnetType.PUBLIC }, 
            ])
                
        #create new Security Group
        sg = ec2.CfnSecurityGroup(
            self,
            "ec2securitygroup",
            group_description="this is aws-cdk-handson workshop",
            group_name="ec2securitygroup",
            security_group_ingress=[
                {
                    "ipProtocol": "tcp",
                    "fromPort": 80,
                    "toPort": 80,
                    "cidrIp": "0.0.0.0/0",
                },
                {
                    "ipProtocol": "tcp",
                    "fromPort": 22,
                    "toPort": 22,
                    "cidrIp": "0.0.0.0/0",
                },
            ],
            vpc_id=vpc.vpc_id
        )

        #create Elastic Network Interface
        eni0 = ec2.CfnNetworkInterface(
            self, "eni-" + str(1), subnet_id=vpc.public_subnets[0].subnet_id,
             #group_set=["sg-08cddeaeec7392eb2"]
             group_set=[sg.attr_group_id]
        )
          
        #read and base64 encode userdata file
        data = open("httpd.sh", "rb").read()
        encodedBytes = base64.encodebytes(data)
        encodedStr = str(encodedBytes, "utf-8")

        #create ec2 instances
        ami=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2)
        instance = ec2.CfnInstance(
            self,
            "ec2-httpd-" + str(1),
            image_id=ami.get_image(self).image_id, #use Amazon Linux 2 AMI 
            instance_type="t2.micro",
            key_name="wsu-ap-northeast-1",
            network_interfaces=[
                {
                    "deviceIndex": "0", 
                    "networkInterfaceId": eni0.ref
                }
            
            ],
            tags=[core.CfnTag(key="Name", value="aws-cdk-handson-ec2")],
            iam_instance_profile=instanceProfile.ref,
            user_data=encodedStr
           
        )
           
        #associate EIP with the instance
        eip = ec2.CfnEIP(self, "eip-" + str(1))
        ec2.CfnEIPAssociation(self, "eip-ass-i" + str(1),
                                 allocation_id=eip.attr_allocation_id,
                                 network_interface_id=eni0.ref)
        
        #Export PublicIP and PublicDNSName
        core.CfnOutput(self,"PublicIP",export_name="PublicIP",value=instance.attr_public_ip)
        core.CfnOutput(self,"PublicDNSName",export_name="PublicDNSName",value=instance.attr_public_dns_name)