javaamazon-web-servicesaws-cdk

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.

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.

I've created the BastionHost in this way:

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.

My question is: How can I associate an already existent keypair with an ec2 instance using the CDK? Or, (it would be better) how can I create a fresh key pair using the CDK?


Solution

  • How can I associate an already existent keypair with an ec2 instance using the CDK?

    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. And here is a blog post which explains in more details instance-connect.