redisaws-cloudformationaws-cdkcloudwatch-alarmselastic-cache

Creating CloudWatch Alarm for ElasticCache (Redis) via CDK


I have an existing Redis "Instance" which is working fine, created by CDK Code:

redis = new elasticache.CfnReplicationGroup(this, id + 'RedisCluster', {
            port: 6379,
            clusterMode: 'disabled',
            replicasPerNodeGroup: 1,
            cacheNodeType: cache.t4g.micro,
            engine: 'Redis',
            multiAzEnabled: true,
            autoMinorVersionUpgrade: false,
            cacheParameterGroupName: parameterGroup.ref,
            engineVersion: '7.0',
            cacheSubnetGroupName: subnetGroup.cacheSubnetGroupName,
            securityGroupIds: [securityGroup.securityGroupId],
            replicationGroupDescription: 'My Redis',
        });

Now I want to add a CloudWatch Alarm, and I am attempting something like this:

const alarm = new cloudwatch.Alarm(this, 'MyAlarm', {
        metric: new cloudwatch.Metric({
            namespace: "AWS/ElastiCache",
            metricName: "DatabaseMemoryUsagePercentage",
            period: Duration.minutes(1),
            unit: cloudwatch.Unit.PERCENT,
            statistic: cloudwatch.Stats.AVERAGE,
            dimensionsMap: {
                CacheClusterId: << WHAT VAUE GOES HERE >>,             
                // CacheNodeId: << IS THIS NEEDED? >>,
            },
        }),
        threshold: 60, // Memory Utilisation percentage
        evaluationPeriods: 1,
        datapointsToAlarm: 1,
    });

I am not sure what to use for CacheClusterId.

I am trying to get values from the redis variable, e.g.

    console.log(redis.replicationGroupId); // Returns null
    console.log(redis.primaryClusterId); // Returns null
    console.log(redis.node); // Returns some data, but can't seem to find a unique identifier that I would need

How can I add a CloudWatch Alarm to this Redis "Instance"


Solution

  • I came up with the following solution:

    const redis = new elasticache.CfnReplicationGroup( /* ... */ );
    
    const alarm = new cloudwatch.Alarm( /* ... */ ,
        {  // props
           namespace: "AWS/ElastiCache",
           dimensionsMap: {
               CacheClusterId: redis.ref + '-001',
           },
           /* ... */
        }
    

    Because I also had a read replica, I needed to repeat this code for the other node, (e.g. CacheClusterId: redis.ref + '-002')

    I do not like my solution, as the -001 and -002 are hard coded. Please let me know if anyone know a neat way to avoid hard coding those values.