Deployment keys for unique deployments Terraform deployments

Unique keys for identifying resources with Terraform deployments

Table Of Contents

Today I Explained

Resources within Terraform can be sometimes be created with the name_prefix field set. Instead of using the fixed name field which leaves room for collisions, the name_prefix will generate a unique suffix, typically sourced from the current timestamp. For a stack with multiple resources using these fields, it can generate a large number of uniquely named resources. For resources that don’t support this kind of field, the option still exists for using the random provider to generate a prefix or suffix.

This pattern of uniquely generated resource names can be especially useful as it introduces strong opinionation about how the resources of a Terraform module are referenced. Each deployment of the module is using randomly generated names, forcing referencing a resource from one of these modules to access by the terraform outputs (if any are set), searching by tag conventions, or using fixed name variables.

data "aws_ssm_parameter" "vpc_id" {
  name = "/infra/networking/vpc/id"
}

data "aws_ami" "example" {
  most_recent = true

  owners = ["self"]
  tags = {
    Name   = "app-server"
    Tested = "true"
  }
}

A note on Parameter Store entries

Using parameter store entries to encode the randomly generated names can seem like an unnecessary extra step, when using a fixed name for the resource would allow for direct references. What using a parameter store entry enables is relational mapping between infrastructure within an account. These entries act as weak references connecting the infrastructure. The values of the parameter store can be updated without modification to the dependant module, which permits transitioning between architectures.

As the relational mapping is pushed onto the infrastructure, it isn’t as much the responsibility of the deployment tooling to handle the relational mapping. As services evolve, the pattern creates an almost self-documenting workflow in which interfaces between services as being exposed through tags or parameter store entries.

A note on tags and parameter store

Terraform supports lookups of many but not all infrastructure by tags, which might make it seem like the only necessary approach for this kind of pattern. This can be true, and the parameter store approach is more aimed at flexibility of property lookup, or facilitating interfaces with cloudformation.