|
| 1 | +import { CfnCacheCluster, CfnCacheClusterProps, CfnSubnetGroup } from 'aws-cdk-lib/aws-elasticache'; |
| 2 | +import { Names } from 'aws-cdk-lib'; |
| 3 | +import { Port, SecurityGroup } from 'aws-cdk-lib/aws-ec2'; |
| 4 | +import { Construct } from 'constructs'; |
| 5 | +import { VpcForServerlessApp } from '../vpc/VpcForServerlessApp'; |
| 6 | + |
| 7 | +export type RedisProps = Partial<CfnCacheClusterProps> & { |
| 8 | + vpc: VpcForServerlessApp; |
| 9 | +}; |
| 10 | + |
| 11 | +export class Redis extends CfnCacheCluster { |
| 12 | + constructor(scope: Construct, id: string, props: RedisProps) { |
| 13 | + const securityGroup = new SecurityGroup(scope, `${id}SecurityGroup`, { |
| 14 | + vpc: props.vpc, |
| 15 | + description: 'Security group for Redis', |
| 16 | + allowAllOutbound: false, |
| 17 | + allowAllIpv6Outbound: false, |
| 18 | + }); |
| 19 | + |
| 20 | + const stackId = Names.uniqueResourceName(securityGroup, { |
| 21 | + maxLength: 100, |
| 22 | + }); |
| 23 | + const subnetGroup = new CfnSubnetGroup(scope, `${id}SubnetGroup`, { |
| 24 | + cacheSubnetGroupName: `${stackId}${id}SubnetGroup`, |
| 25 | + description: 'Subnet group for Redis', |
| 26 | + // Isolated subnets don't have a route to the internet (unlike private), this is what we want |
| 27 | + subnetIds: props.vpc.isolatedSubnets.map((subnet) => subnet.subnetId), |
| 28 | + }); |
| 29 | + |
| 30 | + props.vpc.appSecurityGroup.connections.allowTo( |
| 31 | + securityGroup, |
| 32 | + Port.tcp(props.port ?? 6379), |
| 33 | + 'Allow Lambda functions to connect to Redis' |
| 34 | + ); |
| 35 | + |
| 36 | + super(scope, id, { |
| 37 | + engine: 'redis', |
| 38 | + cacheNodeType: 'cache.t3.micro', |
| 39 | + numCacheNodes: 1, |
| 40 | + vpcSecurityGroupIds: [securityGroup.securityGroupId], |
| 41 | + cacheSubnetGroupName: subnetGroup.cacheSubnetGroupName, |
| 42 | + ...props, |
| 43 | + }); |
| 44 | + |
| 45 | + this.addDependsOn(subnetGroup); |
| 46 | + } |
| 47 | +} |
0 commit comments