aws-cloudformation-elasticache
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS CloudFormation ElastiCache
AWS CloudFormation ElastiCache
Overview
概述
Create production-ready Amazon ElastiCache infrastructure using AWS CloudFormation templates. This skill covers Redis clusters, Memcached clusters, replication groups, parameter groups, subnet groups, security groups, template structure best practices, parameter patterns, and cross-stack references for modular, reusable infrastructure as code.
使用AWS CloudFormation模板创建可用于生产环境的Amazon ElastiCache基础设施。本内容涵盖Redis集群、Memcached集群、复制组、参数组、子网组、安全组、模板结构最佳实践、参数模式,以及用于模块化、可重用基础设施即代码的跨栈引用。
When to Use
适用场景
Use this skill when:
- Creating new ElastiCache Redis clusters (standalone or clustered)
- Setting up Redis Replication Groups for high availability
- Creating Memcached clusters for distributed caching
- Configuring ElastiCache Parameter Groups
- Setting up ElastiCache Subnet Groups for VPC deployment
- Implementing template Parameters with AWS-specific types
- Creating Outputs for cross-stack references
- Organizing templates with Mappings and Conditions
- Designing reusable, modular CloudFormation templates for caching infrastructure
在以下场景中使用本内容:
- 创建新的ElastiCache Redis集群(独立式或集群式)
- 搭建用于高可用的Redis复制组
- 创建用于分布式缓存的Memcached集群
- 配置ElastiCache参数组
- 为VPC部署设置ElastiCache子网组
- 使用AWS特定类型实现模板参数
- 创建用于跨栈引用的输出
- 使用映射和条件组织模板
- 设计用于缓存基础设施的可重用、模块化CloudFormation模板
Quick Start
快速开始
Basic Redis Cluster
基础Redis集群
yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Simple Redis ElastiCache cluster with basic configuration
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
Description: Cache node instance type
NumCacheNodes:
Type: Number
Default: 1
Description: Number of cache nodes
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: !Ref NumCacheNodes
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
RedisEndpoint:
Description: Redis cluster endpoint address
Value: !GetAtt CacheCluster.RedisEndpoint.Address
RedisPort:
Description: Redis cluster port
Value: !GetAtt CacheCluster.RedisEndpoint.Portyaml
AWSTemplateFormatVersion: 2010-09-09
Description: Simple Redis ElastiCache cluster with basic configuration
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
Description: Cache node instance type
NumCacheNodes:
Type: Number
Default: 1
Description: Number of cache nodes
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: !Ref NumCacheNodes
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
RedisEndpoint:
Description: Redis cluster endpoint address
Value: !GetAtt CacheCluster.RedisEndpoint.Address
RedisPort:
Description: Redis cluster port
Value: !GetAtt CacheCluster.RedisEndpoint.PortRedis Replication Group
Redis复制组
yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Redis Replication Group with primary and read replicas
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
Description: Cache node instance type
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for Redis replication
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
ReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Primary and replicas for HA
Engine: redis
CacheNodeType: !Ref CacheNodeType
NumNodeGroups: 1
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
PrimaryEndpoint:
Description: Primary endpoint for write operations
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Address
ReaderEndpoint:
Description: Reader endpoint for read operations
Value: !GetAtt ReplicationGroup.ReaderEndPoint.Addressyaml
AWSTemplateFormatVersion: 2010-09-09
Description: Redis Replication Group with primary and read replicas
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
Description: Cache node instance type
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for Redis replication
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
ReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Primary and replicas for HA
Engine: redis
CacheNodeType: !Ref CacheNodeType
NumNodeGroups: 1
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
PrimaryEndpoint:
Description: Primary endpoint for write operations
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Address
ReaderEndpoint:
Description: Reader endpoint for read operations
Value: !GetAtt ReplicationGroup.ReaderEndPoint.AddressTemplate Structure
模板结构
Template Sections Overview
模板章节概述
AWS CloudFormation templates are JSON or YAML files with specific sections. Each section serves a purpose in defining your infrastructure.
yaml
AWSTemplateFormatVersion: 2010-09-09 # Required - template version
Description: Optional description string # Optional descriptionAWS CloudFormation模板是具有特定章节的JSON或YAML文件。每个章节在定义基础设施时都有其用途。
yaml
AWSTemplateFormatVersion: 2010-09-09 # 必填 - 模板版本
Description: Optional description string # 可选描述Section order matters for readability but CloudFormation accepts any order
章节顺序影响可读性,但CloudFormation接受任意顺序
Mappings: {} # Static configuration tables
Metadata: {} # Additional information about resources
Parameters: {} # Input values for customization
Rules: {} # Parameter validation rules
Conditions: {} # Conditional resource creation
Transform: {} # Macro processing (e.g., AWS::Serverless)
Resources: {} # AWS resources to create (REQUIRED)
Outputs: {} # Return values after stack creation
undefinedMappings: {} # 静态配置表
Metadata: {} # 关于资源的附加信息
Parameters: {} # 用于自定义的输入值
Rules: {} # 参数验证规则
Conditions: {} # 条件式资源创建
Transform: {} # 宏处理(例如AWS::Serverless)
Resources: {} # 要创建的AWS资源(必填)
Outputs: {} # 堆栈创建后的返回值
undefinedFormat Version
格式版本
The identifies the template version. Current version is .
AWSTemplateFormatVersion2010-09-09yaml
AWSTemplateFormatVersion: 2010-09-09
Description: ElastiCache Redis Cluster TemplateAWSTemplateFormatVersion2010-09-09yaml
AWSTemplateFormatVersion: 2010-09-09
Description: ElastiCache Redis Cluster TemplateDescription
描述
Add a description to document the template's purpose. Must appear after the format version.
yaml
AWSTemplateFormatVersion: 2010-09-09
Description: >
This template creates an ElastiCache Redis cluster with:
- Multi-AZ deployment for high availability
- Automatic failover enabled
- Encrypted at-rest and in-transit
- Parameter group for custom configuration添加描述以记录模板的用途。必须出现在格式版本之后。
yaml
AWSTemplateFormatVersion: 2010-09-09
Description: >
This template creates an ElastiCache Redis cluster with:
- Multi-AZ deployment for high availability
- Automatic failover enabled
- Encrypted at-rest and in-transit
- Parameter group for custom configurationMetadata
元数据
Use for additional information about resources or parameters, including AWS::CloudFormation::Interface for parameter grouping.
Metadatayaml
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Cache Configuration
Parameters:
- CacheNodeType
- NumCacheNodes
- Engine
- Label:
default: Network
Parameters:
- CacheSubnetGroupName
- VpcSecurityGroupIds
ParameterLabels:
CacheNodeType:
default: Cache Node Instance Type
NumCacheNodes:
default: Number of Cache Nodes使用添加关于资源或参数的附加信息,包括用于参数分组的AWS::CloudFormation::Interface。
Metadatayaml
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Cache Configuration
Parameters:
- CacheNodeType
- NumCacheNodes
- Engine
- Label:
default: Network
Parameters:
- CacheSubnetGroupName
- VpcSecurityGroupIds
ParameterLabels:
CacheNodeType:
default: Cache Node Instance Type
NumCacheNodes:
default: Number of Cache NodesResources Section
资源章节
The section is the only required section. It defines AWS resources to provision.
Resourcesyaml
Resources:
# Cache Subnet Group (required for VPC deployment)
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache deployment
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
# Cache Parameter Group
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Custom parameter group for Redis
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
timeout: 300
# Cache Cluster
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.t3.micro
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroupResourcesyaml
Resources:
# 缓存子网组(VPC部署必填)
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache deployment
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
# 缓存参数组
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Custom parameter group for Redis
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
timeout: 300
# 缓存集群
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.t3.micro
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroupParameters
参数
Parameter Types
参数类型
Use AWS-specific parameter types for validation and easier selection in the console.
yaml
Parameters:
CacheNodeType:
Type: String
Description: ElastiCache node instance type
Default: cache.t3.micro
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup::Name
Description: Existing cache subnet group
VpcSecurityGroupId:
Type: AWS::EC2::SecurityGroup::Id
Description: Security group for cache cluster使用AWS特定的参数类型进行验证,并在控制台中更易于选择。
yaml
Parameters:
CacheNodeType:
Type: String
Description: ElastiCache node instance type
Default: cache.t3.micro
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup::Name
Description: Existing cache subnet group
VpcSecurityGroupId:
Type: AWS::EC2::SecurityGroup::Id
Description: Security group for cache clusterAWS::ElastiCache::CacheCluster::CacheNodeType Values
AWS::ElastiCache::CacheCluster::CacheNodeType取值
Common ElastiCache node types:
yaml
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
AllowedValues:
- cache.t3.micro
- cache.t3.small
- cache.t3.medium
- cache.t3.large
- cache.m5.large
- cache.m5.xlarge
- cache.m5.2xlarge
- cache.m5.4xlarge
- cache.r5.large
- cache.r5.xlarge
- cache.r5.2xlarge
- cache.r5.4xlarge
- cache.r6g.large
- cache.r6g.xlarge
- cache.r6g.2xlarge常见的ElastiCache节点类型:
yaml
Parameters:
CacheNodeType:
Type: String
Default: cache.t3.micro
AllowedValues:
- cache.t3.micro
- cache.t3.small
- cache.t3.medium
- cache.t3.large
- cache.m5.large
- cache.m5.xlarge
- cache.m5.2xlarge
- cache.m5.4xlarge
- cache.r5.large
- cache.r5.xlarge
- cache.r5.2xlarge
- cache.r5.4xlarge
- cache.r6g.large
- cache.r6g.xlarge
- cache.r6g.2xlargeParameter Constraints
参数约束
Add constraints to validate parameter values.
yaml
Parameters:
CacheClusterId:
Type: String
Description: Cache cluster identifier
Default: myrediscluster
AllowedPattern: "[a-zA-Z][a-zA-Z0-9]*"
ConstraintDescription: Must begin with a letter; contain only alphanumeric characters
MinLength: 1
MaxLength: 50
NumCacheNodes:
Type: Number
Description: Number of cache nodes
Default: 1
MinValue: 1
MaxValue: 10
CachePort:
Type: Number
Description: Cache port number
Default: 6379
MinValue: 1024
MaxValue: 65535添加约束以验证参数值。
yaml
Parameters:
CacheClusterId:
Type: String
Description: Cache cluster identifier
Default: myrediscluster
AllowedPattern: "[a-zA-Z][a-zA-Z0-9]*"
ConstraintDescription: Must begin with a letter; contain only alphanumeric characters
MinLength: 1
MaxLength: 50
NumCacheNodes:
Type: Number
Description: Number of cache nodes
Default: 1
MinValue: 1
MaxValue: 10
CachePort:
Type: Number
Description: Cache port number
Default: 6379
MinValue: 1024
MaxValue: 65535Engine and Version Parameters
引擎和版本参数
yaml
Parameters:
Engine:
Type: String
Description: Cache engine
Default: redis
AllowedValues:
- redis
- memcached
EngineVersion:
Type: String
Description: Cache engine version
Default: 7.0
EngineVersionMajor:
Type: String
Description: Cache engine major version
Default: "7.0"
AllowedValues:
- "6.x"
- "7.0"yaml
Parameters:
Engine:
Type: String
Description: Cache engine
Default: redis
AllowedValues:
- redis
- memcached
EngineVersion:
Type: String
Description: Cache engine version
Default: 7.0
EngineVersionMajor:
Type: String
Description: Cache engine major version
Default: "7.0"
AllowedValues:
- "6.x"
- "7.0"SSM Parameter Types
SSM参数类型
Reference Systems Manager parameters for dynamic values.
yaml
Parameters:
LatestRedisVersion:
Type: AWS::SSM::Parameter::Value<String>
Description: Latest Redis version from SSM
Default: /elasticache/redis/latest/version
LatestMemcachedVersion:
Type: AWS::SSM::Parameter::Value<String>
Description: Latest Memcached version from SSM
Default: /elasticache/memcached/latest/version引用Systems Manager参数以获取动态值。
yaml
Parameters:
LatestRedisVersion:
Type: AWS::SSM::Parameter::Value<String>
Description: Latest Redis version from SSM
Default: /elasticache/redis/latest/version
LatestMemcachedVersion:
Type: AWS::SSM::Parameter::Value<String>
Description: Latest Memcached version from SSM
Default: /elasticache/memcached/latest/versionMappings
映射
Use for static configuration data based on regions or instance types.
Mappingsyaml
Mappings:
CacheNodeConfig:
cache.t3.micro:
CPU: 2
MemoryMiB: 555
NetworkGbits: 5
cache.t3.medium:
CPU: 2
MemoryMiB: 3218
NetworkGbits: 10
cache.m5.large:
CPU: 2
MemoryMiB: 6910
NetworkGbits: 10
cache.r5.large:
CPU: 2
MemoryMiB: 13866
NetworkGbits: 10
RegionMap:
us-east-1:
RedisPort: 6379
MemcachedPort: 11211
us-west-2:
RedisPort: 6379
MemcachedPort: 11211
eu-west-1:
RedisPort: 6379
MemcachedPort: 11211
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: 1
Engine: redis
CachePort: !FindInMap [RegionMap, !Ref AWS::Region, RedisPort]使用存储基于区域或实例类型的静态配置数据。
Mappingsyaml
Mappings:
CacheNodeConfig:
cache.t3.micro:
CPU: 2
MemoryMiB: 555
NetworkGbits: 5
cache.t3.medium:
CPU: 2
MemoryMiB: 3218
NetworkGbits: 10
cache.m5.large:
CPU: 2
MemoryMiB: 6910
NetworkGbits: 10
cache.r5.large:
CPU: 2
MemoryMiB: 13866
NetworkGbits: 10
RegionMap:
us-east-1:
RedisPort: 6379
MemcachedPort: 11211
us-west-2:
RedisPort: 6379
MemcachedPort: 11211
eu-west-1:
RedisPort: 6379
MemcachedPort: 11211
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: 1
Engine: redis
CachePort: !FindInMap [RegionMap, !Ref AWS::Region, RedisPort]Conditions
条件
Use to conditionally create resources based on parameters.
Conditionsyaml
Parameters:
EnableMultiAZ:
Type: String
Default: false
AllowedValues:
- true
- false
EnableEncryption:
Type: String
Default: true
AllowedValues:
- true
- false
Environment:
Type: String
Default: development
AllowedValues:
- development
- staging
- production
Conditions:
IsMultiAZ: !Equals [!Ref EnableMultiAZ, true]
IsEncrypted: !Equals [!Ref EnableEncryption, true]
IsProduction: !Equals [!Ref Environment, production]
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: !If [IsMultiAZ, 2, 1]
Engine: redis
AutomaticFailoverEnabled: !If [IsMultiAZ, true, false]
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup使用根据参数有条件地创建资源。
Conditionsyaml
Parameters:
EnableMultiAZ:
Type: String
Default: false
AllowedValues:
- true
- false
EnableEncryption:
Type: String
Default: true
AllowedValues:
- true
- false
Environment:
Type: String
Default: development
AllowedValues:
- development
- staging
- production
Conditions:
IsMultiAZ: !Equals [!Ref EnableMultiAZ, true]
IsEncrypted: !Equals [!Ref EnableEncryption, true]
IsProduction: !Equals [!Ref Environment, production]
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: !Ref CacheNodeType
NumCacheNodes: !If [IsMultiAZ, 2, 1]
Engine: redis
AutomaticFailoverEnabled: !If [IsMultiAZ, true, false]
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupCondition Functions
条件函数
yaml
Conditions:
IsDev: !Equals [!Ref Environment, development]
IsStaging: !Equals [!Ref Environment, staging]
IsProduction: !Equals [!Ref Environment, production]
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
# Production gets larger instances
CacheNodeType: !If [IsProduction, cache.r5.large, cache.t3.micro]
# Production gets multi-AZ
NumCacheNodes: !If [IsProduction, 3, 1]
AutomaticFailoverEnabled: !If [IsProduction, true, false]yaml
Conditions:
IsDev: !Equals [!Ref Environment, development]
IsStaging: !Equals [!Ref Environment, staging]
IsProduction: !Equals [!Ref Environment, production]
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
# 生产环境使用更大的实例
CacheNodeType: !If [IsProduction, cache.r5.large, cache.t3.micro]
# 生产环境使用多AZ
NumCacheNodes: !If [IsProduction, 3, 1]
AutomaticFailoverEnabled: !If [IsProduction, true, false]Transform
转换
Use for macros like AWS::Serverless for SAM templates.
Transformyaml
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Serverless ElastiCache application template
Globals:
Function:
Timeout: 30
Runtime: python3.11
Resources:
CacheFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
CodeUri: function/
Policies:
- ElastiCacheFullAccessPolicy:
CacheClusterId: !Ref CacheCluster
Environment:
Variables:
CACHE_ENDPOINT: !GetAtt CacheCluster.RedisEndpoint.Address
CACHE_PORT: !GetAtt CacheCluster.RedisEndpoint.Port使用处理宏,例如用于SAM模板的AWS::Serverless。
Transformyaml
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Serverless ElastiCache application template
Globals:
Function:
Timeout: 30
Runtime: python3.11
Resources:
CacheFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
CodeUri: function/
Policies:
- ElastiCacheFullAccessPolicy:
CacheClusterId: !Ref CacheCluster
Environment:
Variables:
CACHE_ENDPOINT: !GetAtt CacheCluster.RedisEndpoint.Address
CACHE_PORT: !GetAtt CacheCluster.RedisEndpoint.PortOutputs and Cross-Stack References
输出和跨栈引用
Basic Outputs
基础输出
yaml
Outputs:
CacheClusterId:
Description: Cache Cluster ID
Value: !Ref CacheCluster
CacheClusterEndpoint:
Description: Cache cluster endpoint address
Value: !GetAtt CacheCluster.RedisEndpoint.Address
CacheClusterPort:
Description: Cache cluster port
Value: !GetAtt CacheCluster.RedisEndpoint.Port
CacheClusterArn:
Description: Cache Cluster ARN
Value: !GetAtt CacheCluster.Arn
CacheNodeType:
Description: Cache Node Type
Value: !Ref CacheNodeTypeyaml
Outputs:
CacheClusterId:
Description: Cache Cluster ID
Value: !Ref CacheCluster
CacheClusterEndpoint:
Description: Cache cluster endpoint address
Value: !GetAtt CacheCluster.RedisEndpoint.Address
CacheClusterPort:
Description: Cache cluster port
Value: !GetAtt CacheCluster.RedisEndpoint.Port
CacheClusterArn:
Description: Cache Cluster ARN
Value: !GetAtt CacheCluster.Arn
CacheNodeType:
Description: Cache Node Type
Value: !Ref CacheNodeTypeExporting Values for Cross-Stack References
导出值用于跨栈引用
Export values so other stacks can import them.
yaml
Outputs:
CacheClusterId:
Description: Cache Cluster ID for other stacks
Value: !Ref CacheCluster
Export:
Name: !Sub ${AWS::StackName}-CacheClusterId
CacheClusterEndpoint:
Description: Cache cluster endpoint for application stacks
Value: !GetAtt CacheCluster.RedisEndpoint.Address
Export:
Name: !Sub ${AWS::StackName}-CacheEndpoint
CacheClusterPort:
Description: Cache cluster port for application stacks
Value: !GetAtt CacheCluster.RedisEndpoint.Port
Export:
Name: !Sub ${AWS::StackName}-CachePort
ConnectionString:
Description: Full connection string for applications
Value: !Sub redis://${CacheClusterEndpoint}:${CacheClusterPort}/0
Export:
Name: !Sub ${AWS::StackName}-CacheConnectionString导出值以便其他堆栈可以导入。
yaml
Outputs:
CacheClusterId:
Description: Cache Cluster ID for other stacks
Value: !Ref CacheCluster
Export:
Name: !Sub ${AWS::StackName}-CacheClusterId
CacheClusterEndpoint:
Description: Cache cluster endpoint for application stacks
Value: !GetAtt CacheCluster.RedisEndpoint.Address
Export:
Name: !Sub ${AWS::StackName}-CacheEndpoint
CacheClusterPort:
Description: Cache cluster port for application stacks
Value: !GetAtt CacheCluster.RedisEndpoint.Port
Export:
Name: !Sub ${AWS::StackName}-CachePort
ConnectionString:
Description: Full connection string for applications
Value: !Sub redis://${CacheClusterEndpoint}:${CacheClusterPort}/0
Export:
Name: !Sub ${AWS::StackName}-CacheConnectionStringImporting Values in Another Stack
在另一个堆栈中导入值
yaml
Parameters:
CacheClusterId:
Type: AWS::ElastiCache::Cluster::Id
Description: Cache cluster ID from cache stack
CacheEndpoint:
Type: String
Description: Cache cluster endpoint address
Resources:
ApplicationConfig:
Type: AWS::SSM::Parameter
Properties:
Name: /app/cache/endpoint
Value: !Ref CacheEndpoint
Type: Stringyaml
Parameters:
CacheClusterId:
Type: AWS::ElastiCache::Cluster::Id
Description: Cache cluster ID from cache stack
CacheEndpoint:
Type: String
Description: Cache cluster endpoint address
Resources:
ApplicationConfig:
Type: AWS::SSM::Parameter
Properties:
Name: /app/cache/endpoint
Value: !Ref CacheEndpoint
Type: StringCross-Stack Reference Pattern
跨栈引用模式
Create a dedicated cache stack that exports values:
yaml
undefined创建专用的缓存堆栈来导出值:
yaml
undefinedcache-stack.yaml
cache-stack.yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Cache infrastructure stack
Parameters:
EnvironmentName:
Type: String
Default: production
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: !Sub Subnet group for ${EnvironmentName}
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis parameter group
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Cache security group
VpcId: !Ref VPCId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
ReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Redis replication for ${EnvironmentName}
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
CacheClusterId:
Value: !Ref ReplicationGroup
Export:
Name: !Sub ${EnvironmentName}-CacheClusterId
CacheEndpoint:
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Address
Export:
Name: !Sub ${EnvironmentName}-CacheEndpoint
CachePort:
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Port
Export:
Name: !Sub ${EnvironmentName}-CachePort
CacheReaderEndpoint:
Value: !GetAtt ReplicationGroup.ReaderEndPoint.Address
Export:
Name: !Sub ${EnvironmentName}-CacheReaderEndpoint
Application stack imports these values:
```yamlAWSTemplateFormatVersion: 2010-09-09
Description: Cache infrastructure stack
Parameters:
EnvironmentName:
Type: String
Default: production
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: !Sub Subnet group for ${EnvironmentName}
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis parameter group
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Cache security group
VpcId: !Ref VPCId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
ReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Redis replication for ${EnvironmentName}
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
Outputs:
CacheClusterId:
Value: !Ref ReplicationGroup
Export:
Name: !Sub ${EnvironmentName}-CacheClusterId
CacheEndpoint:
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Address
Export:
Name: !Sub ${EnvironmentName}-CacheEndpoint
CachePort:
Value: !GetAtt ReplicationGroup.PrimaryEndPoint.Port
Export:
Name: !Sub ${EnvironmentName}-CachePort
CacheReaderEndpoint:
Value: !GetAtt ReplicationGroup.ReaderEndPoint.Address
Export:
Name: !Sub ${EnvironmentName}-CacheReaderEndpoint
应用堆栈导入这些值:
```yamlapplication-stack.yaml
application-stack.yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Application stack that imports from cache stack
Parameters:
CacheStackName:
Type: String
Description: Name of the cache stack
Default: cache-stack
Resources:
ApplicationConfig:
Type: AWS::SSM::Parameter
Properties:
Name: /app/cache/endpoint
Value: !ImportValue
Fn::Sub: ${CacheStackName}-CacheEndpoint
Type: String
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.11
Handler: app.handler
Environment:
Variables:
CACHE_ENDPOINT: !ImportValue
Fn::Sub: ${CacheStackName}-CacheEndpoint
undefinedAWSTemplateFormatVersion: 2010-09-09
Description: Application stack that imports from cache stack
Parameters:
CacheStackName:
Type: String
Description: Name of the cache stack
Default: cache-stack
Resources:
ApplicationConfig:
Type: AWS::SSM::Parameter
Properties:
Name: /app/cache/endpoint
Value: !ImportValue
Fn::Sub: ${CacheStackName}-CacheEndpoint
Type: String
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.11
Handler: app.handler
Environment:
Variables:
CACHE_ENDPOINT: !ImportValue
Fn::Sub: ${CacheStackName}-CacheEndpoint
undefinedElastiCache Components
ElastiCache组件
Cache Subnet Group
缓存子网组
Required for VPC deployment. Must include at least 2 subnets in different AZs.
yaml
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-subnetVPC部署必填。必须包含至少2个不同可用区的子网。
yaml
Resources:
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup
Properties:
Description: Subnet group for ElastiCache
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-subnetCache Parameter Group
缓存参数组
Custom parameter groups for cache configuration.
yaml
Resources:
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Custom parameter group for Redis 7.x
Family: redis7.x
Parameters:
# Memory management
maxmemory-policy: allkeys-lru
maxmemory-samples: 5
# Connection settings
timeout: 300
tcp-keepalive: 300
# Slow log
slowlog-log-slower-than: 10000
slowlog-max-len: 128
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-param用于缓存配置的自定义参数组。
yaml
Resources:
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Custom parameter group for Redis 7.x
Family: redis7.x
Parameters:
# 内存管理
maxmemory-policy: allkeys-lru
maxmemory-samples: 5
# 连接设置
timeout: 300
tcp-keepalive: 300
# 慢日志
slowlog-log-slower-than: 10000
slowlog-max-len: 128
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-paramRedis Parameter Groups (Common Configurations)
Redis参数组(常见配置)
yaml
undefinedyaml
undefinedFor caching with LRU eviction
用于LRU淘汰的缓存
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis LRU cache config
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
maxmemory-samples: 5
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis LRU cache config
Family: redis7.x
Parameters:
maxmemory-policy: allkeys-lru
maxmemory-samples: 5
For session storage
用于会话存储
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis session store config
Family: redis7.x
Parameters:
maxmemory-policy: volatile-lru
timeout: 3600
tcp-keepalive: 60
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis session store config
Family: redis7.x
Parameters:
maxmemory-policy: volatile-lru
timeout: 3600
tcp-keepalive: 60
For Redis Cluster
用于Redis集群
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis Cluster config
Family: redis7.x
Parameters:
cluster-enabled: yes
timeout: 5000
undefinedCacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis Cluster config
Family: redis7.x
Parameters:
cluster-enabled: yes
timeout: 5000
undefinedMemcached Parameter Groups (Common Configurations)
Memcached参数组(常见配置)
yaml
Resources:
MemcachedParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Memcached parameter group
Family: memcached1.6
Parameters:
max_item_size: 10485760
request_max_size: 2097152
connection_idle_timeout: 600yaml
Resources:
MemcachedParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Memcached parameter group
Family: memcached1.6
Parameters:
max_item_size: 10485760
request_max_size: 2097152
connection_idle_timeout: 600Cache Cluster - Redis Standalone
缓存集群 - 独立式Redis
yaml
Resources:
RedisCacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: redis-standalone
CacheNodeType: cache.t3.medium
NumCacheNodes: 1
Engine: redis
EngineVersion: "7.0"
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
AutoMinorVersionUpgrade: true
SnapshotRetentionLimit: 0
SnapshotWindow: 05:00-06:00yaml
Resources:
RedisCacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: redis-standalone
CacheNodeType: cache.t3.medium
NumCacheNodes: 1
Engine: redis
EngineVersion: "7.0"
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
AutoMinorVersionUpgrade: true
SnapshotRetentionLimit: 0
SnapshotWindow: 05:00-06:00Cache Cluster - Memcached
缓存集群 - Memcached
yaml
Resources:
MemcachedCacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: memcached-cluster
CacheNodeType: cache.m5.large
NumCacheNodes: 3
Engine: memcached
EngineVersion: "1.6"
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref MemcachedParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Resources:
MemcachedCacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: memcached-cluster
CacheNodeType: cache.m5.large
NumCacheNodes: 3
Engine: memcached
EngineVersion: "1.6"
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref MemcachedParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupReplication Group - Redis with Automatic Failover
复制组 - 带自动故障转移的Redis
yaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupIdentifier: redis-replication
ReplicationGroupDescription: Redis with automatic failover
Engine: redis
EngineVersion: "7.0"
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 2
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupIdentifier: redis-replication
ReplicationGroupDescription: Redis with automatic failover
Engine: redis
EngineVersion: "7.0"
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 2
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupReplication Group - Redis Cluster Mode
复制组 - Redis集群模式
yaml
Resources:
RedisClusterReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupIdentifier: redis-cluster
ReplicationGroupDescription: Redis Cluster with data partitioning
Engine: redis
EngineVersion: "7.0"
CacheNodeType: cache.r5.xlarge
NumNodeGroups: 3
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Resources:
RedisClusterReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupIdentifier: redis-cluster
ReplicationGroupDescription: Redis Cluster with data partitioning
Engine: redis
EngineVersion: "7.0"
CacheNodeType: cache.r5.xlarge
NumNodeGroups: 3
ReplicasPerNodeGroup: 1
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupCache Security Group
缓存安全组
yaml
Resources:
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group for ElastiCache
VpcId: !Ref VPCId
GroupName: !Sub ${AWS::StackName}-cache-sg
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-sgyaml
Resources:
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group for ElastiCache
VpcId: !Ref VPCId
GroupName: !Sub ${AWS::StackName}-cache-sg
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-cache-sgGlobal Replication Group (Cross-Region)
全局复制组(跨区域)
yaml
Resources:
GlobalReplicationGroup:
Type: AWS::ElastiCache::GlobalReplicationGroup
Properties:
GlobalReplicationGroupIdSuffix: global
GlobalReplicationGroupDescription: Global Redis replication
Members:
- ReplicationGroupId: !Ref PrimaryReplicationGroup
ReplicationGroupRegion: !Ref AWS::Region
- ReplicationGroupId: !Ref SecondaryReplicationGroup
ReplicationGroupRegion: us-west-2yaml
Resources:
GlobalReplicationGroup:
Type: AWS::ElastiCache::GlobalReplicationGroup
Properties:
GlobalReplicationGroupIdSuffix: global
GlobalReplicationGroupDescription: Global Redis replication
Members:
- ReplicationGroupId: !Ref PrimaryReplicationGroup
ReplicationGroupRegion: !Ref AWS::Region
- ReplicationGroupId: !Ref SecondaryReplicationGroup
ReplicationGroupRegion: us-west-2Security and Encryption
安全与加密
Encryption at Rest and In Transit
静态加密和传输中加密
yaml
Resources:
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis with encryption
Family: redis7.x
Parameters:
# TLS configuration
tls-enabled: yes
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Encrypted cache security group
VpcId: !Ref VPCId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.r5.large
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
# Encryption settings
AtRestEncryptionEnabled: true
TransitEncryptionEnabled: true
AuthToken: !Ref CacheAuthTokenyaml
Resources:
CacheParameterGroup:
Type: AWS::ElastiCache::ParameterGroup
Properties:
Description: Redis with encryption
Family: redis7.x
Parameters:
# TLS配置
tls-enabled: yes
CacheSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Encrypted cache security group
VpcId: !Ref VPCId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 6379
ToPort: 6379
SourceSecurityGroupId: !Ref AppSecurityGroup
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.r5.large
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
CacheParameterGroupName: !Ref CacheParameterGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
# 加密设置
AtRestEncryptionEnabled: true
TransitEncryptionEnabled: true
AuthToken: !Ref CacheAuthTokenUsing Secrets Manager for Auth Token
使用Secrets Manager存储认证令牌
yaml
Resources:
CacheAuthTokenSecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/elasticache/auth-token
Description: ElastiCache Redis authentication token
SecretString: !Sub '{"auth-token":"${CacheAuthToken}"}'
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.r5.large
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
TransitEncryptionEnabled: true
AuthToken: !Ref CacheAuthTokenyaml
Resources:
CacheAuthTokenSecret:
Type: AWS::SecretsManager::Secret
Properties:
Name: !Sub ${AWS::StackName}/elasticache/auth-token
Description: ElastiCache Redis authentication token
SecretString: !Sub '{"auth-token":"${CacheAuthToken}"}'
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheNodeType: cache.r5.large
NumCacheNodes: 1
Engine: redis
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroup
TransitEncryptionEnabled: true
AuthToken: !Ref CacheAuthTokenHigh Availability and Scaling
高可用性与扩展
Multi-AZ with Automatic Failover
带自动故障转移的多可用区
yaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Multi-AZ Redis with failover
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 2
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Multi-AZ Redis with failover
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 2
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupMemcached Horizontal Scaling
Memcached水平扩展
yaml
Parameters:
NumCacheNodes:
Type: Number
Default: 3
MinValue: 1
MaxValue: 20
Resources:
MemcachedCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: memcached-cluster
CacheNodeType: cache.m5.xlarge
NumCacheNodes: !Ref NumCacheNodes
Engine: memcached
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Parameters:
NumCacheNodes:
Type: Number
Default: 3
MinValue: 1
MaxValue: 20
Resources:
MemcachedCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: memcached-cluster
CacheNodeType: cache.m5.xlarge
NumCacheNodes: !Ref NumCacheNodes
Engine: memcached
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupRedis Scaling - Read Replicas
Redis扩展 - 只读副本
yaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Redis with read replicas
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 3
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupyaml
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
ReplicationGroupDescription: Redis with read replicas
Engine: redis
CacheNodeType: cache.r5.large
NumNodeGroups: 1
ReplicasPerNodeGroup: 3
AutomaticFailoverEnabled: true
MultiAZEnabled: true
CacheSubnetGroupName: !Ref CacheSubnetGroup
VpcSecurityGroupIds:
- !Ref CacheSecurityGroupBest Practices
最佳实践
Use AWS-Specific Parameter Types
使用AWS特定参数类型
Always use AWS-specific parameter types for validation and easier selection.
yaml
Parameters:
CacheNodeType:
Type: AWS::ElastiCache::CacheCluster::CacheNodeType
Description: ElastiCache node type
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup::Name
Description: Cache subnet group
VpcSecurityGroup:
Type: AWS::EC2::SecurityGroup::Id
Description: Security group for cache始终使用AWS特定参数类型进行验证并在控制台中更易于选择。
yaml
Parameters:
CacheNodeType:
Type: AWS::ElastiCache::CacheCluster::CacheNodeType
Description: ElastiCache node type
CacheSubnetGroup:
Type: AWS::ElastiCache::SubnetGroup::Name
Description: Cache subnet group
VpcSecurityGroup:
Type: AWS::EC2::SecurityGroup::Id
Description: Security group for cacheEnable Encryption for Production
为生产环境启用加密
yaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
# Encryption at rest
AtRestEncryptionEnabled: true
# Encryption in transit
TransitEncryptionEnabled: true
# Authentication
AuthToken: !Ref CacheAuthTokenyaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
# 静态加密
AtRestEncryptionEnabled: true
# 传输中加密
TransitEncryptionEnabled: true
# 认证
AuthToken: !Ref CacheAuthTokenUse Multi-AZ for Production
为生产环境使用多可用区
yaml
Conditions:
IsProduction: !Equals [!Ref Environment, production]
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
AutomaticFailoverEnabled: !If [IsProduction, true, false]
MultiAZEnabled: !If [IsProduction, true, false]
ReplicasPerNodeGroup: !If [IsProduction, 2, 1]yaml
Conditions:
IsProduction: !Equals [!Ref Environment, production]
Resources:
RedisReplicationGroup:
Type: AWS::ElastiCache::ReplicationGroup
Properties:
AutomaticFailoverEnabled: !If [IsProduction, true, false]
MultiAZEnabled: !If [IsProduction, true, false]
ReplicasPerNodeGroup: !If [IsProduction, 2, 1]Use Proper Naming Conventions
使用适当的命名约定
yaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
Tags:
- Key: Name
Value: !Sub ${Environment}-${Application}-redis
- Key: Environment
Value: !Ref Environment
- Key: Application
Value: !Ref ApplicationName
- Key: ManagedBy
Value: CloudFormationyaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
Tags:
- Key: Name
Value: !Sub ${Environment}-${Application}-redis
- Key: Environment
Value: !Ref Environment
- Key: Application
Value: !Ref ApplicationName
- Key: ManagedBy
Value: CloudFormationSeparate Cache and Application Stacks
分离缓存和应用堆栈
yaml
undefinedyaml
undefinedcache-stack.yaml - Rarely changes
cache-stack.yaml - 很少变更
AWSTemplateFormatVersion: 2010-09-09
Description: Cache infrastructure (VPC, subnets, ElastiCache)
Resources:
CacheSubnetGroup: AWS::ElastiCache::SubnetGroup
CacheParameterGroup: AWS::ElastiCache::ParameterGroup
CacheSecurityGroup: AWS::EC2::SecurityGroup
CacheCluster: AWS::ElastiCache::Cluster
AWSTemplateFormatVersion: 2010-09-09
Description: Cache infrastructure (VPC, subnets, ElastiCache)
Resources:
CacheSubnetGroup: AWS::ElastiCache::SubnetGroup
CacheParameterGroup: AWS::ElastiCache::ParameterGroup
CacheSecurityGroup: AWS::EC2::SecurityGroup
CacheCluster: AWS::ElastiCache::Cluster
application-stack.yaml - Changes frequently
application-stack.yaml - 频繁变更
AWSTemplateFormatVersion: 2010-09-09
Description: Application resources
Parameters:
CacheStackName:
Type: String
Resources:
ApplicationConfig: AWS::SSM::Parameter
undefinedAWSTemplateFormatVersion: 2010-09-09
Description: Application resources
Parameters:
CacheStackName:
Type: String
Resources:
ApplicationConfig: AWS::SSM::Parameter
undefinedUse Pseudo Parameters
使用伪参数
Use pseudo parameters for region-agnostic templates.
yaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: !Sub ${AWS::StackName}-${AWS::Region}
Tags:
- Key: Region
Value: !Ref AWS::Region
- Key: AccountId
Value: !Ref AWS::AccountId使用伪参数创建与区域无关的模板。
yaml
Resources:
CacheCluster:
Type: AWS::ElastiCache::Cluster
Properties:
CacheClusterIdentifier: !Sub ${AWS::StackName}-${AWS::Region}
Tags:
- Key: Region
Value: !Ref AWS::Region
- Key: AccountId
Value: !Ref AWS::AccountIdValidate Before Deployment
部署前验证
bash
undefinedbash
undefinedValidate template
验证模板
aws cloudformation validate-template --template-body file://template.yaml
aws cloudformation validate-template --template-body file://template.yaml
Use cfn-lint for advanced validation
使用cfn-lint进行高级验证
pip install cfn-lint
cfn-lint template.yaml
pip install cfn-lint
cfn-lint template.yaml
Check for AWS-specific issues
检查特定AWS问题
cfn-lint template.yaml --region us-east-1
undefinedcfn-lint template.yaml --region us-east-1
undefinedStack Policies
堆栈策略
Stack policies protect critical resources from unintended updates during stack operations.
yaml
{
"Statement": [
{
"Effect": "Allow",
"Action": "Update:*",
"Principal": "*",
"Resource": "*"
},
{
"Effect": "Deny",
"Action": [
"Update:Replace",
"Update:Delete"
],
"Principal": "*",
"Resource": "LogicalResourceId/CacheCluster"
},
{
"Effect": "Deny",
"Action": [
"Update:Replace",
"Update:Delete"
],
"Principal": "*",
"Resource": "LogicalResourceId/ReplicationGroup"
}
]
}堆栈策略可保护关键资源在堆栈操作期间免受意外更新。
yaml
{
"Statement": [
{
"Effect": "Allow",
"Action": "Update:*",
"Principal": "*",
"Resource": "*"
},
{
"Effect": "Deny",
"Action": [
"Update:Replace",
"Update:Delete"
],
"Principal": "*",
"Resource": "LogicalResourceId/CacheCluster"
},
{
"Effect": "Deny",
"Action": [
"Update:Replace",
"Update:Delete"
],
"Principal": "*",
"Resource": "LogicalResourceId/ReplicationGroup"
}
]
}Drift Detection
漂移检测
Drift detection identifies when the actual infrastructure configuration differs from the CloudFormation template.
漂移检测可识别实际基础设施配置与CloudFormation模板之间的差异。
Detecting Drift
检测漂移
bash
undefinedbash
undefinedDetect drift on entire stack
检测整个堆栈的漂移
aws cloudformation detect-stack-drift
--stack-name production-elasticache
--stack-name production-elasticache
aws cloudformation detect-stack-drift
--stack-name production-elasticache
--stack-name production-elasticache
Detect drift on specific resources
检测特定资源的漂移
aws cloudformation detect-stack-drift
--stack-name production-elasticache
--logical-resource-ids CacheCluster,CacheParameterGroup
--stack-name production-elasticache
--logical-resource-ids CacheCluster,CacheParameterGroup
aws cloudformation detect-stack-drift
--stack-name production-elasticache
--logical-resource-ids CacheCluster,CacheParameterGroup
--stack-name production-elasticache
--logical-resource-ids CacheCluster,CacheParameterGroup
Get drift detection status
获取漂移检测状态
aws cloudformation describe-stack-drift-detection-status
--stack-drift-detection-id <detection-id>
--stack-drift-detection-id <detection-id>
undefinedaws cloudformation describe-stack-drift-detection-status
--stack-drift-detection-id <detection-id>
--stack-drift-detection-id <detection-id>
undefinedDrift Detection Response
漂移检测响应
json
{
"StackResourceDrifts": [
{
"LogicalResourceId": "CacheCluster",
"PhysicalResourceId": "production-cache-cluster",
"ResourceType": "AWS::ElastiCache::Cluster",
"StackId": "arn:aws:cloudformation:us-east-1:123456789:stack/production-elasticache/...",
"DriftStatus": "MODIFIED",
"PropertyDifferences": [
{
"PropertyPath": "NumCacheNodes",
"ExpectedValue": "3",
"ActualValue": "2"
}
]
}
]
}json
{
"StackResourceDrifts": [
{
"LogicalResourceId": "CacheCluster",
"PhysicalResourceId": "production-cache-cluster",
"ResourceType": "AWS::ElastiCache::Cluster",
"StackId": "arn:aws:cloudformation:us-east-1:123456789:stack/production-elasticache/...",
"DriftStatus": "MODIFIED",
"PropertyDifferences": [
{
"PropertyPath": "NumCacheNodes",
"ExpectedValue": "3",
"ActualValue": "2"
}
]
}
]
}Related Resources
相关资源
- For advanced patterns: See EXAMPLES.md
- For reference: See REFERENCE.md
- AWS CloudFormation User Guide: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/
- ElastiCache Documentation: https://docs.aws.amazon.com/AmazonElastiCache/latest/redsug/
- Redis Documentation: https://redis.io/documentation
- Memcached Documentation: https://memcached.org/documentation
- 高级模式:参见EXAMPLES.md
- 参考文档:参见REFERENCE.md
- AWS CloudFormation用户指南:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/
- ElastiCache文档:https://docs.aws.amazon.com/AmazonElastiCache/latest/redsug/
- Redis文档:https://redis.io/documentation
- Memcached文档:https://memcached.org/documentation