9

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?

2 Answers 2

14

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`);
1
  • Thanks, this answer saved me hours of extra work. You are a legend. Cheers.
    – Raghu
    Apr 3, 2021 at 6:09
7

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.

3
  • Yes, I have already read this. The problem is: to install ec2 instance connect on the bastion I have to connect via SSH to the bastion (as mentioned in the blog post that you linked, dot one), but how can I ssh connect to the bastion if I haven't the ssh keys? (In an automatic way, via the CDK) Feb 3, 2020 at 16:53
  • If you do not have a specific reason for using BastionHostLinux you could create an instance using Instance class and just give name of your existing key pair using InstanceProperties. Feb 3, 2020 at 21:39
  • Yes I agree, I think the Instance is the best approach. Feb 4, 2020 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.