如何访问 CDK 创建的 EC2 实例?

Jay*_*tta 6 amazon-web-services aws-cdk

我正在使用此 CDK 类配置基础设施:

// 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,
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

当我检查 AWS 面板时,我看到创建的实例没有密钥对。

在这种情况下如何访问实例?

Jay*_*tta 11

您可以转到您的 AWS 账户 > EC2 > 密钥对,创建一个新的密钥对,然后您可以将密钥名称传递给正在创建的集群:

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
        })
Run Code Online (Sandbox Code Playgroud)

我通过阅读有关 CloudFormation 的这篇文章得到了这个想法。

  • 对,就是那样。另外,显然请确保为 SSH 入站打开端口 22。您可以通过定义安全组及其入站规则或使用“.connections.allowFrom”来完成此操作 (2认同)