Assistance with CloudFormation and CloudWatch Agent


Working on some CloudFormation to install and configure the CloudWatch Agent. However, I'm having trouble writing this literal file that includes variables so I can use it for CloudWatch. Towards the bottom of the code, I need the ${aws:ImageId} written as is and not replaced by a value in CloudFormation.

I've tried removing !Sub, but it results in an empty string. I've tried using $!{aws:ImageId} and ${!aws:ImageId} but CloudFormation removes the $, resulting in a string with {aws:ImageId} or it results in a blank value.

Two other thoughts - save this on a public S3 bucket and pull it down or create a new image with the file and CloudWatch already installed. This is for a hands-on lab where I ONLY have access to CloudFormation and other AWS services,*** and the accounts are ephemeral.***

Running out of ideas, so I'm posting here for some help.

    Type: AWS::EC2::Instance
      InstanceType: t3.micro
        Ref: InstanceProfile
        Ref: LatestAmiId
        - Ref: ProductionSecurityGroup
        Ref: PrivateSubnetAz2
          !Sub |
            sudo hostname prd-app-cache-002
            yum update -y
            yum install -y amazon-cloudwatch-agent
            echo "Writing CloudWatch Agent configuration file"
            sudo cat << EOF > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
              "agent": {
                "metrics_collection_interval": 10,
                "run_as_user": "cwagent"
              "metrics": {
                "namespace": "prd-app-cache-002",
                "aggregation_dimensions": [["InstanceId"]],
                "append_dimensions": {
                  "ImageId": "${aws:ImageId}",
                  "InstanceId": "${aws:InstanceId}",
                  "InstanceType": "${aws:InstanceType}"
1 Answer

You can either place amazon-cloudwatch-agent.json in S3 and get it from aws s3 cp, etc., or you can set it in the Systems Manager parameter store and get the configuration.
Incidentally, if you store the data in the Systems Manager parameter store, you can start CloudWatch Agent with the following command.

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c ssm:configuration-parameter-store-name
profile picture
answered 5 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions