AWS CloudFormation - Using Parameters

Parameter Type in CloudFormation template allows user to provide input values to the template. This allows us to reuse the template for different set of values.

In the example below, the template allows to create a Security Group based on the inputs provided by user. The values for Ingress FromPort, ToPort, Protocol, security group name & description are all parameterized. The value is referenced in the Resource Type creation using the !Ref function.

AWSTemplateFormatVersion: 2010-09-09
Description: Template to create Security Group


Parameters:
  SgPort:
    Description: "Sg Ingress Port Number to Open"
    Type: Number
  SgDescription:
    Description: "Sg Description"
    Type: String
  SgProtocol:
    Description: "Sg Protocol"
    Type: String
  SgGroupName:
    Description: "Sg Group Name"
    Type: String

Resources:
  secGroupName:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Ref SgGroupName
      GroupDescription: !Ref SgDescription
      SecurityGroupIngress:
        - IpProtocol: !Ref SgProtocol
          FromPort: !Ref SgPort
          ToPort: !Ref SgPort
          CidrIp: "0.0.0.0/0"
      Tags:
        - Key: "Project"
          Value: "CF Demo"
        - Key: "Name"
          Value: !Ref SgGroupName

To execute,

aws cloudformation create-stack --stack-name SgStack --template-body file:///home/ec2-user/CF_Learnings/003_Parameter/createSG.yaml --parameters ParameterKey=SgPort,ParameterValue=443 ParameterKey=SgDescription,ParameterValue="SSL PortOpen" ParameterKey=SgGroupName,ParameterValue="SSL port SG" ParameterKey=SgProtocol,ParameterValue="tcp"

2022-06-04 19_12_55-54.66.203.169 (ec2-user).png

To describe the stack resources:

2022-06-04 19_12_18-54.66.203.169 (ec2-user).png

Thus by changing the input parameter, we could reuse this template again to create a different Security Group.