Working with Conditions
This tutorial references the code in the aws-connectedcar-dotnet-serverless repository. If you're new to this course, see the introduction for information about setting up your workstation and getting the sample code.
Conditions are a very useful feature of the CloudFormation template language. Using conditions, you can automatically apply different property values to resources, selectively create resources, or even selectively create entire stacks when working with nested templates. This makes it possible, using the same set of templates, to tailor your stacks to suit the needs of different environments.
Setting Resource Properties Conditionally
To see how to conditionally set resource properties, let’s start with the example shown below from the admin.yaml template. In this case we’re assuming that we have mock data to work with during development, and as a result we can safely turn on full API Gateway request and response logging in that environment. But in other environments, we’re working with real production data or non-obfuscated copies of this data, and so we don't want to log what might be sensitive information.
To make this possible we’re first declaring the IsDevelopment variable, based on the value of the EnvironmentName input parameter in the Conditions section of the template on line 56. Then, for the AdminAPI resource, on line 71, we’re using this variable to conditionally enable the API DataTraceEnabled property, which controls the request and response logging:
For information about condition functions such as !If, !Equals, !And, see the AWS documentation here: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html
Creating Resources Conditionally
The sample code doesn’t actually make use of this technique, but we can outline it here. If you have a resource that only needs to be created under specific conditions, you can first define a boolean variable, as we saw above. Then you can add a Condition property to the resource and assign its value to the condition variable.
As an example, let’s say you want to conditionally create an S3 bucket only for development environments. Here’s a basic resource declaration, borrowed from the AWS documentation, that is creates an S3 bucket without any conditions:
Resources:
S3Bucket:
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
Properties:
BucketName: DOC-EXAMPLE-BUCKET
To then conditionally create this resource only for development environments, you just need to add the Condition property, as shown below on the third line, before the type declaration:
Resources:
S3Bucket:
Condition: !If [ isDevelopment, true, false ]
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
Properties:
BucketName: DOC-EXAMPLE-BUCKET