@aws-cdk/aws-elasticache-alpha

中文文档
2.275.0-alpha.0发布于 2026/10/27Apache-2.0TypeScriptCommonJS零依赖近 30 天下载 4.4万

The CDK Construct Library for AWS::ElastiCache

原始使用文档
文档目录17 节
  1. Serverless Cache
  2. Connecting to serverless cache
  3. Using a custom engine version
  4. Cache usage limits
  5. Backups and restore
  6. Encryption at rest
  7. Customer Managed Key for encryption at rest
  8. Metrics and monitoring
  9. Import an existing serverless cache
  10. User and User Group
  11. RBAC
  12. Create users
  13. Default user
  14. Add users to the user group
  15. Assign user group
  16. Grant permissions to IAM-enabled users
  17. Import an existing user and user group

ElastiCache CDK Construct Library


cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


This module has constructs for Amazon ElastiCache.

  • The ServerlessCache construct facilitates the creation and management of serverless cache.
  • The User and UserGroup constructs facilitate the creation and management of users for the cache.

Serverless Cache

Amazon ElastiCache Serverless is a serverless option that automatically scales cache capacity based on application traffic patterns. You can create a serverless cache using the ServerlessCache construct:

const vpc = new ec2.Vpc(this, 'VPC');
 
const cache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  vpc,
});

Connecting to serverless cache

To control who can access the serverless cache by the security groups, use the .connections attribute.

The serverless cache has a default port 6379.

This example allows an EC2 instance to connect to the serverless cache:

declare const serverlessCache: elasticache.ServerlessCache;
declare const instance: ec2.Instance;
 
// allow the EC2 instance to connect to serverless cache on default port 6379
serverlessCache.connections.allowDefaultPortFrom(instance);

Using a custom engine version

The named CacheEngine and UserEngine static members cover the versions available at the time of the most recent CDK release. If ElastiCache releases a new engine version before it is added as a named member, use the .of(...) factory to target it without waiting for a CDK update:

declare const vpc: ec2.Vpc;

new elasticache.ServerlessCache(this, 'ServerlessCache', {
  // Use any engine/version combination supported by ElastiCache:
  engine: elasticache.CacheEngine.of('valkey', '9'),
  vpc,
});

The same pattern applies to UserEngine.of(engineType) for users and user groups.

Cache usage limits

You can configure usage limits on both cache data storage and ECPU/second for your cache to control costs and ensure predictable performance.

Configuration options:

  • Maximum limits: Ensure your cache usage never exceeds the configured maximum
  • Minimum limits: Reserve a baseline level of resources for consistent performance
  • Both: Define a range where your cache usage will operate

For more infomation, see Setting scaling limits to manage costs.

declare const vpc: ec2.Vpc;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  engine: elasticache.CacheEngine.VALKEY_LATEST,
  vpc,
  cacheUsageLimits: {
    // cache data storage limits (GB)
    dataStorageMinimumSize: Size.gibibytes(2), // minimum: 1GB
    dataStorageMaximumSize: Size.gibibytes(3), // maximum: 5000GB
    // rate limits (ECPU/second)
    requestRateLimitMinimum: 1000, // minimum: 1000
    requestRateLimitMaximum: 10000, // maximum: 15000000
  },
});

Backups and restore

You can enable automatic backups for serverless cache. When automatic backups are enabled, ElastiCache creates a backup of the cache on a daily basis.

Also you can set the backup window for any time when it's most convenient. If you don't specify a backup window, ElastiCache assigns one automatically.

For more information, see Scheduling automatic backups.

To enable automatic backups, set the backupRetentionLimit property. You can also specify the snapshot creation time by setting backupTime property:

declare const vpc: ec2.Vpc;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  backup: {
    // enable automatic backups and set the retention period to 6 days
    backupRetentionLimit: 6,
    // set the backup window to 9:00 AM UTC
    backupTime: events.Schedule.cron({
      hour: '9',
      minute: '0',
    }),
  },
  vpc,
});

You can create a final backup by setting backupNameBeforeDeletion property.

declare const vpc: ec2.Vpc;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  engine: elasticache.CacheEngine.VALKEY_LATEST,
  backup: {
    // set a backup name before deleting a cache
    backupNameBeforeDeletion: "my-final-backup-name",
  },
  vpc,
});

You can restore from backups by setting snapshot ARNs to backupArnsToRestore property:

declare const vpc: ec2.Vpc;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  engine: elasticache.CacheEngine.VALKEY_LATEST,
  backup: {
    // set the backup(s) to restore
    backupArnsToRestore: ['arn:aws:elasticache:us-east-1:123456789012:serverlesscachesnapshot:my-final-backup-name'],
  },
  vpc,
});

Encryption at rest

At-rest encryption is always enabled for Serverless Cache. There are two encryption options:

  • Default: When no kmsKey is specified (left as undefined), AWS owned KMS keys are used automatically
  • Customer Managed Key: Create a KMS key first, then pass it to the cache via the kmsKey property

Customer Managed Key for encryption at rest

ElastiCache supports symmetric Customer Managed key (CMK) for encryption at rest.

For more information, see Using customer managed keys from AWS KMS.

To use CMK, set your CMK to the kmsKey property:

import { Key } from 'aws-cdk-lib/aws-kms';
 
declare const kmsKey: Key;
declare const vpc: ec2.Vpc;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  engine: elasticache.CacheEngine.VALKEY_LATEST,
  serverlessCacheName: 'my-serverless-cache',
  vpc,
  // set Customer Managed Key
  kmsKey,
});

Metrics and monitoring

You can monitor your serverless cache using CloudWatch Metrics via the metric method.

For more information about serverless cache metrics, see Serverless metrics and events for Valkey and Redis OSS and Serverless metrics and events for Memcached.

declare const serverlessCache: elasticache.ServerlessCache;
 
// The 5 minutes average of the total number of successful read-only key lookups in the cache.
const cacheHits = serverlessCache.metricCacheHitCount();
 
// The 5 minutes average of the total number of bytes used by the data stored in the cache.
const bytesUsedForCache = serverlessCache.metricDataStored();
 
// The 5 minutes average of the total number of ElastiCacheProcessingUnits (ECPUs) consumed by the requests executed on the cache.
const elastiCacheProcessingUnits = serverlessCache.metricProcessingUnitsConsumed();
 
// Create an alarm for ECPUs.
elastiCacheProcessingUnits.createAlarm(this, 'ElastiCacheProcessingUnitsAlarm', {
  threshold: 50,
  evaluationPeriods: 1,
});

Import an existing serverless cache

To import an existing ServerlessCache, use the ServerlessCache.fromServerlessCacheAttributes method:

declare const securityGroup: ec2.SecurityGroup;
 
const importedServerlessCache = elasticache.ServerlessCache.fromServerlessCacheAttributes(this, 'ImportedServerlessCache', {
  serverlessCacheName: 'my-serverless-cache',
  securityGroups: [securityGroup],
});

User and User Group

Setup required properties and create:

const newDefaultUser = new elasticache.NoPasswordUser(this, 'NoPasswordUser', {
  userId: 'default',
  accessControl: elasticache.AccessControl.fromAccessString("on ~* +@all"),
})
 
const userGroup = new elasticache.UserGroup(this, 'UserGroup', {
  users: [newDefaultUser],
});

RBAC

In Valkey 7.2 and onward and Redis OSS 6.0 onward you can use a feature called Role-Based Access Control (RBAC). RBAC is also the only way to control access to serverless caches.

RBAC enables you to control cache access through user groups. These user groups are designed as a way to organize access to caches.

For more information, see Role-Based Access Control (RBAC).

To enable RBAC for ElastiCache with Valkey or Redis OSS, you take the following steps:

  • Create users.
  • Create a user group and add users to the user group.
  • Assign the user group to a cache.

Create users

First, you need to create users by using IamUser, PasswordUser or NoPasswordUser construct.

With RBAC, you create users and assign them specific permissions by using accessString property.

For more information, see Specifying Permissions Using an Access String.

You can create an IAM-enabled user by using IamUser construct:

const user = new elasticache.IamUser(this, 'User', {
  // set user engine
  engine: elasticache.UserEngine.REDIS,
    
  // set user id
  userId: 'my-user',
 
  // set username
  userName: 'my-user',
 
  // set access string
  accessControl: elasticache.AccessControl.fromAccessString("on ~* +@all"),
});

NOTE: IAM-enabled users must have matching user id and username. For more information, see Limitations. The construct can set automatically the username to be the same as the user id.

If you want to create a password authenticated user, use PasswordUser construct:

const user = new elasticache.PasswordUser(this, 'User', {
  // set user engine
  engine: elasticache.UserEngine.VALKEY,
  
  // set user id
  userId: 'my-user-id',  
    
  // set access string
  accessControl: elasticache.AccessControl.fromAccessString("on ~* +@all"),
 
  // set username
  userName: 'my-user-name',
 
  // set up to two passwords
  passwords: [
    // "SecretIdForPassword" is the secret id for the password
    SecretValue.secretsManager('SecretIdForPassword'),
    // "AnotherSecretIdForPassword" is the secret id for the password
    SecretValue.secretsManager('AnotherSecretIdForPassword'),
  ],
});

You can also create a no password required user by using NoPasswordUser construct:

const user = new elasticache.NoPasswordUser(this, 'User', {
  // set user engine  
  engine: elasticache.UserEngine.REDIS, 
    
  // set user id
  userId: 'my-user-id',
 
  // set access string
  accessControl: elasticache.AccessControl.fromAccessString("on ~* +@all"),
 
  // set username
  userName: 'my-user-name',
});

NOTE: NoPasswordUser is only available for Redis Cache.

Default user

ElastiCache automatically creates a default user with both a user ID and username set to default. This default user cannot be modified or deleted. The user is created as a no password authentication user.

This user is intended for compatibility with the default behavior of previous Redis OSS versions and has an access string that permits it to call all commands and access all keys.

To use this automatically created default user in CDK, you can import it using NoPasswordUser.fromUserAttributes method. For more information on import methods, see the Import an existing user and user group section.

To add proper access control to a cache, replace the default user with a new one that is either disabled by setting the accessString to off -@all or secured with a strong password.

To change the default user, create a new default user with the username set to default. You can then swap it with the original default user.

For more information, see Applying RBAC to a Cache for ElastiCache with Valkey or Redis OSS.

If you want to create a new default user, userName must be default and userId must not be default by using NoPasswordUser or PasswordUser:

// use the original `default` user by using import method
const defaultUser = elasticache.NoPasswordUser.fromUserAttributes(this, 'DefaultUser', {
  // userId and userName must be 'default'
  userId: 'default',
});
 
// create a new default user
const newDefaultUser = new elasticache.NoPasswordUser(this, 'NewDefaultUser', {
  // new default user id must not be 'default'
  userId: 'new-default',
  // new default username must be 'default'
  userName: 'default',
  // set access string
  accessControl: elasticache.AccessControl.fromAccessString("on ~* +@all"),
});

NOTE: You can't create a new default user using IamUser because an IAM-enabled user's username and user ID cannot be different.

Add users to the user group

Next, use the UserGroup construct to create a user group and add users to it. Ensure that you include either the original default user or a new default user:

declare const newDefaultUser: elasticache.IUser;
declare const user: elasticache.IUser;
declare const anotherUser: elasticache.IUser;
 
const userGroup = new elasticache.UserGroup(this, 'UserGroup', {
  // add users including default user
  users: [newDefaultUser, user],
});
 
// you can also add a user by using addUser method
userGroup.addUser(anotherUser);

Assign user group

Finally, assign a user group to cache:

declare const vpc: ec2.Vpc;
declare const userGroup: elasticache.UserGroup;
 
const serverlessCache = new elasticache.ServerlessCache(this, 'ServerlessCache', {
  engine: elasticache.CacheEngine.VALKEY_LATEST,
  serverlessCacheName: 'my-serverless-cache',
  vpc,
  // assign User Group
  userGroup,
});
 

Grant permissions to IAM-enabled users

If you create IAM-enabled users, "elasticache:Connect" action must be allowed for the users and cache.

NOTE: You don't need grant permissions to no password required users or password authentication users.

For more information, see Authenticating with IAM.

To grant permissions, you can use the grantConnect method in IamUser and ServerlessCache constructs:

declare const user: elasticache.IamUser;
declare const serverlessCache: elasticache.ServerlessCache;
declare const role: iam.Role;
 
// grant "elasticache:Connect" action permissions to role
user.grantConnect(role);
serverlessCache.grants.connect(role);

Import an existing user and user group

You can import an existing user and user group by using import methods:

const stack = new Stack();
 
const importedIamUser = elasticache.IamUser.fromUserId(this, 'ImportedIamUser', 'my-iam-user-id');
 
const importedPasswordUser = elasticache.PasswordUser.fromUserAttributes(stack, 'ImportedPasswordUser', {
  userId: 'my-password-user-id',
});
 
const importedNoPasswordUser = elasticache.NoPasswordUser.fromUserAttributes(stack, 'ImportedNoPasswordUser', {
  userId: 'my-no-password-user-id',
});
 
const importedUserGroup = elasticache.UserGroup.fromUserGroupAttributes(this, 'ImportedUserGroup', {
  userGroupName: 'my-user-group-name'
});

版本与发布记录

@aws-cdk/aws-elasticache-alpha 共发布 70 个版本,首次发布于 2025/09/29;过去 12 个月发布了 64 个版本。

版本发布日期距今
2.275.0-alpha.0latest2026/10/2712 天前
2.274.0-alpha.02026/10/2018 天前
2.273.0-alpha.02026/10/0930 天前
2.272.0-alpha.02026/09/301 个月前
2.271.0-alpha.02026/09/261 个月前
2.270.0-alpha.02026/09/181 个月前

关于 @aws-cdk/aws-elasticache-alpha 的常见问题

@aws-cdk/aws-elasticache-alpha 是什么?

The CDK Construct Library for AWS::ElastiCache

如何安装 @aws-cdk/aws-elasticache-alpha?

在项目目录运行 npm install @aws-cdk/aws-elasticache-alpha,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.5.0)、aws-cdk-lib(^2.275.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-cdk/aws-elasticache-alpha 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-cdk/aws-elasticache-alpha 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws-cdk/aws-elasticache-alpha 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws-cdk/aws-elasticache-alpha 可以商用吗?

@aws-cdk/aws-elasticache-alpha 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-cdk/aws-elasticache-alpha 的下载量有多少?

根据 npm 官方下载统计,@aws-cdk/aws-elasticache-alpha 在 2026/10/07 – 2026/11/05 这 30 天内被下载 43,948 次,日均约 1,465 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-cdk/aws-elasticache-alpha 还在维护吗?

最新版本 2.275.0-alpha.0 发布于 2026/10/27(12 天前);至今共发布 70 个版本,其中过去 12 个月发布了 64 个;首次发布于 2025/09/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。