### Simple Apache Installation with cfn-init Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.md Installs and starts the Apache web server (httpd) on an EC2 instance using yum and systemd. This example also includes UserData to install cfn-bootstrap and execute cfn-init. ```yaml Resources: EC2Instance: Type: AWS::EC2::Instance Metadata: AWS::CloudFormation::Init: config: packages: yum: httpd: [] services: systemd: httpd: enabled: true ensureRunning: true Properties: ImageId: !Ref LatestAmiId InstanceType: !Ref InstanceType UserData: !Base64 Fn::Sub: | #!/bin/bash yum install -y aws-cfn-bootstrap /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2Instance --region ${AWS::Region} ``` -------------------------------- ### Systemd Unit File Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-init.md A systemd unit file example for the cfn-hup daemon, allowing it to be started and stopped by systemd. ```systemd [Unit] Description=cfn-hup daemon [Service] ExecStart=/usr/bin/cfn-hup -v PIDFile=/var/run/cfn-hup.pid [Install] WantedBy=multi-user.target ``` -------------------------------- ### Amazon Linux Example with cfn-init and cfn-signal Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-signal.md This example shows a common pattern where cfn-init is used to install an application, and cfn-signal is used to report the success or failure of that installation. The exit code of cfn-init determines the signal sent, enabling automatic stack rollback on failure. ```bash #!/bin/bash -xe /usr/bin/cfn-init -s --region us-east-1 --stack my-stack --resource my-instance --configsets default /opt/aws/bin/cfn-signal -e $? --stack my-stack --resource my-instance --region us-east-1 ``` -------------------------------- ### Initial Stack Configuration for Web Server Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/updating.stacks.walkthrough Defines the metadata for installing Apache and PHP, and configuring the httpd service to run. This is part of the initial stack setup. ```yaml WebServerInstance: Type: AWS::EC2::Instance Metadata: AWS::CloudFormation::Init: config: packages: yum: httpd: [] php: [] files: /var/www/html/index.php: content: | Hello World!'; ?> mode: '000644' owner: apache group: apache services: systemd: httpd: enabled: true ensureRunning: true ``` -------------------------------- ### Launch Configuration with cfn-init Metadata (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatepolicy.md Example of a Launch Configuration resource with AWS::CloudFormation::Init metadata. This is used for bootstrapping instances in an Auto Scaling group with software installations and commands. ```json "LaunchConfig": { "Type" : "AWS::AutoScaling::LaunchConfiguration", "Metadata" : { "Comment" : "Install a simple PHP application", "AWS::CloudFormation::Init" : { ... } } } ``` -------------------------------- ### Example Ubuntu/Debian Repository Configuration Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-ssm-patchbaseline-patchsource.md Provides an example of a configuration for Ubuntu Server and Debian Server repositories. Repo information must be specified in a single line. ```text deb http://security.ubuntu.com/ubuntu jammy main ``` ```text deb https://site.example.com/debian distribution component1 component2 component3 ``` -------------------------------- ### Create S3 Bucket with Defaults (YAML) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-s3.md This snippet creates an S3 bucket using default settings. It is a basic example for getting started. ```yaml 1. MyS3Bucket: 2. Type: AWS::S3::Bucket ``` -------------------------------- ### Install MSI Packages with cfn-init Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-init.md Install Windows MSI packages by providing the URL to the package file. ```json "msi" : { "awscli" : "https://s3.amazonaws.com/aws-cli/AWSCLI64.msi" } ``` ```yaml msi: awscli: "https://s3.amazonaws.com/aws-cli/AWSCLI64.msi" ``` -------------------------------- ### Create a container recipe with all parameters Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-imagebuilder-containerrecipe.md This example shows how to create a container recipe with all available parameters, including name, version, parent image, components, target repository, Dockerfile template, working directory, KMS key ID, and tags. ```json { "Resources": { "ContainerRecipeAllParameters": { "Type": "AWS::ImageBuilder::ContainerRecipe", "Properties": { "Name": "container-recipe-name", "Version": "1.0.0", "ParentImage": { "Ref": "ParentImage" }, "Description": "description", "ContainerType": "DOCKER", "Components": [ { "ComponentArn": { "Ref": "ComponentArn" } }, { "ComponentArn": { "Ref": "AnotherComponentArn" } } ], "TargetRepository": { "Service": "ECR", "RepositoryName": { "Ref": "RepositoryName" } }, "DockerfileTemplateData": "FROM {{{ imagebuilder:parentImage }}}\n{{{ imagebuilder:environments }}}\n{{{ imagebuilder:components }}}\n", "WorkingDirectory": "dummy-working-directory", "KmsKeyId": { "Ref": "KmsKeyId" }, "Tags": { "Usage": "Documentation" } } } }, "Outputs": { "OutputContainerRecipeArn": { "Value": { "Fn::GetAtt": [ "ContainerRecipeAllParameters", "Arn" ] } } } } ``` -------------------------------- ### Create S3 Bucket with Defaults (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-s3.md This snippet creates an S3 bucket using default settings. It is a basic example for getting started. ```json 1. "myS3Bucket" : { 2. "Type" : "AWS::S3::Bucket" 3. } ``` -------------------------------- ### Install Packages with cfn-init (RPM, yum, Rubygems, Zypper) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-init.md Specify packages for installation using various managers. You can provide specific versions, URLs, or request the latest available. ```json "rpm" : { "epel" : "http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm" }, "yum" : { "httpd" : [], "php" : [], "wordpress" : [] }, "rubygems" : { "chef" : [ "0.10.2" ] }, "zypper" : { "git" : [] } ``` ```yaml rpm: epel: "http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm" yum: httpd: [] php: [] wordpress: [] rubygems: chef: - "0.10.2" zypper: git: [] ``` -------------------------------- ### Specify CloudFormation Actions with Wildcards in IAM Policy Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/control-access-with-iam.md Use wildcards in the Action element of an IAM policy to specify multiple CloudFormation API actions that match a pattern. This example grants permissions for all actions starting with 'Get'. ```json "Action": "cloudformation:Get*" ``` -------------------------------- ### Example: Filter for Metric Namespaces Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-oam-link-linkfilter.md This example demonstrates filtering metric namespaces that do not start with 'AWS/'. ```text Namespace NOT LIKE 'AWS/%' ``` -------------------------------- ### Example CloudFormation Quick-Create Link (Formatted) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stacks-quick-create-links.md An example of a quick-create link with line breaks for readability, demonstrating the inclusion of template URL, stack name, and specific template parameters. ```url https://us-east-2.console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/create/review ?templateURL=https://s3.us-east-2.amazonaws.com/cloudformation-templates-us-east-2/WordPress_Single_Instance.template &stackName=MyWPBlog ¶m_DBName=mywpblog ¶m_InstanceType=t2.medium ``` -------------------------------- ### Example: Get specific metadata key Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-get-metadata.md Use the `-k` or `--key` option to retrieve a specific value from a key-value pair metadata block. This example shows how to get the value associated with 'Key2'. ```bash cfn-get-metadata -k Key2 ``` -------------------------------- ### CloudFormation Provisioned Product Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-servicecatalog-cloudformationprovisionedproduct.md This example demonstrates how to create a CloudFormationProvisionedProduct resource. It shows how to specify the product name, provisioning artifact name, and how to pass provisioning parameters, including referencing outputs from another CloudFormation resource using Fn::GetAtt. ```yaml AWSTemplateFormatVersion: '2010-09-09' Description: Serverless Stack Resources: SimpleLambda: Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct Properties: ProductName: Basic Lambda ProvisioningArtifactName: '1.0' SimpleApiGateway: Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct Properties: ProductName: API Gateway ProvisioningArtifactName: '1.0' ProvisioningParameters: - Key: LambdaArn Value: !GetAtt [SimpleLambda, Outputs.SCLambdaArn] ``` -------------------------------- ### AWS::SSM::Association Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html This resource creates a State Manager association for your managed instances. A State Manager association defines the state that you want to maintain on your instances. For example, an association can specify that anti-virus software must be installed and running on your instances, or that certain ports must be closed. For static targets, the association specifies a schedule for when the configuration is reapplied. For dynamic targets, such as an AWS Resource Groups or an AWS Auto Scaling Group, State Manager applies the configuration when new instances are added to the group. The association also specifies actions to take when applying the configuration. For example, an association for anti-virus software might run once a day. If the software is not installed, then State Manager installs it. If the software is installed, but the service is not running, then the association might instruct State Manager to start the service. ```APIDOC ## AWS::SSM::Association ### Description Creates a State Manager association for your managed instances. A State Manager association defines the state that you want to maintain on your instances. For example, an association can specify that anti-virus software must be installed and running on your instances, or that certain ports must be closed. For static targets, the association specifies a schedule for when the configuration is reapplied. For dynamic targets, such as an AWS Resource Groups or an AWS Auto Scaling Group, State Manager applies the configuration when new instances are added to the group. The association also specifies actions to take when applying the configuration. For example, an association for anti-virus software might run once a day. If the software is not installed, then State Manager installs it. If the software is installed, but the service is not running, then the association might instruct State Manager to start the service. ### Syntax #### JSON ```json { "Type" : "AWS::SSM::Association", "Properties" : { "ApplyOnlyAtCronInterval" : Boolean, "AssociationName" : String, "AutomationTargetParameterName" : String, "CalendarNames" : [ String, ... ], "ComplianceSeverity" : String, "DocumentVersion" : String, "InstanceId" : String, "MaxConcurrency" : String, "MaxErrors" : String, "Name" : String, "OutputLocation" : InstanceAssociationOutputLocation, "Parameters" : [ String, ... ], "ScheduleExpression" : String, "ScheduleOffset" : Integer, "SyncCompliance" : String, "Targets" : [ Target, ... ], "WaitForSuccessTimeoutSeconds" : Integer } } ``` ``` -------------------------------- ### Create MySQL Setup File (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-init.md Creates a MySQL setup file with database creation and user grant statements. Uses intrinsic functions to reference database and user credentials. ```json "files" : { "/tmp/setup.mysql" : { "content" : { "Fn::Join" : ["", [ "CREATE DATABASE ", { "Ref" : "DBName" }, ";\n", "CREATE USER '", { "Ref" : "DBUsername" }, "'@'localhost' IDENTIFIED BY '", { "Ref" : "DBPassword" }, "';\n", "GRANT ALL ON ", { "Ref" : "DBName" }, ".* TO '", { "Ref" : "DBUsername" }, "'@'localhost'";\n", "FLUSH PRIVILEGES;\n" ]]}, "mode" : "000644", "owner" : "root", "group" : "root" } } ``` -------------------------------- ### Example: Filter for Log Group Name Prefixes Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-oam-link-linkfilter.md This example includes log groups whose names start with 'aws/lambda/' or 'AWSLogs'. ```text LogGroupName LIKE 'aws/lambda/%' OR LogGroupName LIKE 'AWSLogs%' ``` -------------------------------- ### AWS::Panorama::ApplicationInstance Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-panorama-applicationinstance.md Creates an application instance and deploys it to a device. ```APIDOC ## AWS::Panorama::ApplicationInstance ### Description Creates an application instance and deploys it to a device. ### Properties #### JSON ```json { "Type" : "AWS::Panorama::ApplicationInstance", "Properties" : { "ApplicationInstanceIdToReplace" : {{String}}, "DefaultRuntimeContextDevice" : {{String}}, "Description" : {{String}}, "ManifestOverridesPayload" : {{ManifestOverridesPayload}}, "ManifestPayload" : {{ManifestPayload}}, "Name" : {{String}}, "RuntimeRoleArn" : {{String}}, "Tags" : {{[ Tag, ... ]}} } } ``` #### YAML ```yaml Type: AWS::Panorama::ApplicationInstance Properties: ApplicationInstanceIdToReplace: {{String}} DefaultRuntimeContextDevice: {{String}} Description: {{String}} ManifestOverridesPayload: {{ManifestOverridesPayload}} ManifestPayload: {{ManifestPayload}} Name: {{String}} RuntimeRoleArn: {{String}} Tags: - Tag ``` ``` -------------------------------- ### Stage Creation Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-apigatewayv2-stage.md This example demonstrates how to create a stage resource named MyStage, associating it with an existing deployment and API. It configures default route settings and access log settings. ```json { "MyStage": { "Type": "AWS::ApiGatewayV2::Stage", "Properties": { "StageName": "Prod", "Description": "Prod Stage", "DeploymentId": { "Ref": "MyDeployment" }, "ApiId": { "Ref": "CFNWebSocket" }, "DefaultRouteSettings": { "DetailedMetricsEnabled": true, "LoggingLevel": "INFO", "DataTraceEnabled": false, "ThrottlingBurstLimit": 10, "ThrottlingRateLimit": 10 }, "AccessLogSettings": { "DestinationArn": "arn:aws:logs:us-east-1:123456789:log-group:my-log-group", "Format": "{\"requestId\":\"$context.requestId\", \"ip\": \"$context.identity.sourceIp\", \"caller\":\"$context.identity.caller\", \"user\":\"$context.identity.user\",\"requestTime\":\"$context.requestTime\", \"eventType\":\"$context.eventType\",\"routeKey\":\"$context.routeKey\", \"status\":\"$context.status\",\"connectionId\":\"$context.connectionId\"}" } } } } ``` ```yaml MyStage: Type: 'AWS::ApiGatewayV2::Stage' Properties: StageName: Prod Description: Prod Stage DeploymentId: !Ref MyDeployment ApiId: !Ref CFNWebSocket DefaultRouteSettings: DetailedMetricsEnabled: true LoggingLevel: INFO DataTraceEnabled: false ThrottlingBurstLimit: 10 ThrottlingRateLimit: 10 AccessLogSettings: DestinationArn: 'arn:aws:logs:us-east-1:123456789:log-group:my-log-group' Format: >- {"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user","requestTime":"$context.requestTime", "eventType":"$context.eventType","routeKey":"$context.routeKey", "status":"$context.status","connectionId":"$context.connectionId"} ``` -------------------------------- ### Create an association that runs a bash script Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ssm-association.md This example creates an AWS::SSM::Association to run a bash script on EC2 instances tagged with 'nginx: yes'. It includes resources for an S3 bucket, an IAM role for SSM, an EC2 instance profile, and the EC2 instance itself. The association uses the AWS-RunShellScript document to install and start Nginx. ```yaml --- Description: "Deploy single Amazon Linux 2 EC2 instance and install Nginx by a State Manager association" Parameters: LatestAmiId: Type: 'AWS::SSM::Parameter::Value*' Default: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2" Resources: amzn-s3-demo-bucket: Type: AWS::S3::Bucket # Role that allows SSM Agent to communicate with SSM and allows use of all features of SSM SSMInstanceRole: Type : AWS::IAM::Role Properties: Policies: - PolicyDocument: Version: '2012-10-17 ' Statement: - Action: - s3:GetObject Resource: - !Sub 'arn:aws:s3:::aws-ssm-${AWS::Region}/*' - !Sub 'arn:aws:s3:::aws-windows-downloads-${AWS::Region}/*' - !Sub 'arn:aws:s3:::amazon-ssm-${AWS::Region}/*' - !Sub 'arn:aws:s3:::amazon-ssm-packages-${AWS::Region}/*' - !Sub 'arn:aws:s3:::${AWS::Region}-birdwatcher-prod/*' - !Sub 'arn:aws:s3:::patch-baseline-snapshot-${AWS::Region}/*' Effect: Allow PolicyName: ssm-custom-s3-policy - PolicyDocument: Version: '2012-10-17 ' Statement: - Action: - s3:GetObject - s3:PutObject - s3:PutObjectAcl - s3:ListBucket Resource: - !Sub 'arn:${AWS::Partition}:s3:::amzn-s3-demo-bucket/*' - !Sub 'arn:${AWS::Partition}:s3:::amzn-s3-demo-bucket' Effect: Allow PolicyName: s3-instance-bucket-policy Path: "/" ManagedPolicyArns: - !Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore' - !Sub 'arn:${AWS::Partition}:iam::aws:policy/CloudWatchAgentServerPolicy' AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "ec2.amazonaws.com" - "ssm.amazonaws.com" Action: "sts:AssumeRole" SSMInstanceProfile: Type: "AWS::IAM::InstanceProfile" Properties: Roles: - !Ref SSMInstanceRole EC2Instance: Type: "AWS::EC2::Instance" Properties: ImageId: !Ref LatestAmiId InstanceType: "t3.medium" IamInstanceProfile: !Ref SSMInstanceProfile Tags: - Key: 'nginx' Value: 'yes' NginxAssociation: DependsOn: EC2Instance # CloudFormation Resource Type that creates State Manager Associations Type: AWS::SSM::Association Properties: # Command Document that this Association will run Name: AWS-RunShellScript # Targeting Instance by Tags Targets: - Key: tag:nginx Values: - 'yes' # The passing in the S3 Bucket that is created in the template that logs will be sent to OutputLocation: S3Location: OutputS3BucketName: !Ref amzn-s3-demo-bucket OutputS3KeyPrefix: 'logs/' # Parameters for the AWS-RunShellScript, in this case commands to install nginx Parameters: commands: - | sudo amazon-linux-extras install nginx1 -y sudo service nginx start Outputs: WebServerPublic: Value: !GetAtt 'EC2Instance.PublicDnsName' Description: Public DNS for WebServer ``` -------------------------------- ### Create a Configured Model Algorithm (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cleanroomsml-configuredmodelalgorithm.md This example demonstrates how to create a configured model algorithm using JSON format. It includes configurations for training and inference containers, along with tags. ```json { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "MyConfiguredModelAlgorithm": { "Type": "AWS::CleanRoomsML::ConfiguredModelAlgorithm", "Properties": { "Name": "MyMLAlgorithm", "Description": "A configured model algorithm for collaborative ML", "RoleArn": "arn:aws:iam::123456789012:role/CleanRoomsMLServiceRole", "TrainingContainerConfig": { "ImageUri": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-training-image:latest", "MetricDefinitions": [ { "Name": "loss", "Regex": "Loss: ([0-9\\.]+)" } ] }, "InferenceContainerConfig": { "ImageUri": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-inference-image:latest" }, "Tags": [ { "Key": "Environment", "Value": "Production" } ] } } } } ``` -------------------------------- ### Auto Scaling Launch Configuration Setup Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-efs.md Defines an Auto Scaling launch configuration that includes package installation (nfs-utils) and file setup for mounting EFS. ```yaml LaunchConfiguration: Type: AWS::AutoScaling::LaunchConfiguration Metadata: AWS::CloudFormation::Init: configSets: MountConfig: - setup - mount setup: packages: yum: nfs-utils: [] files: "/home/ec2-user/post_nfsstat": content: !Sub | #!/bin/bash INPUT="$(cat)" CW_JSON_OPEN='{ "Namespace": "EFS", "MetricData": [ ' CW_JSON_CLOSE=' ] }' CW_JSON_METRIC='' METRIC_COUNTER=0 for COL in 1 2 3 4 5 6; do COUNTER=0 METRIC_FIELD=$COL DATA_FIELD=$(($COL+($COL-1))) while read line; do if [[ COUNTER -gt 0 ]]; then LINE=`echo $line | tr -s ' ' ` AWS_COMMAND="aws cloudwatch put-metric-data --region ${AWS::Region}" MOD=$(( $COUNTER % 2)) if [ $MOD -eq 1 ]; then ``` -------------------------------- ### Launch Configuration Update Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-updatepolicy.md Shows a basic structure for an AWS::AutoScaling::LaunchConfiguration resource with metadata for CloudFormation Init. ```json "LaunchConfigUpdateRubygemsPkg": { "Type" : "AWS::AutoScaling::LaunchConfiguration", "Metadata" : { "Comment" : "Install a simple PHP application", "AWS::CloudFormation::Init" : { ... } } } ``` -------------------------------- ### Example CloudFormation Resource Policy Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudtrail-resourcepolicy.md Creates a resource policy allowing a specific AWS account to call PutAuditEvents on a CloudTrail channel. Refer to the CloudTrail User Guide for more examples. ```json { "Type": "AWS:CloudTrail:ResourcePolicy", "Properties": { "ResourceArn": "arn:aws:cloudtrail:us-east-1:01234567890:channel/EXAMPLE8-0558-4f7e-a06a-43969EXAMPLE", "ResourcePolicy": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"DeliverEventsThroughChannel\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": [ \"arn:aws:iam::111122223333:root\" ] }, \"Action\":\"cloudtrail-data:PutAuditEvents\", \"Resource\": \"arn:aws:cloudtrail:us-east-1:01234567890:channel/EXAMPLE8-0558-4f7e-a06a-43969EXAMPLE\" } ] }" } } ``` -------------------------------- ### Deployment Creation Example (YAML) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-apigatewayv2-deployment.md This example demonstrates how to create an AWS::ApiGatewayV2::Deployment resource for an API named MyApi with a stage named Beta. It also specifies a description and depends on a route named MyRoute. ```yaml Deployment: Type: 'AWS::ApiGatewayV2::Deployment' DependsOn: - MyRoute Properties: Description: My deployment ApiId: !Ref MyApi StageName: Beta ``` -------------------------------- ### Get FileSystem ID Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html Shows an example of the FileSystemId attribute for an EFS file system. ```text fs-abcdef0123456789a ``` -------------------------------- ### Example Global Network Creation Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-networkmanager-globalnetwork.md This example demonstrates how to create a global network using CloudFormation. ```yaml Resources: MyGlobalNetwork: Type: AWS::NetworkManager::GlobalNetwork Properties: Description: My first global network Tags: - Key: Name Value: MyGlobalNetwork ``` -------------------------------- ### Create a Configured Model Algorithm (YAML) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cleanroomsml-configuredmodelalgorithm.md This example demonstrates how to create a configured model algorithm using YAML format. It includes configurations for training and inference containers, along with tags. ```yaml AWSTemplateFormatVersion: '2010-09-09' Resources: MyConfiguredModelAlgorithm: Type: AWS::CleanRoomsML::ConfiguredModelAlgorithm Properties: Name: MyMLAlgorithm Description: A configured model algorithm for collaborative ML RoleArn: arn:aws:iam::123456789012:role/CleanRoomsMLServiceRole TrainingContainerConfig: ImageUri: 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-training-image:latest MetricDefinitions: - Name: loss Regex: 'Loss: ([0-9\.]+)' InferenceContainerConfig: ImageUri: 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-inference-image:latest Tags: - Key: Environment Value: Production ``` -------------------------------- ### Get FileSystem ARN Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html Shows an example of the ARN attribute for an EFS file system. ```text arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-0123456789abcdef8 ``` -------------------------------- ### Deployment Creation Example (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-apigatewayv2-deployment.md This example demonstrates how to create an AWS::ApiGatewayV2::Deployment resource for an API named MyApi with a stage named Beta. It also specifies a description and depends on a route named MyRoute. ```json { "Deployment": { "Type": "AWS::ApiGatewayV2::Deployment", "DependsOn": [ "MyRoute" ], "Properties": { "Description": "My deployment", "ApiId": { "Ref": "MyApi" }, "StageName": "Beta" } } } ``` -------------------------------- ### Ref Function Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-mediapackage-originendpoint.md Use the Ref function to get the name of the origin endpoint. ```json { "Ref": "myOriginEndpoint" } ``` -------------------------------- ### VPC Configuration Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html Example demonstrating how to connect a Lambda function to a VPC using CloudFormation. ```yaml Connect a function to a VPC. ``` -------------------------------- ### Create a Mock GET Method Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-apigateway-method.md Example of creating a mock GET method for an API Gateway REST API. This includes defining request and response parameters, and integration details for a mock endpoint. ```json { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "Api": { "Type": "AWS::ApiGateway::RestApi", "Properties": { "Name": "myAPI" } }, "MockMethod": { "Type": "AWS::ApiGateway::Method", "Properties": { "RestApiId": { "Ref": "Api" }, "ResourceId": { "Fn::GetAtt": [ "Api", "RootResourceId" ] }, "HttpMethod": "GET", "AuthorizationType": "NONE", "RequestParameters": { "method.request.header.myheader": false }, "Integration": { "Type": "MOCK", "RequestParameters": { "integration.request.header.header1": "method.request.header.myheader" }, "RequestTemplates": { "application/json": "{\"statusCode\": 200}" }, "IntegrationResponses": [ { "StatusCode": "200", "ResponseParameters": { "method.response.header.header1": "integration.response.header.header1", "method.response.header.header2": "'staticvalue'" } } ] }, "MethodResponses": [ { "StatusCode": "200", "ResponseParameters": { "method.response.header.header1": true, "method.response.header.header2": true } } ] } } } } ``` ```yaml AWSTemplateFormatVersion: '2010-09-09' Resources: Api: Type: AWS::ApiGateway::RestApi Properties: Name: myAPI MockMethod: Type: AWS::ApiGateway::Method Properties: RestApiId: !Ref Api ResourceId: !GetAtt Api.RootResourceId HttpMethod: GET AuthorizationType: NONE RequestParameters: method.request.header.myheader: false Integration: Type: MOCK RequestTemplates: application/json: "{\"statusCode\": 200}" RequestParameters: integration.request.header.header1: method.request.header.myheader IntegrationResponses: - StatusCode: '200' ResponseParameters: method.response.header.header1: integration.response.header.header1 method.response.header.header2: '''staticvalue''' MethodResponses: - StatusCode: '200' ResponseParameters: method.response.header.header1: true method.response.header.header2: true ``` -------------------------------- ### Example Yum Repository Configuration Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-ssm-patchbaseline-patchsource.md Provides an example of a configuration for yum repositories. ```text [main] name=MyCustomRepository baseurl=https://my-custom-repository enabled=1 ``` -------------------------------- ### YAML Example: Get Multiple Load Balancer Attributes Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html This example retrieves multiple attributes, 'SourceSecurityGroup.OwnerAlias' and 'SourceSecurityGroup.GroupName', for a load balancer named 'myELB' using the Fn::GetAtt intrinsic function in YAML. ```yaml !GetAtt myELB.SourceSecurityGroup.OwnerAlias !GetAtt myELB.SourceSecurityGroup.GroupName ``` -------------------------------- ### Example Docker Image Tag Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-codebuild-project-environment.md Illustrates the format for specifying a Docker image using a tag. ```text /: ``` -------------------------------- ### Ref Function Example for AWS::FSx::Snapshot Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-fsx-snapshot.md Example of using the intrinsic Ref function to get the ID of an AWS::FSx::Snapshot resource. The Ref function returns the snapshot ID, such as 'fsvolsnap-0123456789abcedf5'. ```json {"Ref":"logical_snapshot_id"} ``` -------------------------------- ### SageMaker Notebook Instance Lifecycle Configuration Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-sagemaker-notebookinstancelifecycleconfig.md This example demonstrates how to create a SageMaker notebook instance with an associated lifecycle configuration. It shows the JSON and YAML formats for defining the resources. ```json { "Description": "Basic NotebookInstance test", "Resources": { "BasicNotebookInstance": { "Type": "AWS::SageMaker::NotebookInstance", "Properties": { "InstanceType": "ml.t2.medium", "RoleArn": { "Fn::GetAtt" : [ "ExecutionRole", "Arn" ] }, "LifecycleConfigName": { "Fn::GetAtt" : [ "BasicNotebookInstanceLifecycleConfig", "NotebookInstanceLifecycleConfigName" ] } }, "BasicNotebookInstanceLifecycleConfig": { "Type": "AWS::SageMaker::NotebookInstanceLifecycleConfig", "Properties": { "OnStart": [ { "Content": { "Fn::Base64": "echo 'hello'" } } ] } }, "ExecutionRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17" , "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "sagemaker.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/", "Policies": [ { "PolicyName": "root", "PolicyDocument": { "Version": "2012-10-17" , "Statement": [ { "Effect": "Allow", "Action": "*", "Resource": "*" } ] } } ] } } }, "Outputs": { "BasicNotebookInstanceId": { "Value": { "Ref" : "BasicNotebookInstance" } }, "BasicNotebookInstanceLifecycleConfigId": { "Value": { "Ref" : "BasicNotebookInstanceLifecycleConfig" } } } } } ``` ```yaml Description: "Basic NotebookInstance test" Resources: BasicNotebookInstance: Type: "AWS::SageMaker::NotebookInstance" Properties: InstanceType: "ml.t2.medium" RoleArn: !GetAtt ExecutionRole.Arn LifecycleConfigName: !GetAtt BasicNotebookInstanceLifecycleConfig.NotebookInstanceLifecycleConfigName BasicNotebookInstanceLifecycleConfig: Type: "AWS::SageMaker::NotebookInstanceLifecycleConfig" Properties: OnStart: - Content: Fn::Base64: "echo 'hello'" ExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "sagemaker.amazonaws.com" Action: - "sts:AssumeRole" Path: "/" Policies: - PolicyName: "root" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: "*" Resource: "*" Outputs: BasicNotebookInstanceId: Value: !Ref BasicNotebookInstance BasicNotebookInstanceLifecycleConfigId: Value: !Ref BasicNotebookInstanceLifecycleConfig ``` -------------------------------- ### JSON Example: Get Load Balancer DNS Name Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html This JSON example demonstrates how to retrieve the DNS name of a load balancer using Fn::GetAtt. Ensure the logical name 'myELB' matches your resource definition. ```json "Fn::GetAtt" : [ "myELB" , "DNSName" ] ``` -------------------------------- ### YAML Example: Get Load Balancer DNS Name Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html This YAML example shows how to obtain the DNS name of a load balancer using the short form of Fn::GetAtt. Replace 'myELB' with the actual logical ID of your load balancer. ```yaml !GetAtt myELB.DNSName ``` -------------------------------- ### YAML Example: EC2 Instance Depends on RDS DB Instance Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html This YAML snippet shows the equivalent of the JSON example, defining an EC2 instance that depends on an RDS DB instance. It ensures the database is provisioned before the EC2 instance starts. ```yaml Resources: Ec2Instance: Type: AWS::EC2::Instance Properties: ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64}}' InstanceType: t2.micro DependsOn: myDB myDB: Type: AWS::RDS::DBInstance Properties: AllocatedStorage: '5' DBInstanceClass: db.t2.small Engine: MySQL EngineVersion: '5.5' MasterUsername: '{{resolve:secretsmanager:MySecret:SecretString:username}}' MasterUserPassword: '{{resolve:secretsmanager:MySecret:SecretString:password}}' ``` -------------------------------- ### Construct Install URL with Fn::Join in JSON Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.md Constructs a WordPress installation URL using Fn::Join, combining a base URL, the load balancer's DNS name, and a path. This output provides a direct link to the installation page. ```JSON { "Outputs": { "InstallURL": { "Value": { "Fn::Join": [ "", [ "http://", { "Fn::GetAtt": [ "ElasticLoadBalancer", "DNSName" ] }, "/wp-admin/install.php" ] ] }, "Description": "Installation URL of the WordPress website" } } } ``` -------------------------------- ### Ref Return Value Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-elementalinference-feed.md Demonstrates how to use the intrinsic Ref function to get the ID of the feed. This is useful for referencing the feed in other resources. ```json { "Ref":"abcdefghijklmnopqrst" } ``` -------------------------------- ### List All Resource Types with Pagination Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ListTypes.md This example shows how to list all resource types, including private and public ones, and how to handle pagination using MaxResults and NextToken. It retrieves the first 10 results and provides a token for fetching subsequent pages. ```shell aws cloudformation list-types --max-results 10 --next-token "some-token-value" ``` -------------------------------- ### Create GameLift Fleet with a Build Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-gamelift-fleet.md This example demonstrates how to create a GameLift fleet using a custom game build. It specifies network permissions, instance type, fleet type, log paths, and runtime configuration. The example syntax for log path and server launch path uses values for a Windows build. ```json { "Resources": { "FleetResource": { "Type": "AWS::GameLift::Fleet", "Properties": { "BuildId": { "Ref": "BuildResource" }, "CertificateConfiguration": { "CertificateType": "DISABLED" }, "Description": "Description of my Fleet", "DesiredEC2Instances": 1, "EC2InboundPermissions": [ { "FromPort": 1234, "ToPort": 1324, "IpRange": "0.0.0.0/24", "Protocol": "TCP" }, { "FromPort": 1356, "ToPort": 1578, "IpRange": "192.168.0.0/24", "Protocol": "UDP" } ], "EC2InstanceType": "c4.large", "FleetType": "SPOT", "LogPaths": [ "c:\\game\\testlog.log", "c:\\game\\testlog2.log" ], "MetricGroups": [ "MetricGroupName" ], "Name": "MyGameFleet", "NewGameSessionProtectionPolicy": "FullProtection", "ResourceCreationLimitPolicy": { "NewGameSessionsPerCreator": 5, "PolicyPeriodInMinutes": 2 }, "RuntimeConfiguration": { "GameSessionActivationTimeoutSeconds": 300, "MaxConcurrentGameSessionActivations": 1, "ServerProcesses": [ { "ConcurrentExecutions": 1, "LaunchPath": "c:\\game\\TestApplicationServer.exe" } ] }, "Locations": [ "us-west-2", "us-east-1", "eu-west-1" ] } } } } ``` -------------------------------- ### Ref Function Example Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-connect-evaluationform.md Use the `Ref` function to get the evaluation form name. This is useful for referencing the resource in other parts of your CloudFormation template. ```json { "Ref": "myEvaluationFormName" } ``` -------------------------------- ### Create an On-Demand AWS Glue Trigger Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html Example of creating an on-demand trigger that initiates a single job. This is useful for manually starting workflows. ```json { "Resources": { "OnDemandJobTrigger": { "Type": "AWS::Glue::Trigger", "Properties": { "Type": "ON_DEMAND", "Description": "DESCRIPTION_ON_DEMAND", "Actions": [ { "JobName": "prod-job2" } ], "Name": "prod-trigger1-ondemand" } } } } ``` ```yaml Resources: OnDemandJobTrigger: Type: AWS::Glue::Trigger Properties: Type: ON_DEMAND Description: DESCRIPTION_ON_DEMAND Actions: - JobName: prod-job2 Name: prod-trigger1-ondemand ``` -------------------------------- ### Launch Template with Instance Metadata Options (JSON) Source: https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-launchtemplate.md Creates a launch template with instance metadata options enabled to allow access to instance tags. Includes image ID, instance type, security group IDs, and tag specifications for the instance. ```json { "Resources": { "myLaunchTemplate": { "Type": "AWS::EC2::LaunchTemplate", "Properties": { "LaunchTemplateData": { "ImageId": "ami-0a70b9d193ae8a799", "InstanceType": "t2.micro", "MetadataOptions": { "InstanceMetadataTags": "enabled" }, "SecurityGroupIds": [ "sg-12a4c434" ], "TagSpecifications": [ { "ResourceType": "instance", "Tags": [ { "Key": "department", "Value": "dev" } ] } ] } } } } } ```