Scilla
Scilla

Reputation: 385

Creating Ec2 SSH KEy with Cloud Formation in CI/CD

Consider this CI/CD scenario:

In dev stage I want to deploy my stack with an Ec2 Instance and EC2 key pair from a CF.

From the docs I understand the Cloud Formation Resource, can point to an existing Key that can be created from the AWS Management Console and no other way.

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-keypair.html

I want to create my Key with the stack, so that I can use it to ssh in the instance. I would provide the value to my SSH through an env var, therefore I would be the only one knowing the key value.

Is anyone aware of a solution for this scenario?

Upvotes: 1

Views: 2065

Answers (3)

Martin Hollingsworth
Martin Hollingsworth

Reputation: 7329

This capability has been added to Cloudformation now via the AWS::EC2::KeyPair resource - "To have Amazon EC2 create a new key pair, omit the PublicKeyMaterial property. When Amazon EC2 creates a new key pair, the private key is saved to an AWS Systems Manager Parameter Store"

Not sure when exactly this was added.

Upvotes: 2

Maurice
Maurice

Reputation: 13117

A console-only operation in AWS is usually not a thing. Practically all operations in the console use the underlying public APIs (some exceptions exist).

If you really want to create an EC2 Key Pair in CloudFormation, you can do it through a custom resource. This is essentially a Lambda Function that can do arbitrary things and may or may not return values.

Creating a KeyPair is done through the CreateKeyPair action in the EC2 API, which is documented here. You could use this API call in a Custom Resource to create a KeyPair, Save the Public Key somewhere safe (e.g. Secrets Manager) and return the name of the KeyPair as an attribute.

I would advise against this though. It's not trivial to ensure the Private Key is only accessible to you.

I recommend you configure your CloudFormation template in a way that the instance is able to use EC2 instance connect. This allows you to use the EC2 API to inject temporary SSH keys into the instance to establish a connection or even use the session manager from the browser. I'd prefer these options, because they use temporary credentials and/or are easier to audit.

References

Upvotes: 1

Marcin
Marcin

Reputation: 238189

Sadly, you can't create ssh key pair in plain CloudFormation (CFN). This is not supported. Instead, if you really want to manage key pair creation using CFN, you have to use custom resources.

The resource would be in the form of a lambda function which would use AWS SDK, e.g., create_key_pair and save the resulting private key, in SSM Parameter Store for example.

Any further application that requires the key generated would be able to retrieve if from the store.

Upvotes: 1

Related Questions