Infrastructure as code · Intermediate · 20 min
Lay out the Relay OpenTofu project: providers, variables and outputs
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · hashicorp/aws 6.74
You will have an OpenTofu 1.13 project for Relay split into versions, provider, variable, local and output files, with separate dev and prod values and a private, versioned S3 bucket planned and applied for dev.
On this page
This series builds Relay, a small public status page, on AWS with OpenTofu. By part 8, Relay is Nginx serving a static page from one EC2 instance in its own VPC, with the page's assets in a private S3 bucket, state stored remotely and encrypted, the network in a tested module, plans posted on pull requests and a nightly drift check. All of it lives in one folder, ~/relay-demo.
This first part sets up the folder so the later parts have somewhere obvious to put things. The OpenTofu basics tutorial kept everything in one main.tf, which is fine for two resources and painful for thirty. Here you split the root module into files by job, pin the tool and provider versions, declare typed inputs that reject bad values, keep dev and prod values in separate files, and plan and apply the first real resource: the assets bucket, with versioning on and all public access blocked.
OpenTofu reads every .tf file in a folder as one configuration, so the file names are for people, not for the tool. The layout used in this series is:
versions.tf: which OpenTofu and provider versions the project acceptsproviders.tf: how the AWS provider is configuredvariables.tf: the inputs, with types, defaults and validationlocals.tf: names and tags worked out once from the inputs- one file per area of infrastructure, starting with
assets.tf outputs.tf: the values other parts and people needdev.tfvarsandprod.tfvars: the values for each environment
Creating an S3 bucket in your account is not free in principle: S3 bills for what you store and the requests you make. An empty bucket stores nothing, and this part uploads nothing, but check the S3 pricing page for your Region before you go further in the series.
Step 1 · Create the folder and pin the versions
Make the project folder and confirm your OpenTofu version:
mkdir -p ~/relay-demo
cd ~/relay-demo
tofu versionWrite versions.tf. It says which versions of OpenTofu and of the AWS provider this project works with:
cat > versions.tf <<'HCL'
terraform {
required_version = "~> 1.13"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.74"
}
}
}
HCL~> 1.13 accepts OpenTofu 1.13 and any later 1.x release, so a teammate on 1.12 gets a clear error instead of odd behaviour. ~> 6.74 accepts AWS provider 6.74 and later 6.x releases, never 7.0, because a major version is where providers rename and remove arguments.
Add a .gitignore before anything else lands in the folder. State, plan files and the provider download must stay out of Git, and so must override files, which are personal adjustments:
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
*_override.tf
EOFThe AWS provider is a large download: the Linux amd64 archive for 6.74.0 is about 174 MB. If you pay for data by the gigabyte, as many people on prepaid mobile data do, turn on OpenTofu's plugin cache so every project on this machine shares one copy instead of downloading its own:
mkdir -p "$HOME/.terraform.d/plugin-cache"
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"Add the export line to your ~/.bashrc or ~/.zshrc to keep it. Then initialise the project:
tofu inittofu init downloads the newest provider that matches ~> 6.74 and writes .terraform.lock.hcl. The lock file records the exact version and its checksums, so the next tofu init, on your machine or a teammate's, installs the same build. Commit it with the code. Pin provider versions with the dependency lock file covers upgrades and checksums in more depth.
The lock file only holds checksums for the platform you ran tofu init on. If your team mixes Linux and macOS machines, record the others too. This downloads the provider once more per platform, so skip it on a metered connection:
tofu providers lock -platform=linux_amd64 -platform=linux_arm64 -platform=darwin_arm64Check it worked
tofu version prints OpenTofu v1.13.10 or a later 1.13 release. tofu init ends with OpenTofu has been successfully initialized!. Look at the lock file:
grep -A2 'provider "registry.opentofu.org/hashicorp/aws"' .terraform.lock.hclIt shows the provider address, a version line such as version = "6.74.0" and constraints = "~> 6.74".
Step 2 · Declare the inputs with types and validation
Every value that differs between dev and prod, or that a person might reasonably change, becomes a variable. Write variables.tf:
cat > variables.tf <<'HCL'
variable "project" {
type = string
description = "Short project name, used at the start of every resource name."
default = "relay"
validation {
condition = can(regex("^[a-z][a-z0-9-]{1,11}$", var.project))
error_message = "project must be 2 to 12 characters: lowercase letters, digits and hyphens, starting with a letter."
}
}
variable "environment" {
type = string
description = "Which copy of Relay this is: dev or prod."
validation {
condition = contains(["dev", "prod"], var.environment)
error_message = "environment must be dev or prod."
}
}
variable "region" {
type = string
description = "AWS Region to build in, for example eu-west-1."
validation {
condition = can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]$", var.region))
error_message = "region must look like an AWS Region code, for example eu-west-1 or af-south-1."
}
}
variable "force_destroy_assets" {
type = bool
description = "Allow tofu destroy to delete the assets bucket even when it still holds objects."
default = false
}
variable "extra_tags" {
type = map(string)
description = "Additional tags for every resource, such as an owner or cost centre."
default = {}
validation {
condition = alltrue([for key in keys(var.extra_tags) : !startswith(lower(key), "aws:")])
error_message = "Tag keys starting with aws: are reserved by AWS."
}
}
HCLA few choices here are deliberate:
environmentandregionhave no default. Anyone running a plan has to say which environment and Region they mean, so nobody builds prod by forgetting a flag.- The
projectrule keeps names short for a reason. S3 bucket names are limited to 63 characters, and the bucket name you build later is the prefix, the wordassetsand a 12-digit account ID. force_destroy_assetsdefaults tofalse, the safe value. Only dev turns it on.- The
extra_tagsrule rejects keys starting withaws:, a prefix AWS keeps for its own tags. Catching it here gives a clear message before any API call.
A validation block runs when OpenTofu has the variable's value, which is at plan time, not when you write the file. For preconditions and check blocks as well as validation, see check inputs with validation, preconditions and check blocks.
Check it worked
tofu validateIt prints Success! The configuration is valid. If you mistyped a function name or a bracket, the error names the file and line.
Step 3 · Name and tag everything from one place
Resource names and tags are built from the same few inputs everywhere. Work them out once in locals.tf:
cat > locals.tf <<'HCL'
locals {
name_prefix = "${var.project}-${var.environment}"
common_tags = merge(var.extra_tags, {
Project = var.project
Environment = var.environment
ManagedBy = "opentofu"
})
}
HCLmerge() takes the later map's value when a key appears twice, so the three standard tags always win over anything in extra_tags. Someone cannot pass Environment = "prod" from the dev file by accident.
Now configure the provider in providers.tf. default_tags puts the common tags on every resource that supports tags, so no resource file has to repeat them:
cat > providers.tf <<'HCL'
provider "aws" {
region = var.region
default_tags {
tags = local.common_tags
}
}
HCLThe provider block holds no credentials, and it should stay that way. The AWS provider looks for them where the AWS CLI does: environment variables, then your shared config and credentials files. Tell it which profile to use in your shell. Replace relay-sandbox with your own profile name, then confirm who you are signed in as:
export AWS_PROFILE=relay-sandbox
aws sts get-caller-identityThe second command prints your account ID and the ARN of the user or role you are using. Check that the account is the practice one before you go further.
Check it worked
tofu validateIt still prints Success! The configuration is valid. The provider now has a Region and tags to use, but nothing has called AWS yet.
Step 4 · Give each environment its own values file
A .tfvars file sets variable values. Keep one per environment, side by side, so a reviewer can compare them at a glance. Write dev.tfvars and prod.tfvars, replacing the Owner values with your own name and team:
cat > dev.tfvars <<'HCL'
environment = "dev"
region = "eu-west-1"
force_destroy_assets = true
extra_tags = {
Owner = "replace-with-your-name"
}
HCL
cat > prod.tfvars <<'HCL'
environment = "prod"
region = "eu-west-1"
force_destroy_assets = false
extra_tags = {
Owner = "replace-with-your-team"
CostCentre = "relay"
}
HCLPick the Region closest to most of Relay's visitors. For visitors in southern Africa, af-south-1 (Cape Town) is closer than Europe, but it is an opt-in Region: enable it for your account before you use it, or every call fails.
These files are safe to commit because they hold no secrets, and they should never hold any. If a later value is secret, pass it in a TF_VAR_ environment variable or read it from a secrets manager, never from a committed file.
OpenTofu only reads terraform.tfvars and *.auto.tfvars on its own. Named files like these are loaded only when you pass -var-file, which is the point: every command says which environment it is for. Ask OpenTofu what the dev values produce:
printf '%s\n' 'local.name_prefix' 'local.common_tags' | tofu console -var-file=dev.tfvarsThen try a value the rules forbid. A -var after -var-file overrides the file:
tofu plan -var-file=dev.tfvars -var environment=stagingCheck it worked
The console prints "relay-dev" and then a map something like "Environment" = "dev", "ManagedBy" = "opentofu", your Owner value and "Project" = "relay", with the keys in quotes. The plan with environment=staging stops with Error: Invalid value for variable and your message, environment must be dev or prod., before it plans anything.
Step 5 · Describe the assets bucket and its outputs
Relay's status page loads its images and stylesheet from a private bucket that only the web server can read (part 3 adds that permission). Write assets.tf:
cat > assets.tf <<'HCL'
data "aws_caller_identity" "current" {}
resource "aws_s3_bucket" "assets" {
bucket = "${local.name_prefix}-assets-${data.aws_caller_identity.current.account_id}"
force_destroy = var.force_destroy_assets
tags = {
Name = "${local.name_prefix}-assets"
}
}
resource "aws_s3_bucket_versioning" "assets" {
bucket = aws_s3_bucket.assets.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_public_access_block" "assets" {
bucket = aws_s3_bucket.assets.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
HCLBucket names are shared by every AWS account in the world, so relay-dev-assets on its own is likely taken. The aws_caller_identity data source reads your account ID, and adding it to the name makes a clash very unlikely. Since version 4 of the provider, versioning is its own resource, aws_s3_bucket_versioning, rather than a block inside aws_s3_bucket, and the public access block has always been a separate resource. All three still describe one bucket in AWS. You do not need an encryption resource for the basics: S3 has encrypted every new object with S3-managed keys by default since January 2023.
Versioning means an overwritten or deleted file can be recovered, and it also means old versions keep counting as stored data. Part 8 covers emptying a versioned bucket before you delete it.
Now write outputs.tf. Outputs are how later parts, scripts and people get values out of the project without reading the state:
cat > outputs.tf <<'HCL'
output "name_prefix" {
description = "Prefix shared by every Relay resource name in this environment."
value = local.name_prefix
}
output "assets_bucket_name" {
description = "Name of the private bucket that holds the status page assets."
value = aws_s3_bucket.assets.bucket
}
output "assets_bucket_arn" {
description = "ARN of the assets bucket, for IAM policies in later parts."
value = aws_s3_bucket.assets.arn
}
HCLMake a dev plan and save it:
tofu plan -var-file=dev.tfvars -out=dev.tfplanCheck it worked
The plan lists three resources that will be created and ends with Plan: 3 to add, 0 to change, 0 to destroy. The bucket's bucket line already shows the full name, relay-dev-assets- followed by your account ID, because the data source was read during the plan. Its tags_all line lists your common tags plus Name, which is default_tags at work. The outputs appear under Changes to Outputs.
Step 6 · Apply the dev plan and confirm nothing is left to change
Applying a saved plan does exactly what you reviewed and asks no further question. Apply it, then read the outputs:
tofu apply dev.tfplan
tofu outputLook at what OpenTofu recorded for the bucket's public access settings and tags:
tofu state show aws_s3_bucket_public_access_block.assets
tofu state show aws_s3_bucket.assetsThen plan again. -detailed-exitcode makes the command exit with 0 when there are no changes and 2 when there are, which scripts and part 8's drift check rely on:
tofu plan -var-file=dev.tfvars -detailed-exitcodeCheck it worked
tofu output prints assets_bucket_arn, assets_bucket_name and name_prefix = "relay-dev". The public access block shows all four settings as true, and the bucket's tags_all includes ManagedBy = "opentofu". The last plan says No changes. Your infrastructure matches the configuration. and echo $? straight after it prints 0. In the S3 console, the bucket's Permissions tab shows Block all public access as On.
Step 7 · Compare the prod plan and check the formatting
Plan prod against the same folder, without saving the plan:
tofu plan -var-file=prod.tfvarsRead it carefully, because it shows the biggest trap in this layout. The plan wants to destroy the dev bucket and create relay-prod-assets-... in its place: Plan: 3 to add, 0 to change, 3 to destroy. The values files change the inputs, but both environments share one state file in this folder, so OpenTofu sees prod as an edit to dev. Do not apply prod here. Part 4 moves state into S3, and each environment needs its own state there before prod is ever built.
Finally, check the formatting. tofu fmt lays out .tf and .tfvars files in the standard style, and -check reports files that differ without changing them, which is what a CI job runs:
tofu fmt -check
tofu validateIf you stop the series here, remove the dev bucket. Leave it in place if you are going on to part 2, which builds on this state:
tofu destroy -var-file=dev.tfvarsCheck it worked
tofu fmt -check prints nothing and exits with 0. If it prints a file name, run tofu fmt to fix the layout and check again. Your folder now holds versions.tf, providers.tf, variables.tf, locals.tf, assets.tf, outputs.tf, dev.tfvars, prod.tfvars, .gitignore and .terraform.lock.hcl, plus dev.tfplan and the local state, which stay out of Git.
Next steps
- Part 2 adds Relay's VPC, subnets and security group to this skeleton: build the Relay network with OpenTofu.
- Part 4 replaces the local state file with encrypted remote state: store Relay state remotely with encryption.
- Go back over plan, apply and drift with local providers in manage infrastructure with OpenTofu.
- See how the S3 backend works in Terraform in store Terraform 1.17 state remotely in an S3 bucket.
Related tutorials
- Turn the Relay network into a reusable OpenTofu moduleYou will move Relay's VPC, subnets, routes and web security group into a local modules/network module with its own inputs, outputs and README, and adopt the 18 running objects with moved blocks so the plan destroys nothing.
- Test the Relay network module with tofu test and mock providersYou will have a tofu test suite for Relay's network module that checks subnet ranges, input validation and outputs against a mocked AWS provider, and passes in seconds with no credentials.
- Store the Relay state in S3 with locking and OpenTofu state encryptionYou will create a state bucket from a separate bootstrap configuration, move the Relay state into it with S3 locking, and encrypt that state and every saved plan with OpenTofu's own encryption, ready to switch to AWS KMS.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials