简体   繁体   English

使用 CDK 创建/关联 ssh 密钥对到 ec2 实例

[英]Create/associate ssh keypair to an ec2 instance with the CDK

I'm using the new Cloud Development Toolkit (CDK) to build an infrastructure on AWS using Java language.我正在使用新的云开发工具包 (CDK) 在 AWS 上使用 Java 语言构建基础设施。

I'm using a Bastion Host on a public subnet to communicate with an RDS instance on a private subnet, so I reach the database (on the private subnet) externally via an ssh tunnelling on the Bastion Host.我正在使用公共子网上的堡垒主机与私有子网上的 RDS 实例进行通信,因此我通过堡垒主机上的 ssh 隧道从外部访问数据库(在私有子网上)。

I've created the BastionHost in this way:我以这种方式创建了 BastionHost:

BastionHostLinux
            .Builder
            .create(scope, bastionId)
            .vpc(vpc)
            .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.SMALL))
            .subnetSelection(subnetSelection)
            .instanceName(bastionName)
            .build();

I don't find any method to create or associate ssh key pair to the instance, so when I try to connect, aws tell me that I don't have any ssh key pair associated with the ec2 instance.我没有找到任何方法来创建 ssh 密钥对或将 ssh 密钥对关联到实例,所以当我尝试连接时,aws 告诉我我没有任何与 ec2 实例关联的 ssh 密钥对。

My question is: How can I associate an already existent keypair with an ec2 instance using the CDK?我的问题是:如何使用 CDK 将已存在的密钥对与 ec2 实例相关联? Or, (it would be better) how can I create a fresh key pair using the CDK?或者,(最好)如何使用 CDK 创建新的密钥对?

You can use addPropertyOverride to set an existing key for the bastion host.您可以使用addPropertyOverride为堡垒主机设置现有密钥。

    const bastionSecurityGroup = new ec2.SecurityGroup(this, 'BastionSecurityGroup', {
      vpc,
    });
    const bastion = new ec2.BastionHostLinux(this, 'Bastion', {
      vpc,
      subnetSelection: { subnetType: ec2.SubnetType.PUBLIC },
      instanceName: `my-bastion`,
    });
    bastion.instance.instance.addPropertyOverride('KeyName', `my-bastion-key`);

How can I associate an already existent keypair with an ec2 instance using the CDK?如何使用 CDK 将已存在的密钥对与 ec2 实例相关联?

There is no ssh key on bastion instance, if you want to ssh to it you should use aws ec2-instance-connect , look at example from aws CDK documentation.堡垒实例上没有 ssh 密钥,如果您想通过 ssh 连接到它,您应该使用aws ec2-instance-connect ,查看 aws CDK 文档中的示例 And here is a blog post which explains in more details instance-connect .这是一篇博客文章,其中详细解释了instance-connect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM