Overflow 404
Overflow 404

Reputation: 492

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?

Upvotes: 9

Views: 12338

Answers (3)

zhong chen
zhong chen

Reputation: 1

const ec2Instance = new ec2.Instance(this, 'ec2-instance', {
  vpc,
  vpcSubnets: {
    subnetType: ec2.SubnetType.PUBLIC,
  },
  role: role,
  securityGroup: securityGroup,
  instanceType: ec2.InstanceType.of(
    ec2.InstanceClass.BURSTABLE2,
    ec2.InstanceSize.MICRO,
  ),
  machineImage: new ec2.AmazonLinuxImage({
    generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
  }),
  keyPair,
});

Upvotes: 0

Asimov4
Asimov4

Reputation: 2854

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`);

Upvotes: 15

IgorMadjeric
IgorMadjeric

Reputation: 399

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.

Upvotes: 8

Related Questions