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?

Overflow 404
  • 482
  • 5
  • 20

2 Answers2

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`);
Asimov4
  • 2,776
  • 3
  • 23
  • 38
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.

IgorMadjeric
  • 389
  • 2
  • 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) – Overflow 404 Feb 03 '20 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`. – IgorMadjeric Feb 03 '20 at 21:39
  • Yes I agree, I think the Instance is the best approach. – Overflow 404 Feb 04 '20 at 07:57