---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'ElastiCache Redis'
Metadata:
  'AWS::CloudFormation::Interface':
    ParameterGroups:
    - Label:
        default: 'Parent Stacks'
      Parameters:
      - ParentVPCStack
    - Label:
        default: 'ElastiCache Parameters'
      Parameters:
      - EngineVersion
      - CacheNodeType
Parameters:
  ParentVPCStack:
    Description: 'Stack name of parent VPC (created by eksctl command).'
    Type: String
  EngineVersion:
    Description: 'Redis version'
    Type: String
    Default: '5.0.4'
    AllowedValues:
    - '5.0.4'
    - '5.0.0'
    - '4.0.10'
  CacheNodeType:
    Description: 'The compute and memory capacity of the nodes in the node group (shard).'
    Type: 'String'
    Default: 'cache.t2.micro'
Mappings:
  EngineVersionMap:
    '4.0.10':
      CacheParameterGroupFamily: 'redis4.0'
    '5.0.0':
      CacheParameterGroupFamily: 'redis5.0'
    '5.0.4':
      CacheParameterGroupFamily: 'redis5.0'
Resources:
  CacheParameterGroup:
    Type: 'AWS::ElastiCache::ParameterGroup'
    Properties:
      CacheParameterGroupFamily: !FindInMap [EngineVersionMap, !Ref EngineVersion, CacheParameterGroupFamily]
      Description: !Ref 'AWS::StackName'
      Properties:
        'cluster-enabled': 'yes'
        'maxmemory-policy': 'allkeys-lru'
  CacheSubnetGroupName:
    Type: 'AWS::ElastiCache::SubnetGroup'
    Properties:
      Description: !Ref 'AWS::StackName'
      SubnetIds: !Split
      - ','
      - 'Fn::ImportValue': !Sub '${ParentVPCStack}::SubnetsPrivate'

  RedisCluster:
    Type: 'AWS::ElastiCache::ReplicationGroup'
    Properties:
      AtRestEncryptionEnabled: false
      AutomaticFailoverEnabled: true
      AutoMinorVersionUpgrade: true
      CacheNodeType: !Ref CacheNodeType
      CacheParameterGroupName: !Ref CacheParameterGroup
      CacheSubnetGroupName: !Ref CacheSubnetGroupName
      Engine: redis
      EngineVersion: !Ref EngineVersion
      NumCacheClusters: 3
      Port: 6379
      PreferredMaintenanceWindow: 'sun:23:00-mon:01:30'
      ReplicationGroupDescription: 'ElastiCache Redis'
      ReplicationGroupId: !Sub '${AWS::StackName}'
      SecurityGroupIds:
      - 'Fn::ImportValue': !Sub '${ParentVPCStack}::SharedNodeSecurityGroup'

Outputs:
  StackName:
    Description: 'Stack name'
    Value: !Sub '${AWS::StackName}'
  ClusterName:
    Description: 'The name of the cluster'
    Value: !Sub '${AWS::StackName}'
    Export:
      Name: !Sub '${AWS::StackName}::ClusterName'
  RedisEndPointAddress:
    Description: 'The DNS address of the primary read-write cache node.'
    Value: !GetAtt 'RedisCluster.ConfigurationEndPoint.Address'
    Export:
      Name: !Sub '${AWS::StackName}::ConfigurationEndPointAddress'
  RedisEndPointPort:
    Description: 'The port that the primary read-write cache engine is listening on.'
    Value: !GetAtt 'RedisCluster.ConfigurationEndPoint.Port'
    Export:
      Name: !Sub '${AWS::StackName}::ConfigurationEndPointPort'
