简体   繁体   English

如何在 Cloudformation 中为属性使用条件

[英]How to use conditions for properties in Cloudformation

I am trying to create a lambda function, version and alias using CloudFormation template and it is working as expected.我正在尝试使用 CloudFormation 模板创建一个 lambda 函数、版本和别名,它按预期工作。 But In my case I want to configure the RoutingConfig based on some input parameters.但就我而言,我想根据一些输入参数配置RoutingConfig

Example : If endures provided the TrafficShitVersion as a inputparam, then only I want to add RoutingConfig to the alias.示例:如果忍者提供了 TrafficShitVersion 作为输入参数,那么我只想将RoutingConfig添加到别名中。

Can any one help me how to achieve this use case谁能帮我实现这个用例

--- 
Description: "Lambda Example"
Parameters:
 TrafficShitVersion :
    Default: 0
    Type: String
    Description: TrafficShitVersion 
    
Conditions:
  CreateRouting: !Not 
    - !Equals 
      - !Ref TrafficShitVersion 
      - 0
Resources: 
  MyLambdaFunction: 
    Properties: 
      Code: 
        ZipFile: |
            exports.handler = function(event){
                console.log(JSON.stringify(event, null, 4))
                const response = {
                    statusCode: 200,
                    body: JSON.stringify('Hello from LambdaV5!')
                }
                return response
            };
      FunctionName: bhanuFunction
      Handler: index.handler
      Role: "RoleARN"
      Runtime: nodejs12.x
      Tags: 
        - 
          Key: "lambda:createdBy"
          Value: SAM
    Type: "AWS::Lambda::Function"
  myfunctionVersion3: 
    DeletionPolicy: Retain
    Properties: 
      FunctionName: 
        Ref: MyLambdaFunction
    Type: "AWS::Lambda::Version"
  myfunctionVersionAlias: 
    Properties: 
      FunctionName: 
        Ref: MyLambdaFunction
      FunctionVersion: 
       Fn::GetAtt : 
          - myfunctionVersion3
          - Version
      Name: MyTestAliash
      //Need to add the condition only if TrafficShitVersion is provided then only add ***RoutingConfig***
      RoutingConfig:
        AdditionalVersionWeights:
          - FunctionVersion: !Ref TrafficShitVersion 
            FunctionWeight: 0.5
    Type: "AWS::Lambda::Alias"

As per AWS docs, we can use Fn::If and AWS::NoValue to set properties accordingly.根据 AWS 文档,我们可以使用Fn::IfAWS::NoValue来相应地设置属性。

The template will look like:该模板将如下所示:

MyLambdaFunctionAlias: 

Properties: 
  FunctionName: 
    Ref: MyLambdaFunction
  FunctionVersion: 
   Fn::GetAtt : 
      - MyFunctionVersion3
      - Version
  Name: MyTestAlias
  RoutingConfig:
   !If
   - "CreateRouting"
   -
     AdditionalVersionWeights:
       - FunctionVersion: !Ref TrafficShitVersion 
         FunctionWeight: 0
   - !Ref "AWS::NoValue"
Type: "AWS::Lambda::Alias"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM