Define Project Name Variable with Naming Convention Validation

Create a Terraform string variable for project names with regex validation enforcing lowercase alphanumeric naming conventions.

Common Patterns

Detailed Explanation

Project Name Variable

A project name variable is used throughout your infrastructure for resource naming, tagging, and organization. Enforcing a naming convention prevents issues with services that have strict name requirements.

Variable Definition

variable "project_name" {
  type        = string
  description = "Name of the project, used for resource naming"
  default     = "my-project"

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]*$", var.project_name))
    error_message = "Project name must start with a letter and contain only lowercase letters, numbers, and hyphens."
  }
}

Why This Naming Convention?

Many AWS resources have naming restrictions:

Service Max Length Allowed Characters
S3 Bucket 63 a-z, 0-9, -, .
IAM Role 64 A-Za-z0-9+=,.@_-
Lambda Function 64 a-zA-Z0-9-_
RDS Instance 63 a-z0-9-
ECS Cluster 255 a-zA-Z0-9-_

By enforcing ^[a-z][a-z0-9-]*$, the project name is compatible with the strictest requirements (S3 and RDS).

Usage in Resource Naming

locals {
  name_prefix = "${var.project_name}-${var.environment}"
}

resource "aws_s3_bucket" "assets" {
  bucket = "${local.name_prefix}-assets"
}

resource "aws_iam_role" "app" {
  name = "${local.name_prefix}-app-role"
}

Adding Length Validation

For extra safety, combine regex with length checks:

validation {
  condition     = can(regex("^[a-z][a-z0-9-]*$", var.project_name)) && length(var.project_name) >= 3 && length(var.project_name) <= 20
  error_message = "Project name must be 3-20 characters, start with a letter, and contain only lowercase letters, numbers, and hyphens."
}

Use Case

Standardized infrastructure modules where consistent resource naming across S3, IAM, RDS, and other services requires a validated project identifier.

Try It — Terraform Variable Generator

Open full tool