CDK python examples

Basic infrastructure that defines  initial configuration, connections, key name to grant SSH access and use a static elastic IP

import aws_cdk.aws_ec2 as ec2
# import aws_cdk.aws_ec2.Port as Port
import aws_cdk.aws_iam as iam
from aws_cdk import (
    # Duration,
    Stack, Duration,
    # aws_sqs as sqs,
)
from aws_cdk.aws_ec2 import (Peer, Port)
from constructs import Construct
 
 
class PythonCdkBasicStack(Stack):
    EXISTING_VPC_ID = 'vpc-XXXXXXXXXX'
    PUBLIC_KEY_MATERIAL = 'ssh-rsa XXXXXXXXXX'
 
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
 
        # Use an existing vpc
        vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=self.EXISTING_VPC_ID)
        print(f'vpc={vpc}')
 
        # Define a new security group 
        security_group = ec2.SecurityGroup(self, "SpringBootRedisDockerSG",
                                           vpc=vpc
                                           )
        # Allow connections from the peer on the given ports
 
        security_group.connections.allow_from(Peer.ipv4('XX.XX.XX.XX./32'),
                                              Port.tcp(22), "SSH Access from local David", )
        security_group.connections.allow_from(Peer.ipv4('0.0.0.0/0'),
                                              Port.tcp_range(80, 90), "Access from any IP to "
                                                                      "application ports", )
 
        # Use an existing key pair
        cfn_key_pair = ec2.CfnKeyPair(self, "MyCfnKeyPair",
                                      key_name="key_pair_name",
                                      public_key_material=self.PUBLIC_KEY_MATERIAL,
                                      )
        # AMI
        # I specify all attributes for the Linux machine to prevent from using a costly Linux 
        # instance
        amzn_linux = ec2.MachineImage.latest_amazon_linux(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
                edition=ec2.AmazonLinuxEdition.STANDARD,
                virtualization=ec2.AmazonLinuxVirt.HVM,
                storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE,
        )
        print(f'amzn_linux={amzn_linux}')
 
        # define a Role and SSM Managed Policy for the instance 
        role = iam.Role(self,
                        "InstanceSSM",
                        assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
        role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(
                "AmazonSSMManagedInstanceCore"))
        print(f'role={role}')
 
        handle = ec2.InitServiceRestartHandle()
        # Instance config init
        config_sets = ec2.CloudFormationInit.from_config_sets(
                config_sets={
                        # Applies the configs below in this order
                        "default": ["yum_preinstall", "config"]
                },
                configs={
                        "yum_preinstall": ec2.InitConfig([
                                # Install an Amazon Linux package using yum
                                ec2.InitPackage.yum("git", service_restart_handles=[handle]),
                                ec2.InitPackage.yum("docker", service_restart_handles=[handle]),
                                ec2.InitPackage.yum("htop", service_restart_handles=[handle]),
                                ec2.InitService.enable("docker",
                                                       service_restart_handle=handle)
                        ]),
                        "config": ec2.InitConfig([
                                # Create a JSON file from tokens (can also 
                                # create other files)
                                ec2.InitFile.from_object("/etc/stack.json", {
                                        "stack_id": Stack.of(self).stack_id,
                                        "stack_name": Stack.of(self).stack_name,
                                        "region": Stack.of(self).region
                                }),
 
                                # Create a group and user
                                ec2.InitGroup.from_name("my-group"),
                                ec2.InitUser.from_name("my-user"),
 
                                # Install an RPM from the internet
                                ec2.InitPackage.rpm(
                                        "http://mirrors.ukfast.co.uk/sites/dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/r/rubygem-git-1.5.0-2.el8.noarch.rpm"),
                                ec2.InitCommand.shell_command(
                                        "sudo usermod -a -G docker ec2-user",
                                        service_restart_handles=[handle])
                        ])
                },
        )
        init_options = ec2.ApplyCloudFormationInitOptions(
                # Optional, which configsets to activate (['default'] by default)
                config_sets=["default"],
 
                # Optional, how long the installation is expected to take (5 minutes by default)
                timeout=Duration.minutes(6),
 
        )
        # Define the instance
        instance = ec2.Instance(self, "Instance",
                                instance_type=ec2.InstanceType("t2.micro"),
                                machine_image=amzn_linux,
                                vpc=vpc,
                                role=role,
                                init=config_sets,
                                security_group=security_group,
                                key_name=cfn_key_pair.key_name,
                                init_options=init_options
                                )
        print(f'instance={instance}')
 
        # Assign an elastic ip (static) to the instance
        cfn_eIPAssociation = ec2.CfnEIPAssociation(self, "MyCfnEIPAssociation",
                                                   allocation_id="eipalloc-elastic-IP",
                                                   instance_id=instance.instance_id)
        print(f'cfn_eIPAssociation={cfn_eIPAssociation}'
Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *