3

I am launching p2.xlarge instance via cloudformation but sometimes it fails with error "The security group does not exist in default VPC" (not always). I think it could be a race condition.

Here is my cloudformation template:

"Resources":{
"MyInstance":{
    "Type":"AWS::EC2::Instance",
    "Properties":{
        "ImageId":"ami-xxxxxxxx",
        "InstanceType":{
            "Ref":"InstanceType"
        },
        "SecurityGroups":[
            {
                "Ref":"MySecurityGroup"
            }
        ],
        "KeyName":{
            "Ref":"KeyName"
        },
        "UserData":{
            "Fn::Base64":{
                "Fn::Join":[
                    "",
                    [
                        "#!/bin/bash -x\n"
                    ]
                ]
            }
        }
    }
},
"MySecurityGroup":{
    "Type":"AWS::EC2::SecurityGroup",
    "Properties":{
        "GroupDescription":"Enable ports",
        "SecurityGroupIngress":[
            {
                "IpProtocol":"tcp",
                "FromPort":22,
                "ToPort":22,
                "CidrIp":"0.0.0.0/0"
            },
            {
                "IpProtocol":"tcp",
                "FromPort":80,
                "ToPort":80,
                "CidrIp":"0.0.0.0/0"
            },
            {
                "IpProtocol":"tcp",
                "FromPort":443,
                "ToPort":443,
                "CidrIp":"0.0.0.0/0"
            }
        ]
    }
}
Atish Kumbhar
  • 579
  • 1
  • 8
  • 21

1 Answers1

0

You can try adding a DependsOn:

"MyInstance":{
    "Type":"AWS::EC2::Instance",
    "DependsOn": "MySecurityGroup"
    "Properties":{
...

I have found this helps for most resource creation. https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html

In other cases, you might need a wait condition or creation policy. https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-waitcondition.html

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html

EDIT: I realize this is an old question but for those with this problem I hope this helps!

meh93
  • 311
  • 4
  • 13