模板格式错误:未解决的资源依赖性

时间:2018-06-05 04:32:51

标签: amazon-web-services amazon-cloudformation

我尝试使用以下模板创建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"
....

2 个答案:

答案 0 :(得分:2)

!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的导出/导入功能引用堆栈之间的安全组

答案 1 :(得分:0)

如果您使用的是jinja,请确保已更新template.jinja