将 VPC 创建设置为可选



我正在尝试在我的云形成脚本中使VPC创建有条件。例如,如果参数中提供了 VPC ID,则我想在此 VPC 中创建所有资源,否则创建一个新资源。

当我想重用现有 VPC 时,问题就开始了,但我无法推断子网,而我的一个资源需要子网。所以我想,我必须将它们作为参数提供。但是,如果我将它们作为参数提供,在我想创建新的 VPC 的情况下,它会抱怨,因为子网 ID 列表为空,并且必须是有效的。

错误是Parameter validation failed: parameter value for parameter name VpcPrivateSubnetIds does not exist. Rollback requested by user.不可能给出任何虚拟值。任何想法如何实现这一目标?

这是我的 CF 脚本:

VpcId:
  Type: String
  Description: Give the VPC id if you want to use an existing one. Leave empty for creating a new one.
VpcPublicSubnetIds:
  Type: List<AWS::EC2::Subnet::Id>
  Description: List of 3 public SubnetIds for the given VPC. 
VpcPrivateSubnetIds:
  Type: List<AWS::EC2::Subnet::Id>
  Description: List of 3 private SubnetIds for the given VPC. 

Conditions:
  CreateVPC: !Equals [ !Ref VpcId, ""]

Resources: 
  (...)
    Properties:
      PrivateSubnetIds: !If
        - CreateVPC
        - !GetAtt VPCStack.Outputs.PrivateSubnets
        - !Join [',', [!Select [0, !Ref VpcPrivateSubnetIds], !Select [1, !Ref VpcPrivateSubnetIds], !Select [2, !Ref VpcPrivateSubnetIds]]]
      PublicSubnetIds: !If
        - CreateVPC
        - !GetAtt VPCStack.Outputs.PublicSubnets
        - !Join [',', [!Select [0, !Ref VpcPublicSubnetIds], !Select [1, !Ref VpcPublicSubnetIds], !Select [2, !Ref VpcPublicSubnetIds]]]

一种解决方案是将subnetId参数视为字符串,然后可以将其保留为空。(但当存在 VPC 时,用户必须手动键入子网 ID 列表(。

如果列表不为空(将使用现有 VPC(,请使用 Cloudformation 自定义资源 lambda 将字符串(逗号分隔(转换为列表并返回到 cloudformation 以用于资源创建。所以你的堆栈看起来像

Parameters:
  VpcId:
    Type: String
    Description: Give the VPC id if you want to use an existing one. Leave empty for creating a new one.
  VpcPublicSubnetIds:
    Type: String
    Description: List of 3 public SubnetIds for the given VPC.
    Default: ''
  VpcPrivateSubnetIds:
    Type: String
    Description: List of 3 private SubnetIds for the given VPC.
    Default: ''
Conditions:
  CreateVPC: !Equals [ !Ref VpcId, ""]
  CreateList: !Not [!Equals [ !Ref VpcId, ""]]
Resources:
  CreateList:
    Type: AWS::CloudFormation::CustomResource
    Condition: CreateList
    Properties:
      ServiceToken:<some token>
      Public: !Ref VpcPublicSubnetIds
      Private: !Ref VpcPrivateSubnetIds
  SomeResource:
    Properties:
      PrivateSubnetIds: !If
        - CreateVPC
        - !GetAtt VPCStack.Outputs.PrivateSubnets
        - !GetAtt CreateList.PrivateSubnetIds
      PublicSubnetIds: !If
        - CreateVPC
        - !GetAtt VPCStack.Outputs.PublicSubnets
        - !GetAtt CreateList.PublicSubnetIds

请注意,我已经注意到验证了此脚本,因此您可能需要进行一些更正。

相关内容

  • 没有找到相关文章

最新更新