Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
Overflow 404 Avatar asked Feb 03 '20 14:02

Overflow 404


People also ask

How do I add a Keypair to my EC2 instance?

To add or replace a key pairCreate a new key pair using the Amazon EC2 console or a third-party tool. Retrieve the public key from your new key pair. For more information, see Retrieve the public key material. Connect to your instance using your existing private key.

How do I create a Keypair on AWS?

To create a key pairOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, under Network & Security, choose Key Pairs. On the Key Pairs page, choose Create Key Pair. For Key pair name, type a name that is easy for you to remember, and then choose Create.


1 Answers

You can use addPropertyOverride to set an existing key for the bastion host.

    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`);
like image 118
Asimov4 Avatar answered Sep 22 '22 01:09

Asimov4