From bfbf36384749c683fefaf5f6bbe152801ac9ad4d Mon Sep 17 00:00:00 2001 From: Frank <639906+syphernl@users.noreply.github.com> Date: Tue, 11 Jun 2024 21:29:30 +0200 Subject: [PATCH] feat: add support for redis serverless (#235) * feat: add support for redis serverless * update docs * fix outputs * update docs * improve checks * update docs * make dns and outputs work with serverless * make address work * fix description and empty cache_usage_limits entries * prevent empty cache_usage_limits block * rework serverless_cache_usage_limits * update docs * Update main.tf Co-authored-by: Benjamin Smith * Update main.tf Co-authored-by: Benjamin Smith --------- Co-authored-by: Benjamin Smith --- README.md | 25 +- README.yaml | 58 ++-- docs/terraform.md | 16 +- examples/serverless/context.tf | 279 ++++++++++++++++++ examples/serverless/fixtures.us-east-2.tfvars | 29 ++ examples/serverless/main.tf | 63 ++++ examples/serverless/outputs.tf | 44 +++ examples/serverless/variables.tf | 36 +++ examples/serverless/versions.tf | 10 + main.tf | 81 ++++- outputs.tf | 16 +- test/Makefile | 7 +- variables.tf | 31 ++ versions.tf | 2 +- 14 files changed, 642 insertions(+), 55 deletions(-) create mode 100644 examples/serverless/context.tf create mode 100644 examples/serverless/fixtures.us-east-2.tfvars create mode 100644 examples/serverless/main.tf create mode 100644 examples/serverless/outputs.tf create mode 100644 examples/serverless/variables.tf create mode 100644 examples/serverless/versions.tf diff --git a/README.md b/README.md index e5b8c9d1..f81a6601 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ --> -Terraform module to provision an [`ElastiCache`](https://aws.amazon.com/elasticache/) Redis Cluster +Terraform module to provision an [`ElastiCache`](https://aws.amazon.com/elasticache/) Redis Cluster or Serverless instance. > [!TIP] @@ -55,8 +55,8 @@ which is `true` by default. With this enabled, one does not simply `redis-cli` i Amazon provides [good documentation on how to connect with it enabled](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/in-transit-encryption.html#connect-tls). If this is not desired behavior, set `transit_encryption_enabled=false`. -This module creates, by default, a new security group for the Elasticache Redis Cluster. When a configuration -change (for example, a different security group name) cannot be applied to the security group, Terraform will +This module creates, by default, a new security group for the Elasticache Redis Cluster / Serverless Instance. +When a configuration change (for example, a different security group name) cannot be applied to the security group, Terraform will replace that security group with a new one with the new configuration. In order to allow Terraform to fully manage the security group, you should not place any other resources in (or associate any other resources with) the security group this module creates. Also, in order to keep things from breaking when this module replaces the security group, you should @@ -68,7 +68,7 @@ and pass the security group ID in via `associated_security_group_ids`. **Note about `zone_id`**: Previously, `zone_id` was a string. This caused problems (see [#82](https://github.com/cloudposse/terraform-aws-elasticache-redis/issues/82)). Now `zone_id` should be supplied as a `list(string)`, either empty or with exactly 1 zone ID in order to avoid the problem. -For a complete example, see [examples/complete](examples/complete). +For a complete example, see [examples/complete](examples/complete) or [examples/serverless](examples/serverless). For automated tests of the complete example using [bats](https://github.com/bats-core/bats-core) and [Terratest](https://github.com/gruntwork-io/terratest) (which tests and deploys the example on AWS), see [test](test). @@ -153,7 +153,7 @@ module "redis" { ## Examples -Review the [complete example](examples/complete) to see how to use this module. +Review the [complete example](examples/complete) or [serverless example](examples/serverless) to see how to use this module. @@ -176,13 +176,13 @@ Available targets: | Name | Version | |------|---------| | [terraform](#requirement\_terraform) | >= 1.3 | -| [aws](#requirement\_aws) | >= 5.27.0 | +| [aws](#requirement\_aws) | >= 5.32 | ## Providers | Name | Version | |------|---------| -| [aws](#provider\_aws) | >= 5.27.0 | +| [aws](#provider\_aws) | >= 5.32 | ## Modules @@ -200,6 +200,7 @@ Available targets: | [aws_cloudwatch_metric_alarm.cache_memory](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource | | [aws_elasticache_parameter_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_parameter_group) | resource | | [aws_elasticache_replication_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_replication_group) | resource | +| [aws_elasticache_serverless_cache.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_serverless_cache) | resource | | [aws_elasticache_subnet_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_subnet_group) | resource | ## Inputs @@ -273,6 +274,11 @@ Available targets: | [security\_group\_delete\_timeout](#input\_security\_group\_delete\_timeout) | How long to retry on `DependencyViolation` errors during security group deletion. | `string` | `"15m"` | no | | [security\_group\_description](#input\_security\_group\_description) | The description to assign to the created Security Group.
Warning: Changing the description causes the security group to be replaced.
Set this to `null` to maintain parity with releases <= `0.34.0`. | `string` | `"Security group for Elasticache Redis"` | no | | [security\_group\_name](#input\_security\_group\_name) | The name to assign to the security group. Must be unique within the VPC.
If not provided, will be derived from the `null-label.context` passed in.
If `create_before_destroy` is true, will be used as a name prefix. | `list(string)` | `[]` | no | +| [serverless\_cache\_usage\_limits](#input\_serverless\_cache\_usage\_limits) | The usage limits for the serverless cache | `map(any)` | `{}` | no | +| [serverless\_enabled](#input\_serverless\_enabled) | Flag to enable/disable creation of a serverless redis cluster | `bool` | `false` | no | +| [serverless\_major\_engine\_version](#input\_serverless\_major\_engine\_version) | The major version of the engine to use for the serverless cluster | `string` | `"7"` | no | +| [serverless\_snapshot\_time](#input\_serverless\_snapshot\_time) | The daily time that snapshots will be created from the serverless cache. | `string` | `"06:00"` | no | +| [serverless\_user\_group\_id](#input\_serverless\_user\_group\_id) | User Group ID to associate with the replication group | `string` | `null` | no | | [snapshot\_arns](#input\_snapshot\_arns) | A single-element string list containing an Amazon Resource Name (ARN) of a Redis RDB snapshot file stored in Amazon S3. Example: arn:aws:s3:::my\_bucket/snapshot1.rdb | `list(string)` | `[]` | no | | [snapshot\_name](#input\_snapshot\_name) | The name of a snapshot from which to restore data into the new node group. Changing the snapshot\_name forces a new resource. | `string` | `null` | no | | [snapshot\_retention\_limit](#input\_snapshot\_retention\_limit) | The number of days for which ElastiCache will retain automatic cache cluster snapshots before deleting them. | `number` | `0` | no | @@ -294,15 +300,16 @@ Available targets: |------|-------------| | [arn](#output\_arn) | Elasticache Replication Group ARN | | [cluster\_enabled](#output\_cluster\_enabled) | Indicates if cluster mode is enabled | -| [endpoint](#output\_endpoint) | Redis primary or configuration endpoint, whichever is appropriate for the given cluster mode | +| [endpoint](#output\_endpoint) | Redis primary, configuration or serverless endpoint , whichever is appropriate for the given configuration | | [engine\_version\_actual](#output\_engine\_version\_actual) | The running version of the cache engine | | [host](#output\_host) | Redis hostname | | [id](#output\_id) | Redis cluster ID | | [member\_clusters](#output\_member\_clusters) | Redis cluster members | | [port](#output\_port) | Redis port | -| [reader\_endpoint\_address](#output\_reader\_endpoint\_address) | The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled. | +| [reader\_endpoint\_address](#output\_reader\_endpoint\_address) | The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled or serverless is being used. | | [security\_group\_id](#output\_security\_group\_id) | The ID of the created security group | | [security\_group\_name](#output\_security\_group\_name) | The name of the created security group | +| [serverless\_enabled](#output\_serverless\_enabled) | Indicates if serverless mode is enabled | diff --git a/README.yaml b/README.yaml index 0a3b40d0..55950253 100644 --- a/README.yaml +++ b/README.yaml @@ -8,16 +8,16 @@ name: terraform-aws-elasticache-redis # Tags of this project tags: - - aws - - cache - - elasticache - - elasticache-redis - - terraform - - terraform-module +- aws +- cache +- elasticache +- elasticache-redis +- terraform +- terraform-module # Categories of this project categories: - - terraform-modules/databases +- terraform-modules/databases # Logo for this project #logo: docs/logo.png @@ -30,29 +30,29 @@ github_repo: cloudposse/terraform-aws-elasticache-redis # Badges to display badges: - - name: Latest Release - image: https://img.shields.io/github/release/cloudposse/terraform-aws-elasticache-redis.svg?style=for-the-badge - url: https://github.com/cloudposse/terraform-aws-elasticache-redis/releases/latest - - name: Last Updated - image: https://img.shields.io/github/last-commit/cloudposse/terraform-aws-elasticache-redis.svg?style=for-the-badge - url: https://github.com/cloudposse/terraform-aws-elasticache-redis/commits - - name: Slack Community - image: https://slack.cloudposse.com/for-the-badge.svg - url: https://slack.cloudposse.com +- name: Latest Release + image: https://img.shields.io/github/release/cloudposse/terraform-aws-elasticache-redis.svg?style=for-the-badge + url: https://github.com/cloudposse/terraform-aws-elasticache-redis/releases/latest +- name: Last Updated + image: https://img.shields.io/github/last-commit/cloudposse/terraform-aws-elasticache-redis.svg?style=for-the-badge + url: https://github.com/cloudposse/terraform-aws-elasticache-redis/commits +- name: Slack Community + image: https://slack.cloudposse.com/for-the-badge.svg + url: https://slack.cloudposse.com # List any related terraform modules that this module may be used with or that this module depends on. related: - - name: "terraform-aws-security-group" - description: "Terraform module to provision an AWS Security Group." - url: "https://github.com/cloudposse/terraform-aws-security-group" - - name: "terraform-null-label" - description: "Terraform module designed to generate consistent names and tags for resources. Use terraform-null-label to implement a strict naming convention." - url: "https://github.com/cloudposse/terraform-null-label" +- name: "terraform-aws-security-group" + description: "Terraform module to provision an AWS Security Group." + url: "https://github.com/cloudposse/terraform-aws-security-group" +- name: "terraform-null-label" + description: "Terraform module designed to generate consistent names and tags for resources. Use terraform-null-label to implement a strict naming convention." + url: "https://github.com/cloudposse/terraform-null-label" # Short description of this project description: |- - Terraform module to provision an [`ElastiCache`](https://aws.amazon.com/elasticache/) Redis Cluster + Terraform module to provision an [`ElastiCache`](https://aws.amazon.com/elasticache/) Redis Cluster or Serverless instance. # How to use this project # Note: use absolute rather than relative URLs because Hashicorp will copy the README to @@ -67,8 +67,8 @@ usage: |- Amazon provides [good documentation on how to connect with it enabled](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/in-transit-encryption.html#connect-tls). If this is not desired behavior, set `transit_encryption_enabled=false`. - This module creates, by default, a new security group for the Elasticache Redis Cluster. When a configuration - change (for example, a different security group name) cannot be applied to the security group, Terraform will + This module creates, by default, a new security group for the Elasticache Redis Cluster / Serverless Instance. + When a configuration change (for example, a different security group name) cannot be applied to the security group, Terraform will replace that security group with a new one with the new configuration. In order to allow Terraform to fully manage the security group, you should not place any other resources in (or associate any other resources with) the security group this module creates. Also, in order to keep things from breaking when this module replaces the security group, you should @@ -80,7 +80,7 @@ usage: |- **Note about `zone_id`**: Previously, `zone_id` was a string. This caused problems (see [#82](https://github.com/cloudposse/terraform-aws-elasticache-redis/issues/82)). Now `zone_id` should be supplied as a `list(string)`, either empty or with exactly 1 zone ID in order to avoid the problem. - For a complete example, see [examples/complete](examples/complete). + For a complete example, see [examples/complete](examples/complete) or [examples/serverless](examples/serverless). For automated tests of the complete example using [bats](https://github.com/bats-core/bats-core) and [Terratest](https://github.com/gruntwork-io/terratest) (which tests and deploys the example on AWS), see [test](test). @@ -154,11 +154,11 @@ usage: |- ``` examples: |- - Review the [complete example](examples/complete) to see how to use this module. + Review the [complete example](examples/complete) or [serverless example](examples/serverless) to see how to use this module. include: - - "docs/targets.md" - - "docs/terraform.md" +- "docs/targets.md" +- "docs/terraform.md" # Contributors to this project contributors: [] diff --git a/docs/terraform.md b/docs/terraform.md index 452e4fed..202a868c 100644 --- a/docs/terraform.md +++ b/docs/terraform.md @@ -4,13 +4,13 @@ | Name | Version | |------|---------| | [terraform](#requirement\_terraform) | >= 1.3 | -| [aws](#requirement\_aws) | >= 4.18 | +| [aws](#requirement\_aws) | >= 5.32 | ## Providers | Name | Version | |------|---------| -| [aws](#provider\_aws) | >= 4.18 | +| [aws](#provider\_aws) | >= 5.32 | ## Modules @@ -28,6 +28,7 @@ | [aws_cloudwatch_metric_alarm.cache_memory](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_metric_alarm) | resource | | [aws_elasticache_parameter_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_parameter_group) | resource | | [aws_elasticache_replication_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_replication_group) | resource | +| [aws_elasticache_serverless_cache.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_serverless_cache) | resource | | [aws_elasticache_subnet_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/elasticache_subnet_group) | resource | ## Inputs @@ -48,6 +49,7 @@ | [at\_rest\_encryption\_enabled](#input\_at\_rest\_encryption\_enabled) | Enable encryption at rest | `bool` | `false` | no | | [attributes](#input\_attributes) | ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the `delimiter`
and treated as a single ID element. | `list(string)` | `[]` | no | | [auth\_token](#input\_auth\_token) | Auth token for password protecting redis, `transit_encryption_enabled` must be set to `true`. Password must be longer than 16 chars | `string` | `null` | no | +| [auth\_token\_update\_strategy](#input\_auth\_token\_update\_strategy) | Strategy to use when updating the auth\_token. Valid values are `SET`, `ROTATE`, and `DELETE`. Defaults to `ROTATE`. | `string` | `"ROTATE"` | no | | [auto\_minor\_version\_upgrade](#input\_auto\_minor\_version\_upgrade) | Specifies whether minor version engine upgrades will be applied automatically to the underlying Cache Cluster instances during the maintenance window. Only supported if the engine version is 6 or higher. | `bool` | `null` | no | | [automatic\_failover\_enabled](#input\_automatic\_failover\_enabled) | Automatic failover (Not available for T1/T2 instances) | `bool` | `false` | no | | [availability\_zones](#input\_availability\_zones) | Availability zone IDs | `list(string)` | `[]` | no | @@ -100,6 +102,11 @@ | [security\_group\_delete\_timeout](#input\_security\_group\_delete\_timeout) | How long to retry on `DependencyViolation` errors during security group deletion. | `string` | `"15m"` | no | | [security\_group\_description](#input\_security\_group\_description) | The description to assign to the created Security Group.
Warning: Changing the description causes the security group to be replaced.
Set this to `null` to maintain parity with releases <= `0.34.0`. | `string` | `"Security group for Elasticache Redis"` | no | | [security\_group\_name](#input\_security\_group\_name) | The name to assign to the security group. Must be unique within the VPC.
If not provided, will be derived from the `null-label.context` passed in.
If `create_before_destroy` is true, will be used as a name prefix. | `list(string)` | `[]` | no | +| [serverless\_cache\_usage\_limits](#input\_serverless\_cache\_usage\_limits) | The usage limits for the serverless cache | `map(any)` | `{}` | no | +| [serverless\_enabled](#input\_serverless\_enabled) | Flag to enable/disable creation of a serverless redis cluster | `bool` | `false` | no | +| [serverless\_major\_engine\_version](#input\_serverless\_major\_engine\_version) | The major version of the engine to use for the serverless cluster | `string` | `"7"` | no | +| [serverless\_snapshot\_time](#input\_serverless\_snapshot\_time) | The daily time that snapshots will be created from the serverless cache. | `string` | `"06:00"` | no | +| [serverless\_user\_group\_id](#input\_serverless\_user\_group\_id) | User Group ID to associate with the replication group | `string` | `null` | no | | [snapshot\_arns](#input\_snapshot\_arns) | A single-element string list containing an Amazon Resource Name (ARN) of a Redis RDB snapshot file stored in Amazon S3. Example: arn:aws:s3:::my\_bucket/snapshot1.rdb | `list(string)` | `[]` | no | | [snapshot\_name](#input\_snapshot\_name) | The name of a snapshot from which to restore data into the new node group. Changing the snapshot\_name forces a new resource. | `string` | `null` | no | | [snapshot\_retention\_limit](#input\_snapshot\_retention\_limit) | The number of days for which ElastiCache will retain automatic cache cluster snapshots before deleting them. | `number` | `0` | no | @@ -121,13 +128,14 @@ |------|-------------| | [arn](#output\_arn) | Elasticache Replication Group ARN | | [cluster\_enabled](#output\_cluster\_enabled) | Indicates if cluster mode is enabled | -| [endpoint](#output\_endpoint) | Redis primary or configuration endpoint, whichever is appropriate for the given cluster mode | +| [endpoint](#output\_endpoint) | Redis primary, configuration or serverless endpoint , whichever is appropriate for the given configuration | | [engine\_version\_actual](#output\_engine\_version\_actual) | The running version of the cache engine | | [host](#output\_host) | Redis hostname | | [id](#output\_id) | Redis cluster ID | | [member\_clusters](#output\_member\_clusters) | Redis cluster members | | [port](#output\_port) | Redis port | -| [reader\_endpoint\_address](#output\_reader\_endpoint\_address) | The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled. | +| [reader\_endpoint\_address](#output\_reader\_endpoint\_address) | The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled or serverless is being used. | | [security\_group\_id](#output\_security\_group\_id) | The ID of the created security group | | [security\_group\_name](#output\_security\_group\_name) | The name of the created security group | +| [serverless\_enabled](#output\_serverless\_enabled) | Indicates if serverless mode is enabled | diff --git a/examples/serverless/context.tf b/examples/serverless/context.tf new file mode 100644 index 00000000..5e0ef885 --- /dev/null +++ b/examples/serverless/context.tf @@ -0,0 +1,279 @@ +# +# ONLY EDIT THIS FILE IN github.com/cloudposse/terraform-null-label +# All other instances of this file should be a copy of that one +# +# +# Copy this file from https://github.com/cloudposse/terraform-null-label/blob/master/exports/context.tf +# and then place it in your Terraform module to automatically get +# Cloud Posse's standard configuration inputs suitable for passing +# to Cloud Posse modules. +# +# curl -sL https://raw.githubusercontent.com/cloudposse/terraform-null-label/master/exports/context.tf -o context.tf +# +# Modules should access the whole context as `module.this.context` +# to get the input variables with nulls for defaults, +# for example `context = module.this.context`, +# and access individual variables as `module.this.`, +# with final values filled in. +# +# For example, when using defaults, `module.this.context.delimiter` +# will be null, and `module.this.delimiter` will be `-` (hyphen). +# + +module "this" { + source = "cloudposse/label/null" + version = "0.25.0" # requires Terraform >= 0.13.0 + + enabled = var.enabled + namespace = var.namespace + tenant = var.tenant + environment = var.environment + stage = var.stage + name = var.name + delimiter = var.delimiter + attributes = var.attributes + tags = var.tags + additional_tag_map = var.additional_tag_map + label_order = var.label_order + regex_replace_chars = var.regex_replace_chars + id_length_limit = var.id_length_limit + label_key_case = var.label_key_case + label_value_case = var.label_value_case + descriptor_formats = var.descriptor_formats + labels_as_tags = var.labels_as_tags + + context = var.context +} + +# Copy contents of cloudposse/terraform-null-label/variables.tf here + +variable "context" { + type = any + default = { + enabled = true + namespace = null + tenant = null + environment = null + stage = null + name = null + delimiter = null + attributes = [] + tags = {} + additional_tag_map = {} + regex_replace_chars = null + label_order = [] + id_length_limit = null + label_key_case = null + label_value_case = null + descriptor_formats = {} + # Note: we have to use [] instead of null for unset lists due to + # https://github.com/hashicorp/terraform/issues/28137 + # which was not fixed until Terraform 1.0.0, + # but we want the default to be all the labels in `label_order` + # and we want users to be able to prevent all tag generation + # by setting `labels_as_tags` to `[]`, so we need + # a different sentinel to indicate "default" + labels_as_tags = ["unset"] + } + description = <<-EOT + Single object for setting entire context at once. + See description of individual variables for details. + Leave string and numeric variables as `null` to use default value. + Individual variable settings (non-null) override settings in context object, + except for attributes, tags, and additional_tag_map, which are merged. + EOT + + validation { + condition = lookup(var.context, "label_key_case", null) == null ? true : contains(["lower", "title", "upper"], var.context["label_key_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`." + } + + validation { + condition = lookup(var.context, "label_value_case", null) == null ? true : contains(["lower", "title", "upper", "none"], var.context["label_value_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "enabled" { + type = bool + default = null + description = "Set to false to prevent the module from creating any resources" +} + +variable "namespace" { + type = string + default = null + description = "ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique" +} + +variable "tenant" { + type = string + default = null + description = "ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for" +} + +variable "environment" { + type = string + default = null + description = "ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'" +} + +variable "stage" { + type = string + default = null + description = "ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'" +} + +variable "name" { + type = string + default = null + description = <<-EOT + ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'. + This is the only ID element not also included as a `tag`. + The "name" tag is set to the full `id` string. There is no tag with the value of the `name` input. + EOT +} + +variable "delimiter" { + type = string + default = null + description = <<-EOT + Delimiter to be used between ID elements. + Defaults to `-` (hyphen). Set to `""` to use no delimiter at all. + EOT +} + +variable "attributes" { + type = list(string) + default = [] + description = <<-EOT + ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`, + in the order they appear in the list. New attributes are appended to the + end of the list. The elements of the list are joined by the `delimiter` + and treated as a single ID element. + EOT +} + +variable "labels_as_tags" { + type = set(string) + default = ["default"] + description = <<-EOT + Set of labels (ID elements) to include as tags in the `tags` output. + Default is to include all labels. + Tags with empty values will not be included in the `tags` output. + Set to `[]` to suppress all generated tags. + **Notes:** + The value of the `name` tag, if included, will be the `id`, not the `name`. + Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be + changed in later chained modules. Attempts to change it will be silently ignored. + EOT +} + +variable "tags" { + type = map(string) + default = {} + description = <<-EOT + Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`). + Neither the tag keys nor the tag values will be modified by this module. + EOT +} + +variable "additional_tag_map" { + type = map(string) + default = {} + description = <<-EOT + Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`. + This is for some rare cases where resources want additional configuration of tags + and therefore take a list of maps with tag key, value, and additional configuration. + EOT +} + +variable "label_order" { + type = list(string) + default = null + description = <<-EOT + The order in which the labels (ID elements) appear in the `id`. + Defaults to ["namespace", "environment", "stage", "name", "attributes"]. + You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present. + EOT +} + +variable "regex_replace_chars" { + type = string + default = null + description = <<-EOT + Terraform regular expression (regex) string. + Characters matching the regex will be removed from the ID elements. + If not set, `"/[^a-zA-Z0-9-]/"` is used to remove all characters other than hyphens, letters and digits. + EOT +} + +variable "id_length_limit" { + type = number + default = null + description = <<-EOT + Limit `id` to this many characters (minimum 6). + Set to `0` for unlimited length. + Set to `null` for keep the existing setting, which defaults to `0`. + Does not affect `id_full`. + EOT + validation { + condition = var.id_length_limit == null ? true : var.id_length_limit >= 6 || var.id_length_limit == 0 + error_message = "The id_length_limit must be >= 6 if supplied (not null), or 0 for unlimited length." + } +} + +variable "label_key_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of the `tags` keys (label names) for tags generated by this module. + Does not affect keys of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper`. + Default value: `title`. + EOT + + validation { + condition = var.label_key_case == null ? true : contains(["lower", "title", "upper"], var.label_key_case) + error_message = "Allowed values: `lower`, `title`, `upper`." + } +} + +variable "label_value_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of ID elements (labels) as included in `id`, + set as tag values, and output by this module individually. + Does not affect values of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper` and `none` (no transformation). + Set this to `title` and set `delimiter` to `""` to yield Pascal Case IDs. + Default value: `lower`. + EOT + + validation { + condition = var.label_value_case == null ? true : contains(["lower", "title", "upper", "none"], var.label_value_case) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "descriptor_formats" { + type = any + default = {} + description = <<-EOT + Describe additional descriptors to be output in the `descriptors` output map. + Map of maps. Keys are names of descriptors. Values are maps of the form + `{ + format = string + labels = list(string) + }` + (Type is `any` so the map values can later be enhanced to provide additional options.) + `format` is a Terraform format string to be passed to the `format()` function. + `labels` is a list of labels, in order, to pass to `format()` function. + Label values will be normalized before being passed to `format()` so they will be + identical to how they appear in `id`. + Default is `{}` (`descriptors` output will be empty). + EOT +} + +#### End of copy of cloudposse/terraform-null-label/variables.tf diff --git a/examples/serverless/fixtures.us-east-2.tfvars b/examples/serverless/fixtures.us-east-2.tfvars new file mode 100644 index 00000000..ffcd7929 --- /dev/null +++ b/examples/serverless/fixtures.us-east-2.tfvars @@ -0,0 +1,29 @@ +enabled = true + +region = "us-east-2" + +availability_zones = ["us-east-2a", "us-east-2b"] + +namespace = "eg" + +stage = "test" + +name = "redis-serverless" + +serverless_enabled = true + +serverless_major_engine_version = "7" + +serverless_cache_usage_limits = { + data_storage = { + maximum = 1 + } + ecpu_per_second = { + maximum = 5000 + } +} + +at_rest_encryption_enabled = false + +zone_id = "Z3SO0TKDDQ0RGG" + diff --git a/examples/serverless/main.tf b/examples/serverless/main.tf new file mode 100644 index 00000000..df9aae51 --- /dev/null +++ b/examples/serverless/main.tf @@ -0,0 +1,63 @@ +provider "aws" { + region = var.region +} + +module "vpc" { + source = "cloudposse/vpc/aws" + version = "2.2.0" + + ipv4_primary_cidr_block = "172.16.0.0/16" + + context = module.this.context +} + +module "subnets" { + source = "cloudposse/dynamic-subnets/aws" + version = "2.4.1" + + availability_zones = var.availability_zones + vpc_id = module.vpc.vpc_id + igw_id = [module.vpc.igw_id] + ipv4_cidr_block = [module.vpc.vpc_cidr_block] + nat_gateway_enabled = false + nat_instance_enabled = false + + context = module.this.context +} + +# Create a zone in order to validate fix for https://github.com/cloudposse/terraform-aws-elasticache-redis/issues/82 +resource "aws_route53_zone" "private" { + name = format("elasticache-redis-terratest-%s.testing.cloudposse.co", try(module.this.attributes[0], "default")) + + vpc { + vpc_id = module.vpc.vpc_id + } +} + +module "cloudwatch_logs" { + source = "cloudposse/cloudwatch-logs/aws" + version = "0.6.8" + + context = module.this.context +} + +module "redis" { + source = "../../" + + serverless_enabled = var.serverless_enabled + zone_id = [aws_route53_zone.private.id] + vpc_id = module.vpc.vpc_id + allowed_security_groups = [module.vpc.vpc_default_security_group_id] + subnets = module.subnets.private_subnet_ids + serverless_major_engine_version = var.serverless_major_engine_version + at_rest_encryption_enabled = var.at_rest_encryption_enabled + serverless_cache_usage_limits = var.serverless_cache_usage_limits + + # Verify that we can safely change security groups (name changes forces new SG) + security_group_create_before_destroy = true + security_group_name = length(var.sg_name) > 0 ? [var.sg_name] : [] + + security_group_delete_timeout = "5m" + + context = module.this.context +} diff --git a/examples/serverless/outputs.tf b/examples/serverless/outputs.tf new file mode 100644 index 00000000..79a25a1c --- /dev/null +++ b/examples/serverless/outputs.tf @@ -0,0 +1,44 @@ +output "public_subnet_cidrs" { + value = module.subnets.public_subnet_cidrs + description = "Public subnet CIDRs" +} + +output "private_subnet_cidrs" { + value = module.subnets.private_subnet_cidrs + description = "Private subnet CIDRs" +} + +output "vpc_cidr" { + value = module.vpc.vpc_cidr_block + description = "VPC CIDR" +} + +output "serverless_arn" { + value = module.redis.arn + description = "Elasticache Replication Group ARN" +} + +output "cluster_security_group_id" { + value = module.redis.security_group_id + description = "Cluster Security Group ID" +} + +output "serverless_endpoint" { + value = module.redis.endpoint + description = "Redis primary endpoint" +} + +output "cluster_reader_endpoint_address" { + value = module.redis.reader_endpoint_address + description = "Redis non-cluster reader endpoint" +} + +output "serverless_host" { + value = module.redis.host + description = "Redis hostname" +} + +output "serverless_enabled" { + value = module.redis.serverless_enabled + description = "Indicates if serverless mode is enabled" +} \ No newline at end of file diff --git a/examples/serverless/variables.tf b/examples/serverless/variables.tf new file mode 100644 index 00000000..832d605d --- /dev/null +++ b/examples/serverless/variables.tf @@ -0,0 +1,36 @@ +variable "region" { + type = string + description = "AWS region" +} + +variable "availability_zones" { + type = list(string) + description = "Availability zone IDs" +} + +variable "serverless_enabled" { + type = bool + description = "Enable serverless" +} + +variable "serverless_major_engine_version" { + type = string + description = "Serverless major engine version" +} + +variable "serverless_cache_usage_limits" { + type = map(any) + description = "Serverless cache usage limits" + default = {} +} + +variable "at_rest_encryption_enabled" { + type = bool + description = "Enable encryption at rest" +} + +variable "sg_name" { + type = string + default = "" + description = "Name to give to created security group" +} \ No newline at end of file diff --git a/examples/serverless/versions.tf b/examples/serverless/versions.tf new file mode 100644 index 00000000..2731a61b --- /dev/null +++ b/examples/serverless/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.32" + } + } +} diff --git a/main.tf b/main.tf index 29585950..24a2b2b8 100644 --- a/main.tf +++ b/main.tf @@ -2,7 +2,9 @@ # Security Group Resources # locals { - enabled = module.this.enabled + enabled = module.this.enabled + create_normal_instance = local.enabled && !var.serverless_enabled + create_serverless_instance = local.enabled && var.serverless_enabled legacy_egress_rule = local.use_legacy_egress ? { key = "legacy-egress" @@ -82,7 +84,7 @@ locals { var.cluster_size ) - elasticache_member_clusters = local.enabled ? tolist(aws_elasticache_replication_group.default[0].member_clusters) : [] + elasticache_member_clusters = local.create_normal_instance ? tolist(aws_elasticache_replication_group.default[0].member_clusters) : [] # The name of the parameter group can’t include "." safe_family = replace(var.family, ".", "-") @@ -96,6 +98,25 @@ locals { "default.${var.family}" # Default parameter group name created by AWS ) ) + + arn = ( + # If cluster mode is enabled, use the ARN of the replication group + local.create_normal_instance ? join("", aws_elasticache_replication_group.default[*].arn) : + # If serverless mode is enabled, use the ARN of the serverless cache + join("", aws_elasticache_serverless_cache.default[*].arn) + ) + + endpoint_serverless = try(aws_elasticache_serverless_cache.default[0].endpoint[0].address, null) + endpoint_cluster = try(aws_elasticache_replication_group.default[0].configuration_endpoint_address, null) + endpoint_instance = try(aws_elasticache_replication_group.default[0].primary_endpoint_address, null) + # Use the serverless endpoint if serverless mode is enabled, otherwise use the cluster endpoint, otherwise use the instance endpoint + endpoint_address = coalesce(local.endpoint_serverless, local.endpoint_cluster, local.endpoint_instance) + + reader_endpoint_serverless = try(aws_elasticache_serverless_cache.default[0].reader_endpoint[0].address, null) + reader_endpoint_cluster = try(aws_elasticache_replication_group.default[0].reader_endpoint_address, null) + reader_endpoint_instance = try(aws_elasticache_replication_group.default[0].reader_endpoint_address, null) + # Use the serverless reader endpoint if serverless mode is enabled, otherwise use the cluster reader endpoint, otherwise use the instance reader endpoint + reader_endpoint_address = coalesce(local.reader_endpoint_serverless, local.reader_endpoint_cluster, local.reader_endpoint_instance) } resource "aws_elasticache_subnet_group" "default" { @@ -132,8 +153,9 @@ resource "aws_elasticache_parameter_group" "default" { } } +# Create a "normal" Elasticache instance (single node or cluster) resource "aws_elasticache_replication_group" "default" { - count = local.enabled ? 1 : 0 + count = local.create_normal_instance ? 1 : 0 auth_token = var.transit_encryption_enabled ? var.auth_token : null auth_token_update_strategy = var.auth_token_update_strategy @@ -197,11 +219,58 @@ resource "aws_elasticache_replication_group" "default" { ] } +# Create a Serverless Redis instance +resource "aws_elasticache_serverless_cache" "default" { + count = local.create_serverless_instance ? 1 : 0 + + name = var.replication_group_id == "" ? module.this.id : var.replication_group_id + engine = "redis" + + kms_key_id = var.at_rest_encryption_enabled ? var.kms_key_id : null + subnet_ids = var.subnets + security_group_ids = local.create_security_group ? concat(local.associated_security_group_ids, [module.aws_security_group.id]) : local.associated_security_group_ids + + daily_snapshot_time = var.serverless_snapshot_time + description = coalesce(var.description, module.this.id) + major_engine_version = var.serverless_major_engine_version + snapshot_retention_limit = var.snapshot_retention_limit + user_group_id = var.serverless_user_group_id + + dynamic "cache_usage_limits" { + for_each = try([var.serverless_cache_usage_limits], []) + content { + + dynamic "data_storage" { + for_each = try([cache_usage_limits.value.data_storage], []) + content { + maximum = try(data_storage.value.maximum, null) + minimum = try(data_storage.value.minimum, null) + unit = try(data_storage.value.unit, "GB") + } + } + + dynamic "ecpu_per_second" { + for_each = try([cache_usage_limits.value.ecpu_per_second], []) + content { + maximum = try(ecpu_per_second.value.maximum, null) + minimum = try(ecpu_per_second.value.minimum, null) + } + } + } + } + + tags = module.this.tags + + depends_on = [ + aws_elasticache_parameter_group.default + ] +} + # # CloudWatch Resources # resource "aws_cloudwatch_metric_alarm" "cache_cpu" { - count = local.enabled && var.cloudwatch_metric_alarms_enabled ? local.member_clusters_count : 0 + count = local.create_normal_instance && var.cloudwatch_metric_alarms_enabled ? local.member_clusters_count : 0 alarm_name = "${element(local.elasticache_member_clusters, count.index)}-cpu-utilization" alarm_description = "Redis cluster CPU utilization" comparison_operator = "GreaterThanThreshold" @@ -225,7 +294,7 @@ resource "aws_cloudwatch_metric_alarm" "cache_cpu" { } resource "aws_cloudwatch_metric_alarm" "cache_memory" { - count = local.enabled && var.cloudwatch_metric_alarms_enabled ? local.member_clusters_count : 0 + count = local.create_normal_instance && var.cloudwatch_metric_alarms_enabled ? local.member_clusters_count : 0 alarm_name = "${element(local.elasticache_member_clusters, count.index)}-freeable-memory" alarm_description = "Redis cluster freeable memory" comparison_operator = "LessThanThreshold" @@ -256,7 +325,7 @@ module "dns" { dns_name = var.dns_subdomain != "" ? var.dns_subdomain : module.this.id ttl = 60 zone_id = try(var.zone_id[0], tostring(var.zone_id), "") - records = var.cluster_mode_enabled ? [join("", compact(aws_elasticache_replication_group.default[*].configuration_endpoint_address))] : [join("", compact(aws_elasticache_replication_group.default[*].primary_endpoint_address))] + records = [local.endpoint_address] context = module.this.context } diff --git a/outputs.tf b/outputs.tf index 55b345c3..33fdd691 100644 --- a/outputs.tf +++ b/outputs.tf @@ -19,15 +19,16 @@ output "port" { } output "endpoint" { - value = var.cluster_mode_enabled ? join("", compact(aws_elasticache_replication_group.default[*].configuration_endpoint_address)) : join("", compact(aws_elasticache_replication_group.default[*].primary_endpoint_address)) - description = "Redis primary or configuration endpoint, whichever is appropriate for the given cluster mode" + value = local.endpoint_address + description = "Redis primary, configuration or serverless endpoint , whichever is appropriate for the given configuration" } output "reader_endpoint_address" { - value = join("", compact(aws_elasticache_replication_group.default[*].reader_endpoint_address)) - description = "The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled." + value = local.reader_endpoint_address + description = "The address of the endpoint for the reader node in the replication group, if the cluster mode is disabled or serverless is being used." } + output "member_clusters" { value = aws_elasticache_replication_group.default[*].member_clusters description = "Redis cluster members" @@ -39,7 +40,7 @@ output "host" { } output "arn" { - value = join("", aws_elasticache_replication_group.default[*].arn) + value = local.arn description = "Elasticache Replication Group ARN" } @@ -52,3 +53,8 @@ output "cluster_enabled" { value = join("", aws_elasticache_replication_group.default[*].cluster_enabled) description = "Indicates if cluster mode is enabled" } + +output "serverless_enabled" { + value = var.serverless_enabled + description = "Indicates if serverless mode is enabled" +} \ No newline at end of file diff --git a/test/Makefile b/test/Makefile index 17b2fe74..2b424234 100644 --- a/test/Makefile +++ b/test/Makefile @@ -30,7 +30,7 @@ clean: [ "$(TEST_HARNESS_PATH)" == "/" ] || rm -rf $(TEST_HARNESS_PATH) ## Run all tests -all: module examples/complete +all: module examples/complete examples/serverless ## Run basic sanity checks against the module itself module: export TESTS ?= installed lint get-modules module-pinning get-plugins provider-pinning validate terraform-docs input-descriptions output-descriptions @@ -41,3 +41,8 @@ module: deps examples/complete: export TESTS ?= installed lint get-modules get-plugins validate examples/complete: deps $(call RUN_TESTS, ../$@) + +## Run tests against example/serverless +examples/serverless: export TESTS ?= installed lint get-modules get-plugins validate +examples/serverless: deps + $(call RUN_TESTS, ../$@) diff --git a/variables.tf b/variables.tf index a3324891..10cc695c 100644 --- a/variables.tf +++ b/variables.tf @@ -277,3 +277,34 @@ variable "auto_minor_version_upgrade" { default = null description = "Specifies whether minor version engine upgrades will be applied automatically to the underlying Cache Cluster instances during the maintenance window. Only supported if the engine version is 6 or higher." } + +# Add boolean to create a serverless cluster +variable "serverless_enabled" { + type = bool + default = false + description = "Flag to enable/disable creation of a serverless redis cluster" +} + +variable "serverless_major_engine_version" { + type = string + default = "7" + description = "The major version of the engine to use for the serverless cluster" +} + +variable "serverless_snapshot_time" { + type = string + default = "06:00" + description = "The daily time that snapshots will be created from the serverless cache." +} + +variable "serverless_user_group_id" { + type = string + default = null + description = "User Group ID to associate with the replication group" +} + +variable "serverless_cache_usage_limits" { + type = map(any) + default = {} + description = "The usage limits for the serverless cache" +} \ No newline at end of file diff --git a/versions.tf b/versions.tf index 1c9ac7ee..2731a61b 100644 --- a/versions.tf +++ b/versions.tf @@ -4,7 +4,7 @@ terraform { required_providers { aws = { source = "hashicorp/aws" - version = ">= 5.27.0" + version = ">= 5.32" } } }