kk.*_*kk. 16 if-statement amazon-web-services aws-cloudformation
我想根据输入参数填充 cloudformation 中的值。我想根据环境名称是否为Name或test-svc.abc.com不进行分配。如果环境名称为 ,则该值应为,否则应始终为。svc.abc.comprodprodsvc.abc.com{env-name}-svc.abc.com
我有以下表达:
Name: !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]
Run Code Online (Sandbox Code Playgroud)
在上面的表达式中,HostedZoneNamewill 被传递为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
Run Code Online (Sandbox Code Playgroud)
它基本上是三元运算符。
Name = EnvironmentName.equals("prod") ? HostedZoneName : EnvironmentName + "-" + HostedZoneName
Run Code Online (Sandbox Code Playgroud)
与 CloudFormation 中的 if else 条件作斗争。
kk.*_*kk. 10
根据 @rdas 发布的答案,我以 YAML 格式实现了以下表达式:
...
Conditions:
IsProductionEnvironment: !Equals [ !Ref EnvironmentName, prod ]
...
...
Name: !If [IsProductionEnvironment, !Ref 'HostedZoneName', !Join [ '-', [ !Ref EnvironmentName, !Ref 'HostedZoneName' ] ]]
...
Run Code Online (Sandbox Code Playgroud)
查看Cloudformation Conditions。您可以使用它们来定义 if 语句Fn::If
然后,您可以在资源部分中使用此条件来定义如何构建您的HostedZoneName.
这是一个例子。你可能需要做这样的事情:
...
"Conditions" : {
"CreateProdResources" : {"Fn::Equals" : [{"Ref" : "EnvType"}, "prod"]}
},
...
"Properties" : {
"HostedZoneName" : {
"Fn::If" : [
"CreateProdResources",
"svn.abc.com",
{"Fn::Sub": "${Environment}-svc.abc.com"}
]}
},
Run Code Online (Sandbox Code Playgroud)
您可以通过在 !if 中使用 !sub 来实现此目的。下面是我在非产品环境中查找域前缀(dev、qa、stage)的示例。
您的非产品存储桶名称将是
dev.mydomain.xyz.com
qa.mydomain.xyz.com
stage.mydomain.xyz.com
Run Code Online (Sandbox Code Playgroud)
产品存储桶名称将是
mydomain.xyz.com
Run Code Online (Sandbox Code Playgroud)
云化 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
Run Code Online (Sandbox Code Playgroud)