Ssh – How to associate an ssh key pair with the instance created by a stack in Amazon CloudFormation

amazon ec2amazon-cloudformationssh

Previously I have created an EC2 instance based on an image. During the creation process the Amazon wizard created a key pair and then provided it to me so I could connect.

Now I am trying to use CloudFormation instead, so that my new server has some basic software installed (LAMP stack). But the EC2 instance I end up with has no ssh key pair that I can find.

Is there a way to associate a key pair while creating a stack on CloudFormation?

I've read that there are ways to add the key to the instance's volume by stopping the instance, creating a clone, plus some other steps. But my admin skills in this area are not that strong so I am hoping for something that is (for me) more straightforward.

Hope this makes sense – any help much appreciated!

Best Answer

Is there a way to associate a key pair while creating a stack on CloudFormation?

Sure, it indeed works by associating an existing key pair of yours during the process; the AWS CloudFormation Sample Templates feature respective fragments, e.g. the Simple EC2 instance example contains the fragment you are looking for:

  "Parameters" : {
    "KeyName" : {
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance",
      "Type" : "String"
    }
  },

  [...]

  "Resources" : {
    "Ec2Instance" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "KeyName" : { "Ref" : "KeyName" },
        "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]},
        "UserData" : { "Fn::Base64" : "80" }
      }
    }
  },

This fragment enables passing the desired key pair name as a parameter, alternatively you could embed the name directly or simply provide a default one.

Good luck!