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?
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.
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.
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`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With