首页 > 解决方案 > 模板格式错误:未解决的资源依赖关系

问题描述

我尝试使用以下模板创建 EC2 实例:

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

但我得到:

An error occurred (ValidationError) when calling the CreateChangeSet operation: Template format error: Unresolved resource dependencies [SSH] in the Resources block of the template

我无法理解模板中有什么问题,因为名为“SSH”的安全组已经存在:

$ 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"
....

标签: amazon-web-servicesamazon-cloudformation

解决方案


!Ref 仅适用于模板中存在的逻辑 ID。这并不意味着您不能引用现有的安全组,这只是意味着您必须以其他方式引用它。对于您的特定用例,我建议您将安全组作为堆栈参数传递,如下所示:

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

在创建堆栈时,您只需在适当的字段中传递 SSH 安全组。


话虽如此,如果您这样做,您将不会有太多动态设置。您应该在此模板中定义安全组并直接引用它(使用!Ref),或者您可以创建一个管理所有安全组的模板并使用 CloudFormation 的导出/导入功能来引用堆栈之间的安全组。


推荐阅读