Reputation: 4727
I try to create an EC2 instance with the template below:
Parameters:
KeyName:
Default: TestKeyPair
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: AWS::EC2::KeyPair::KeyName
Resources:
Dev:
Properties:
ImageId: ami-4e79ed36
InstanceType: t2.micro
KeyName: !Ref 'KeyName'
SecurityGroups:
- !Ref 'SSH'
Type: AWS::EC2::Instance
but I get:
An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: Unresolved resource dependencies [SSH] in the Resources block of the template
I can't understand what's wrong in the template since the security group named "SSH" is already present:
$ aws ec2 describe-security-groups --group-names SSH
....
"IpPermissions": [
{
"ToPort": 22,
"IpRanges": [
{
"CidrIp": "0.0.0.0/0"
}
],
"FromPort": 22,
"IpProtocol": "tcp",
"UserIdGroupPairs": [],
"PrefixListIds": [],
"Ipv6Ranges": []
}
],
"GroupName": "SSH",
"GroupId": "sg-3b8bc345",
"Description": "Enable SSH access via port 22",
"OwnerId": "150811659115",
"VpcId": "vpc-a84688cf"
....
Upvotes: 19
Views: 69595
Reputation: 6329
!Ref
only works for Logical ID that exists within the template. That doesn't mean that you can't reference an existing security group, that just mean that you'll have to reference it in some other way. For your particular use case I suggest you pass the security group as a stack parameter like so:
Parameters:
KeyName:
Default: TestKeyPair
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: AWS::EC2::KeyPair::KeyName
SSHSecurityGroup:
Description: SecurityGroup that allows access to the instance via SSH
Type: AWS::EC2::SecurityGroup::Id
Resources:
Dev:
Properties:
ImageId: ami-4e79ed36
InstanceType: t2.micro
KeyName: !Ref 'KeyName'
SecurityGroups:
- !Ref SSHSecurityGroup
Type: AWS::EC2::Instance
On the stack creation you just have to pass the SSH Security Group in the appropriated field.
That being said, you won't have a much dynamic setup if you do it this way. You should either define the security group within this template and reference it directly (using !Ref
), or you could create a template that manages all security groups and use the Export/Import feature of CloudFormation to reference the security groups between stacks.
Upvotes: 25