0
votes

I have created below four resources successfully using the Cloud Formation Template (CFT):

  1. VPC
  2. Subnet
  3. InternetGateway
  4. AttachGateway

Now, I am trying to create a security group with EC2 instance, here is the code.

  Type: AWS::EC2::SecurityGroup
  Properties:
      GroupDescription: Allow http and ssh to client host
      VpcId:
         Ref: InsuranceVPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: 80
        ToPort: 80
        CidrIp: 0.0.0.0/0
      - IpProtocol: tcp
        FromPort: 22
        ToPort: 22
        CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
      - IpProtocol: tcp
        FromPort: 80
        ToPort: 80
        CidrIp: 0.0.0.0/0

Ec2Instance: 
  Type: AWS::EC2::Instance
  Properties: 
    ImageId: "ami-08706cb5f68222d09"
    KeyName: 
      Ref: "DevOpsAutomation"
    NetworkInterfaces: 
      - AssociatePublicIpAddress: "true"
        DeviceIndex: "0"
        GroupSet: 
          - Ref: "InsuranceSecurityGroup"
        SubnetId: 
          Ref: "InsuranceSubnet"

But, when I use the Key parameter in (CFT, as shown above, code) which is my key present in the same region of the resources, my CFT stack fails with below error:

Template format error: Unresolved resource dependencies [DevOpsAutomation] in the Resources block of the template note: DevOpsAutomation is my keyname

Steps I validated:

  1. CFT template resources and the key is in the same region
  2. deleted and freshly created key pair
  3. tried to use different key pair
  4. I couldn't see an option anywhere to import the key along with the CFT stack so that my EC2 instance can use it.
  5. Even while creating the stack the key DOESN'T appear (which is visible in keypair section) in the parameter section of the stack.

My query is, how should I create EC2 instance (as a part of CFT) using the key pair which is present in my AWS account?

2

2 Answers

4
votes

Remove the Ref in front of the key name. Ref is used to reference other resources that have been defined as part of the CloudFormation template. If the key pair already exists, you can simply use the key name.

KeyName: "DevOpsAutomation"
2
votes

I have copied here an example

AWSTemplateFormatVersion: '2010-09-09'
Description: >
  AWS CloudFormation template to create Jenkins server
Parameters:
    KeyName:
        Type: AWS::EC2::KeyPair::KeyName
        Default: ritefit-keypair
Resources:
    JenkinsEC2Instance:
        Type: AWS::EC2::Instance
        Properties:
        KeyName: !Ref KeyName

Show us more what have defined KeyName so we can help you what the issue is