如果其他条件形成云

时间:2019-05-16 14:16:39

标签: amazon-web-services if-statement amazon-cloudformation

我想根据输入参数在cloudformation中填充一个值。我想根据环境名称是否为Nametest-svc.abc.com分配为svc.abc.comprod。如果环境名称为prod,则该值应为svc.abc.com,否则应始终为{env-name}-svc.abc.com

我有以下表达式:

Name: !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]

在上面的表达式中,HostedZoneName将作为svc.abc.com传递,并且EnvironmentName的值可以是test, release or prod。因此条件应评估为:

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> test
Output: test-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> release
Output: release-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> 1234567
Output: 1234567-svc.abc.com

Inputs: HostedZoneName -> svc.abc.com, EnvironmentName -> prod
Output: svc.abc.com

基本上是三元运算符。

Name = EnvironmentName.equals("prod") ? HostedZoneName : EnvironmentName + "-" + HostedZoneName

在CloudFormation的if else条件中苦苦挣扎。

3 个答案:

答案 0 :(得分:2)

看看Cloudformation Conditions。您可以使用它们来使用Fn::If

定义if语句

然后,您可以在“资源”部分中使用此条件来定义如何构建HostedZoneName

这是一个例子。您可能需要执行以下操作:

...
 "Conditions" : {
    "CreateProdResources" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]}
  },

...

"Properties" : {
    "HostedZoneName" : {
      "Fn::If" : [
        "CreateProdResources",
        "svn.abc.com",
        {"Fn::Sub": "${Environment}-svc.abc.com"}
      ]}
  },

答案 1 :(得分:1)

您可以通过在 !if 中使用 !sub 来实现这一点。下面是我为非生产环境寻找域前缀 (dev,qa,stage) 的示例。

您的非生产存储桶名称将是

dev.mydomain.xyz.com
qa.mydomain.xyz.com
stage.mydomain.xyz.com

和 prod 存储桶名称将是

mydomain.xyz.com

cloformation Yaml exm

AWSTemplateFormatVersion: 2010-09-09
Description: 'AWS cloudformation template for admin panel s3 bucket. '
Parameters:
  WebBucketName:
    Description: Enter the name of the application
    Type: String
    Default: mydomain.xyz.com
  Environment:
    Description: Enter the environmet name from allowed values
    Type: String
    AllowedValues:
      - qa
      - dev
      - prod
      - stage
Conditions:
  CreateProdResources: !Equals [!Ref Environment, prod]
  CreatedevResources: !Equals [!Ref Environment, dev]
  CreateqaResources: !Equals [!Ref Environment, qa]
  CreatestageResources: !Equals [!Ref Environment, stage]
  MultiCondition: !Or
    - !Condition CreatedevResources
    - !Condition CreateqaResources
    - !Condition CreatestageResources

Resources:
  WebS3AdminPanel:
    Type: AWS::S3::Bucket
    Properties:
      BucketName:
        !If [MultiCondition, !Sub "${Environment}.${WebBucketName}", !Sub "${WebBucketName}" ]
      Tags:
        - Key: Name
          Value: test
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
      AccessControl: PublicRead

答案 2 :(得分:0)

基于@rdas发布的答案,我已将以下表达式实现为YAML格式:

...
Conditions: 
  IsProductionEnvironment: !Equals [ !Ref EnvironmentName, prod ]
...

...
Name: !If [IsProductionEnvironment, !Ref 'HostedZoneName', !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]]
...