cloudformation-coverage-roadmap icon indicating copy to clipboard operation
cloudformation-coverage-roadmap copied to clipboard

AWS::CloudFront::Distribution - MonitoringSubscriptionConfig

Open phy25 opened this issue 4 years ago • 8 comments

Scope of request

I would like to enable CloudFront additional metrics mentioned in https://aws.amazon.com/about-aws/whats-new/2019/12/cloudfront-realtime-metrics/ through CloudFormation rather than manually enabling it through AWS console. Looking at the request AWS console makes, MonitoringSubscriptionConfig might be the right attribute, but it doesn't seem to be supported by CloudFormation yet.

Expected behavior

The attribute seems to be a simple boolean value at this point, so I guess an Update behavior should be enough.

Helpful Links to speed up research and evaluation

https://aws.amazon.com/about-aws/whats-new/2019/12/cloudfront-realtime-metrics/

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/viewing-cloudfront-metrics.html#monitoring-console.distributions-additional

Category

Networking & Content

phy25 avatar Jul 02 '20 14:07 phy25

Seems like that feature is missing in the CloudFront API as well. Not a web service?

andreaswittig avatar Aug 17 '20 08:08 andreaswittig

API capability should be available:

CreateMonitoringSubscription - Amazon CloudFront https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateMonitoringSubscription.html

mikkotikkanen avatar Dec 18 '20 07:12 mikkotikkanen

It's been over a year since the feature has been released. @PatMyron: Have we reached some sort of milestone yet that allows us to get some eyes on this request?

monken avatar Feb 15 '21 19:02 monken

Closing in on 1.5 years between feature launch and Cfn not supporting this ... 🙄

jpluscplusm avatar Apr 04 '21 13:04 jpluscplusm

It's a shame the feature is not yet supported. Ended up with CloudFormation Custom Resource which invokes lambda and configures CloudFront Monitoring Subscription.

CloudFormation example

MonitoringSubscriptionLambdaServiceRole:
  Type: AWS::IAM::Role
  Properties:
    AssumeRolePolicyDocument:
      Statement:
        - Action: sts:AssumeRole
          Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
      Version: "2012-10-17"
    ManagedPolicyArns:
      - Fn::Join:
          - ""
          - - "arn:"
            - Ref: AWS::Partition
            - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
MonitoringSubscriptionLambdaServiceRoleDefaultPolicy:
  Type: AWS::IAM::Policy
  Properties:
    PolicyDocument:
      Statement:
        - Action:
            - cloudfront:GetMonitoringSubscription
            - cloudfront:CreateMonitoringSubscription
            - cloudfront:DeleteMonitoringSubscription
          Effect: Allow
          Resource: "*"
          Sid: AllowSetRealtimeMonitoringSubscription
      Version: "2012-10-17"
    PolicyName: MonitoringSubscriptionLambdaServiceRoleDefaultPolicy
    Roles:
      - Ref: MonitoringSubscriptionLambdaServiceRole
MonitoringSubscriptionLambda:
  Type: AWS::Lambda::Function
  Properties:
    Code:
      ZipFile: |
        var aws = require('aws-sdk');
        var response = require('cfn-response');

        var cloudfront = new aws.CloudFront();

        exports.handler = function (event, context) {
            console.log(event)
            var distributionId = event.ResourceProperties.DistributionId
            var realtimeMetrics = event.ResourceProperties.RealtimeMetrics === 'true'

            if (event.RequestType == "Delete") {
                console.log("Response immediately on custom resource deletion")
                response.send(event, context, response.SUCCESS);
                return;
            }

            var strStatus = realtimeMetrics ? "Enabled" : "Disabled"
            var params = {
                DistributionId: distributionId,
                MonitoringSubscription: {
                    RealtimeMetricsSubscriptionConfig: {
                        RealtimeMetricsSubscriptionStatus: strStatus
                    }
                }
            };
            console.log("Set realtime monitoring subscription status to ", strStatus)
            cloudfront.createMonitoringSubscription(params, function (err, data) {
                if (err) console.error(err); // an error occurred
                else console.log(data);      // successful response
                response.send(event, context, response.SUCCESS);
            });
        };
    Role:
      Fn::GetAtt:
        - MonitoringSubscriptionLambdaServiceRole
        - Arn
    Description: Sets or disables the CloudFront realtime monitoring subscription
    Handler: index.handler
    MemorySize: 128
    Runtime: nodejs14.x
    Timeout: 8
InvokeMonitoringSubscriptionLambda1:
    Type: AWS::CloudFormation::CustomResource
    Properties:
      ServiceToken:
        Fn::GetAtt:
          - MonitoringSubscriptionLambda
          - Arn
      DistributionId:
        Ref: <DISTRIBUTION_ID>
      RealtimeMetrics: true
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete

But there is one critical part with custom resource & lambda combination. The custom resource executes the lambda only on its creation or deletion (and passing parameters to Custom resource doesn't help here). In order to make sure the lambda is executed each time the parameter is changed in the config, I end up with a small hash func in my code that prepares this template - notice the the number at the name InvokeMonitoringSubscriptionLambda1 of the custom resource. The idea to change the CustomResource Logical ID whenever the hash of the parameters passed to lambda changes. CloudFormation service will replace the resource and execute lambda correctly with new parameters.

Such approach can be used to call aws sdk to make any adjustments for not yet supported definitions by CloudFormation.

At last, but very important, the lambda that takes part in CloudFormation lifetime as cfn-resource, doesn't support async/await constructions, so should be pure JS, with nested conditions and callback functions if you decide to put more complex logic here.

vorotech avatar Nov 07 '21 10:11 vorotech

Any ETA on this?

kataik avatar Mar 03 '22 23:03 kataik

Any updates on this?

AljoschaDembowsky2909 avatar Jul 28 '22 09:07 AljoschaDembowsky2909

Any updates on this?

SmoshySmosh avatar Aug 21 '22 22:08 SmoshySmosh

Isn't there https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-monitoringsubscription.html ?

tenjaa avatar Dec 02 '22 22:12 tenjaa

This issue is marked as "coming soon" on the board, and the new CloudFormation field appeared in CDK on a Oct 3 commit.

I am going to help close this.

phy25 avatar Dec 03 '22 16:12 phy25