How do I associate an ssh key pair with the instance created by a stack in Amazon CloudFormation?

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!


AWS CloudFormation parameters can also give you a list of all key's that are available in your account & region. Just change the "Type" of the parameter to the desired AWS type. That will be "AWS::EC2::KeyPair::KeyName" in this case.

With "CloudFormation Parameter Types", the above example will be:

"Parameters" : {
  "KeyName" : {
    "Description" : "EC2 KeyPair to enable SSH access to the instance",
    "Type" : "AWS::EC2::KeyPair::KeyName"
  },
},
[...]

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

I hope this helps.

See also: https://blogs.aws.amazon.com/application-management/post/Tx3DV2UYG9SC38G/Using-the-New-CloudFormation-Parameter-Types