How can I use the condition within cloud formation for creating resources?

46    Asked by DorineHankey in AWS , Asked on Mar 22, 2024

I am currently designing a cloud formation template to deploy infrastructure resources on AWS. Explain to me how can I use the condition within Cloudformation for creating the resources conditionally based on the criteria. 

Answered by Csaba Toth

In the context of AWS, here is the step given of how you can implement conditions within the cloud formation template:-

Define condition in cloud formation

You can define the condition in the cloud formation template by using the “condition” section within the template. It would evaluate whether resources or a set of resources be created based on certain criteria.

Example scenario

Let us assume an example where you want to create an S3 bucket only if a specific environment variable is set to ‘production’.

Here is an example given of a cloud formation template snippet which would demonstrate how you can implement the condition for the above example:-

AWSTemplateFormatVersion: ‘2010-09-09’
Description: Example CloudFormation Template with Conditions
Parameters:
  EnvironmentType:
    Type: String
    Default: ‘development’
    AllowedValues: [‘development’, ‘production’]
    Description: Select the environment type
Conditions:
  CreateBucketCondition:
    !Equals [ !Ref EnvironmentType, ‘production’ ]
Resources:
  MyS3Bucket:
    Condition: CreateBucketCondition
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !If [ CreateBucketCondition, ‘my-production-bucket’, ‘my-development-bucket’ ]

Your Answer

Interviews

Parent Categories