Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access an EC2 instance created by CDK?

I am provisioning an infrastructure using this CDK class:

// imports

export interface AppStackProps extends cdk.StackProps {
    repository: ecr.Repository
}

export class AppStack extends cdk.Stack {
    public readonly service: ecs.BaseService

    constructor(app: cdk.App, id: string, props: AppStackProps) {
        super(app, id, props)

        const vpc = new ec2.Vpc(this, 'main', { maxAzs: 2 })

        const cluster = new ecs.Cluster(this, 'x-workers', { vpc })
        cluster.addCapacity('x-workers-asg', {
            instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO)
        })

        const logging = new ecs.AwsLogDriver({ streamPrefix: "x-logs", logRetention: logs.RetentionDays.ONE_DAY })

        const taskDef = new ecs.Ec2TaskDefinition(this, "x-task")
        taskDef.addContainer("x-container", {
            image: ecs.ContainerImage.fromEcrRepository(props.repository),
            memoryLimitMiB: 512,
            logging,
        })

        this.service = new ecs.Ec2Service(this, "x-service", {
            cluster,
            taskDefinition: taskDef,
        })
    }
}

When I check the AWS panel, I see the instance created without a key pair.

How can I access the instance in this case?

like image 686
Jayr Motta Avatar asked Aug 20 '19 10:08

Jayr Motta


1 Answers

You can go to your AWS account > EC2 > Key Pairs, create a new key pair and then you can pass the key name to the cluster being created:

const cluster = new ecs.Cluster(this, 'x-workers', { vpc })
        cluster.addCapacity('x-workers-asg', {
            instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
            keyName: "x" // this can be a parameter if you prefer
        })

I got this idea by reading this article on CloudFormation.

like image 135
Jayr Motta Avatar answered Sep 23 '22 15:09

Jayr Motta