AWS Cloudformation - 从字符串到数字的参数转换以在我的 CIDRBlock 上使用

问题描述 投票:0回答:1

我的代码遇到这个问题,其中我的参数设置为

Type: String
在第 1 个和第 2 个八位字节上执行了 !Split,以便在我的 pub 和 priv 子网上的 CIDRBlock 中使用它。我可以将其上传到我的堆栈中,但是在创建时出现此错误:

“资源处理程序返回消息:“参数 cidrBlock 的值 (CFN-FirstOctet-hrIoiM1a5WIJ.CFN-SecondOctet-yA4ydUpmLomI.x.x/x) 无效。这不是有效的 CIDR 块。”

 Parameter:
 VPCCidr:
    Type: String
    Description: 'IP address or range that is allowed'
    Default: x.x.x.x/x
    AllowedValues:
      - x.x.x.x/x
      - x.x.x.x/x
      - x.x.x.x/x
 FirstOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !Select [ 0, !Split [ ".", !Ref VPCCidr ]]

  SecondOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !Select [ 1, !Split [ ".", !Ref VPCCidr ]]
PublicSubnet:
    Type: 'AWS::EC2::Subnet'
    Properties:
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: !Sub '${FirstOctet}.${SecondOctet}.x.x/x'
      MapPublicIpOnLaunch: true
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: publicsubnet 
        - Key: Reach
          Value: public

尝试设置

Type: Number
但是我收到此错误:

“资源 SecondOctet 的属性验证失败,并显示消息:[#/Type: Number 不是有效的枚举值]”

FirstOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: Number
      Value: !Select [ 0, !Split [ ".", !Ref VPCCidr ]]

  SecondOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: Number
      Value: !Select [ 1, !Split [ ".", !Ref VPCCidr ]]

我也已经这样做了,但出现解析器错误。

FirstOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: Number
      Value:!Ref !Select [ 0, !Split [ ".", !Ref VPCCidr ]]

  SecondOctet:
    Type: AWS::SSM::Parameter
    Properties:
      Type: Number
      Value:!Ref !Select [ 1, !Split [ ".", !Ref VPCCidr ]]
amazon-web-services aws-cloudformation
1个回答
0
投票

阅读完您遇到的错误后,我的建议是您通过避免使用

AWS::SSM::Parameter
来分割 CIDR 块八位位组来简化您的方法。您看到的错误似乎是由于您尝试使用
AWS::SSM::Parameter
来表示动态值而引起的,这不是 CloudFormation 中该资源类型的正确用例。

您无需为

FirstOctet
SecondOctet
创建单独的参数,而是可以在
VPCCidr
资源内动态拆分和选择
PublicSubnet
的八位字节,而无需中间参数。

类似这样的:

Parameters:
  VPCCidr:
    Type: String
    Description: 'IP address or range that is allowed'
    Default: x.x.x.x/x
    AllowedValues:
      - x.x.x.x/x
      - x.x.x.x/x
      - x.x.x.x/x

Resources:
  PublicSubnet:
    Type: 'AWS::EC2::Subnet'
    Properties:
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: !Sub "${!Select [0, !Split [ '.', !Ref VPCCidr ]]}.${!Select [1, !Split [ '.', !Ref VPCCidr ]]}.x.x/x"
      MapPublicIpOnLaunch: true
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: publicsubnet
        - Key: Reach
          Value: public

这种方法消除了将

FirstOctet
SecondOctet
定义为参数的需要,我认为这会导致解析器错误。

请告诉我这是否有助于解决您的问题!

如果没有,我们可以探索其他可能的选择。

© www.soinside.com 2019 - 2024. All rights reserved.