Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
274 changes: 274 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Repository Overview

This is a Terraform module template repository designed to standardize the structure for creating new Terraform modules. The template uses CloudPosse's `context` provider for consistent naming and tagging conventions.

## Key Architecture Patterns

### Context and Labeling System

Use of `context.tf` (terraform CloudPosse `null-label` module) is now deprecated in all our modules, instead CloudPosse's `context` provider should be used. We also created a default set of variables to unify resource naming:

1. Standard variables (this is an example for `snowflake-warehouse`):

```hcl
variable "name" {
description = "Name of the resource"
type = string
}

variable "name_scheme" {
description = <<EOT
Naming scheme configuration for the resource. This configuration is used to generate names using context provider:
- `properties` - list of properties to use when creating the name - is superseded by `var.context_templates`
- `delimiter` - delimited used to create the name from `properties` - is superseded by `var.context_templates`
- `context_template_name` - name of the context template used to create the name
- `replace_chars_regex` - regex to use for replacing characters in property-values created by the provider - any characters that match the regex will be removed from the name
- `extra_values` - map of extra label-value pairs, used to create a name
- `uppercase` - convert name to uppercase
EOT
type = object({
properties = optional(list(string), ["environment", "name"])
delimiter = optional(string, "_")
context_template_name = optional(string, "snowflake-warehouse")
replace_chars_regex = optional(string, "[^a-zA-Z0-9_]")
extra_values = optional(map(string))
uppercase = optional(bool, true)
})
default = {}
}

variable "context_templates" {
description = "Map of context templates used for naming conventions - this variable supersedes `naming_scheme.properties` and `naming_scheme.delimiter` configuration"
type = map(string)
default = {}
}
```

2. Resource name creation (label taken from datasource and used in resource):

```hcl
locals {
context_template = lookup(var.context_templates, var.name_scheme.context_template_name, null)
}

data "context_label" "this" {
delimiter = local.context_template == null ? var.name_scheme.delimiter : null
properties = local.context_template == null ? var.name_scheme.properties : null
template = local.context_template

replace_chars_regex = var.name_scheme.replace_chars_regex

values = merge(
var.name_scheme.extra_values,
{ name = var.name }
)
}

resource "snowflake_warehouse" "this" {
name = var.name_scheme.uppercase ? upper(data.context_label.this.rendered) : data.context_label.this.rendered
comment = var.comment
}
```

3. Sample provider configuration:

```hcl
provider "context" {
properties = {
"environment" = {}
"name" = {}
}
values = {
environment = "dev"
}
}
```

4. Sample tfvars with context templates:

```hcl
context_templates = {
snowflake-role = "{{.environment}}_{{.name}}"
snowflake-project-warehouse = "{{.environment}}_{{.project}}_{{.name}}"
snowflake-warehouse = "{{.environment}}_{{.name}}"
snowflake-warehouse-role = "{{.prefix}}_{{.environment}}_{{.warehouse}}_{{.name}}"
}
```

### Module Structure

Standard Terraform module files:

- `main.tf` - Primary resource definitions with null_resource examples
- `variables.tf` - Input variables including example_var and sub_resource object
- `outputs.tf` - Output value definitions
- `locals.tf` - Local value computations
- `versions.tf` - Provider version constraints
- `providers.tf` - Local terraform provider configuration
- `bakend.tf` - Local terraform backend configuration
- `examples/` - Directory with example usage of module, usually `simple` (module with minimal configuration) and `complete` (full module variable usage with any suggestions and configurations that might be a good example for future use) is created.
- `modules/` - Standard directory that stores any submodules used within this module (if needed)

## Common Development Commands

### Terraform Operations

```bash
# Initialize and validate
terraform init
terraform validate

# Format and plan
terraform fmt -recursive
terraform plan

# Apply changes
terraform apply
```

### Pre-commit Hooks

```bash
# Install hooks
pre-commit install

# Run all hooks
pre-commit run --all-files

# Run specific validations
pre-commit run terraform-validate
pre-commit run terraform-fmt
pre-commit run tflint
```

### Linting and Documentation

```bash
# Run TFLint with custom config
tflint --config=.tflint.hcl

# Security scanning
checkov -d . --skip-check CKV_TF_1
```

## Pre-commit Configuration

Comprehensive pre-commit hooks configured in `.pre-commit-config.yaml`:

- `terraform-validate` - Validates configuration (runs terraform init)
- `terraform-fmt` - Formats code
- `tflint` - Linting with custom `.tflint.hcl` config
- `terraform-docs` - Auto-generates documentation
- `checkov` - Security scanning (skips CKV_TF_1 for module sources)
- Standard Git hooks (merge conflict detection, YAML validation, EOF fixing)

## Template Usage Notes

When using this template:

1. Replace placeholder text in italics from README.md
2. Update repository name, badges, and links to match your module
3. Replace example variables (`example_var`, `sub_resource`) with actual module variables

## Subresource Context Handling

For modules that need multiple resources with different naming patterns, use the subresource context template pattern:

### Subresource Pattern Implementation

1. **Add context_template_name to subresource variables**:

```hcl
variable "sub_resource" {
description = "Some other resource that is part of stack/module"
type = object({
example_var = string
context_template_name = optional(string) # Allows subresource to use different template
})
}
```

2. **Create subresource template lookup in locals**:

```hcl
locals {
context_template = lookup(var.context_templates, var.name_scheme.context_template_name, null)
subresource_context_template = lookup(var.context_templates,
coalesce(var.sub_resource.context_template_name, var.name_scheme.context_template_name),
null
)
}
```

3. **Use separate data sources for each resource type**:

```hcl
data "context_label" "this" {
template = local.context_template
values = merge(
var.name_scheme.extra_values,
{ name = var.name }
)
}

data "context_label" "subresource" {
template = local.subresource_context_template
values = merge(
var.name_scheme.extra_values,
{ name = var.name }
)
}
```

4. **Example context templates for different resource types**:

```hcl
context_templates = {
resource-type = "{{.environment}}-{{.project}}-{{.name}}"
subresource-type = "{{.environment}}-{{.project}}-{{.name}}-{{.sub}}"
}
```

5. **Provider configuration with additional properties**:

```hcl
provider "context" {
properties = {
"environment" = {}
"name" = {}
"project" = {}
"sub" = {}
}
values = {
environment = "dev"
project = "myproject"
sub = "sub"
}
}
```

### Key Principles for Subresource Handling

- **Single source of truth**: Use one `extra_values` from `name_scheme` - don't duplicate configuration
- **Template-driven**: Let context provider and templates handle value logic, avoid hardcoding
- **Optional override**: Subresources can specify their own `context_template_name` or inherit from main resource
- **Clean separation**: Each resource type gets its own data source with appropriate template
- **Provider-managed values**: Set values like `sub = "sub"` in the context provider, not in module logic

## Development hints

- Always use terraform mcp server to download most up to date documentation and versions
- Try to use Context7 mcp server to get information about additional libraries
- Always use `getindata` modules, if available, instead of unknown modules or raw resources
- Always use terraform best practices when creating code, planning and reviewing
- Always try to create code that is as short as possible
- Always create code that is readable and easily understandable
- **Context Provider Best Practices**:
- Move provider configurations to `providers.tf` files, not in `main.tf`
- Use `.tfvars` files for context templates configuration in examples
- Keep naming logic in context provider and templates, avoid hardcoded values in resources
- Use single `extra_values` source to avoid configuration duplication
33 changes: 9 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,34 +61,15 @@ _Additional information that should be made public, for ex. how to solve known i

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| <a name="input_additional_tag_map"></a> [additional\_tag\_map](#input\_additional\_tag\_map) | Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`.<br>This is for some rare cases where resources want additional configuration of tags<br>and therefore take a list of maps with tag key, value, and additional configuration. | `map(string)` | `{}` | no |
| <a name="input_attributes"></a> [attributes](#input\_attributes) | ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`,<br>in the order they appear in the list. New attributes are appended to the<br>end of the list. The elements of the list are joined by the `delimiter`<br>and treated as a single ID element. | `list(string)` | `[]` | no |
| <a name="input_context"></a> [context](#input\_context) | Single object for setting entire context at once.<br>See description of individual variables for details.<br>Leave string and numeric variables as `null` to use default value.<br>Individual variable settings (non-null) override settings in context object,<br>except for attributes, tags, and additional\_tag\_map, which are merged. | `any` | <pre>{<br> "additional_tag_map": {},<br> "attributes": [],<br> "delimiter": null,<br> "descriptor_formats": {},<br> "enabled": true,<br> "environment": null,<br> "id_length_limit": null,<br> "label_key_case": null,<br> "label_order": [],<br> "label_value_case": null,<br> "labels_as_tags": [<br> "unset"<br> ],<br> "name": null,<br> "namespace": null,<br> "regex_replace_chars": null,<br> "stage": null,<br> "tags": {},<br> "tenant": null<br>}</pre> | no |
| <a name="input_delimiter"></a> [delimiter](#input\_delimiter) | Delimiter to be used between ID elements.<br>Defaults to `-` (hyphen). Set to `""` to use no delimiter at all. | `string` | `null` | no |
| <a name="input_descriptor_formats"></a> [descriptor\_formats](#input\_descriptor\_formats) | Describe additional descriptors to be output in the `descriptors` output map.<br>Map of maps. Keys are names of descriptors. Values are maps of the form<br>`{<br> format = string<br> labels = list(string)<br>}`<br>(Type is `any` so the map values can later be enhanced to provide additional options.)<br>`format` is a Terraform format string to be passed to the `format()` function.<br>`labels` is a list of labels, in order, to pass to `format()` function.<br>Label values will be normalized before being passed to `format()` so they will be<br>identical to how they appear in `id`.<br>Default is `{}` (`descriptors` output will be empty). | `any` | `{}` | no |
| <a name="input_descriptor_name"></a> [descriptor\_name](#input\_descriptor\_name) | Name of the descriptor used to form a resource name | `string` | `"resource-type"` | no |
| <a name="input_enabled"></a> [enabled](#input\_enabled) | Set to false to prevent the module from creating any resources | `bool` | `null` | no |
| <a name="input_environment"></a> [environment](#input\_environment) | ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' | `string` | `null` | no |
| <a name="input_context_templates"></a> [context\_templates](#input\_context\_templates) | Map of context templates used for naming conventions - this variable supersedes `naming_scheme.properties` and `naming_scheme.delimiter` configuration | `map(string)` | `{}` | no |
| <a name="input_example_var"></a> [example\_var](#input\_example\_var) | Example variable passed into the module | `string` | n/a | yes |
| <a name="input_id_length_limit"></a> [id\_length\_limit](#input\_id\_length\_limit) | Limit `id` to this many characters (minimum 6).<br>Set to `0` for unlimited length.<br>Set to `null` for keep the existing setting, which defaults to `0`.<br>Does not affect `id_full`. | `number` | `null` | no |
| <a name="input_label_key_case"></a> [label\_key\_case](#input\_label\_key\_case) | Controls the letter case of the `tags` keys (label names) for tags generated by this module.<br>Does not affect keys of tags passed in via the `tags` input.<br>Possible values: `lower`, `title`, `upper`.<br>Default value: `title`. | `string` | `null` | no |
| <a name="input_label_order"></a> [label\_order](#input\_label\_order) | The order in which the labels (ID elements) appear in the `id`.<br>Defaults to ["namespace", "environment", "stage", "name", "attributes"].<br>You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present. | `list(string)` | `null` | no |
| <a name="input_label_value_case"></a> [label\_value\_case](#input\_label\_value\_case) | Controls the letter case of ID elements (labels) as included in `id`,<br>set as tag values, and output by this module individually.<br>Does not affect values of tags passed in via the `tags` input.<br>Possible values: `lower`, `title`, `upper` and `none` (no transformation).<br>Set this to `title` and set `delimiter` to `""` to yield Pascal Case IDs.<br>Default value: `lower`. | `string` | `null` | no |
| <a name="input_labels_as_tags"></a> [labels\_as\_tags](#input\_labels\_as\_tags) | Set of labels (ID elements) to include as tags in the `tags` output.<br>Default is to include all labels.<br>Tags with empty values will not be included in the `tags` output.<br>Set to `[]` to suppress all generated tags.<br>**Notes:**<br> The value of the `name` tag, if included, will be the `id`, not the `name`.<br> Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be<br> changed in later chained modules. Attempts to change it will be silently ignored. | `set(string)` | <pre>[<br> "default"<br>]</pre> | no |
| <a name="input_name"></a> [name](#input\_name) | ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.<br>This is the only ID element not also included as a `tag`.<br>The "name" tag is set to the full `id` string. There is no tag with the value of the `name` input. | `string` | `null` | no |
| <a name="input_namespace"></a> [namespace](#input\_namespace) | ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique | `string` | `null` | no |
| <a name="input_regex_replace_chars"></a> [regex\_replace\_chars](#input\_regex\_replace\_chars) | Terraform regular expression (regex) string.<br>Characters matching the regex will be removed from the ID elements.<br>If not set, `"/[^a-zA-Z0-9-]/"` is used to remove all characters other than hyphens, letters and digits. | `string` | `null` | no |
| <a name="input_stage"></a> [stage](#input\_stage) | ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' | `string` | `null` | no |
| <a name="input_sub_resource"></a> [sub\_resource](#input\_sub\_resource) | Some other resource that is part of stack/module | <pre>object({<br> descriptor_name = optional(string, "sub-resource-type")<br> example_var = string<br> })</pre> | n/a | yes |
| <a name="input_tags"></a> [tags](#input\_tags) | Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`).<br>Neither the tag keys nor the tag values will be modified by this module. | `map(string)` | `{}` | no |
| <a name="input_tenant"></a> [tenant](#input\_tenant) | ID element \_(Rarely used, not included by default)\_. A customer identifier, indicating who this instance of a resource is for | `string` | `null` | no |
| <a name="input_name"></a> [name](#input\_name) | Name of the resource | `string` | n/a | yes |
| <a name="input_name_scheme"></a> [name\_scheme](#input\_name\_scheme) | Naming scheme configuration for the resource. This configuration is used to generate names using context provider:<br> - `properties` - list of properties to use when creating the name - is superseded by `var.context_templates`<br> - `delimiter` - delimited used to create the name from `properties` - is superseded by `var.context_templates`<br> - `context_template_name` - name of the context template used to create the name<br> - `replace_chars_regex` - regex to use for replacing characters in property-values created by the provider - any characters that match the regex will be removed from the name<br> - `extra_values` - map of extra label-value pairs, used to create a name<br> - `uppercase` - convert name to uppercase | <pre>object({<br> properties = optional(list(string), ["environment", "name"])<br> delimiter = optional(string, "-")<br> context_template_name = optional(string, "resource-type")<br> replace_chars_regex = optional(string, "[^a-zA-Z0-9_-]")<br> extra_values = optional(map(string))<br> uppercase = optional(bool, false)<br> })</pre> | `{}` | no |
| <a name="input_sub_resource"></a> [sub\_resource](#input\_sub\_resource) | Some other resource that is part of stack/module | <pre>object({<br> example_var = string<br> context_template_name = optional(string)<br> })</pre> | n/a | yes |

## Modules

| Name | Source | Version |
|------|--------|---------|
| <a name="module_subresource_label"></a> [subresource\_label](#module\_subresource\_label) | cloudposse/label/null | 0.25.0 |
| <a name="module_this"></a> [this](#module\_this) | cloudposse/label/null | 0.25.0 |
No modules.

## Outputs

Expand All @@ -100,13 +81,15 @@ _Additional information that should be made public, for ex. how to solve known i

| Name | Version |
|------|---------|
| <a name="provider_context"></a> [context](#provider\_context) | ~> 0.4.0 |
| <a name="provider_null"></a> [null](#provider\_null) | 3.1.1 |

## Requirements

| Name | Version |
|------|---------|
| <a name="requirement_terraform"></a> [terraform](#requirement\_terraform) | >= 1.3.0 |
| <a name="requirement_context"></a> [context](#requirement\_context) | ~> 0.4.0 |
| <a name="requirement_null"></a> [null](#requirement\_null) | 3.1.1 |

## Resources
Expand All @@ -115,6 +98,8 @@ _Additional information that should be made public, for ex. how to solve known i
|------|------|
| [null_resource.output_input](https://registry.terraform.io/providers/hashicorp/null/3.1.1/docs/resources/resource) | resource |
| [null_resource.subresource](https://registry.terraform.io/providers/hashicorp/null/3.1.1/docs/resources/resource) | resource |
| [context_label.subresource](https://registry.terraform.io/providers/cloudposse/context/latest/docs/data-sources/label) | data source |
| [context_label.this](https://registry.terraform.io/providers/cloudposse/context/latest/docs/data-sources/label) | data source |
<!-- END_TF_DOCS -->

## CONTRIBUTING
Expand Down
Loading