Terraform on AWS: EC2, State, Backends, Workspaces and Modules
A hands-on Terraform walkthrough on AWS: launch EC2, read the state file, handle drift, use map variables, provisioners, outputs, an S3 backend, workspaces and modules.

ON THIS PAGE
Terraform turns AWS infrastructure into code that can be reviewed, versioned and rebuilt, and the habits formed on a small project (reading plans, protecting state, catching drift) carry straight over to production. This guide manages EC2 instances from an Ubuntu VM (built with Vagrant): it starts with one instance in one file, then splits the project, examines the state file and drift, deploys a website with provisioners, moves the state to Amazon S3, and runs the same code in dev, stage and prod with workspaces. Along the way it explains what plan and apply do under the hood and the mistakes worth avoiding.
What Terraform is
Terraform is an infrastructure as code (IaC) tool. You describe resources such as servers, networks and DNS records in text files, and Terraform creates, changes and deletes them for you through the cloud provider's API. Because the files live in Git, the infrastructure can be reviewed, versioned and reused like any other code.
Common IaC choices:
| Tool | Where it fits |
|---|---|
| Terraform | Many platforms: AWS, Azure, GCP, Kubernetes, GitHub and thousands more through providers |
| AWS CloudFormation | AWS only, native to AWS |
| Azure Bicep | Azure only |
| OpenTofu | Open-source fork of Terraform with the same language and workflow |
Since version 1.6, Terraform is released under the Business Source License (BUSL), which is not an open-source license. That change is the reason OpenTofu exists, as covered in the OpenTofu part of this series.
Two concepts underpin everything that follows:
- Provider: a plugin that communicates with one platform's API. The
hashicorp/awsprovider turnsaws_instanceblocks into EC2 API calls. Providers are published on the Terraform Registry. - Workflow: you write configuration, run
terraform planto see what will change, and runterraform applyto make the change. Terraform records what it created in a state file.
Prerequisites
- An Ubuntu machine (the examples use an Ubuntu 24.04 VM).
- An AWS account with the AWS CLI configured for an IAM user.
- An existing security group and EC2 key pair in us-east-1, referenced by ID and name in the examples.
Install Terraform
Install Terraform by following the official install guide (the examples use Ubuntu 24.04), then verify the binary:
$ terraform --version
$ which terraform

Terraform uses the same credentials as the AWS CLI. Configure the CLI as described in the AWS IAM guide, then confirm that it can reach the account:
$ aws s3 ls
Launch an EC2 instance with Terraform
Creating an instance with Terraform requires the same choices as the console: a name, an AMI, an instance type and a security group. The difference is that they are declared in a file rather than entered in a form.
The first configuration
Terraform reads every .tf file in the current directory. The first version uses two files: one for the provider and one for the instance.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "us-east-1"
}The required_providers block declares which provider to download and which versions are allowed. Without it, Terraform guesses hashicorp/aws from the resource names and takes the latest version.
resource "aws_instance" "demo_server_dipendra" {
ami = "ami-0360c520857e3138f" # Ubuntu 24.04 in us-east-1
instance_type = "t2.micro"
vpc_security_group_ids = ["sg-05694bdfc51f0d457"]
tags = {
Name = "demo-vm-dipenra_Bhatta"
created_by = "terraform"
}
}aws_instance is the resource type and demo_server_dipendra is the local name. Together they form the address aws_instance.demo_server_dipendra, which is how Terraform refers to this instance in plans and in the state.
terraform init
terraform init prepares the directory. It downloads the provider plugin and writes a lock file.
$ terraform init
After init there is a hidden .terraform directory that holds the provider binary, and a .terraform.lock.hcl file that records the exact provider version. The lock file is covered later.

terraform plan and terraform apply
terraform plan previews the actions Terraform will take. A + means create, ~ means update in place, and - means destroy.
$ terraform plan
terraform apply displays the same plan, asks for yes, and then makes the change.
$ terraform apply
The state file
After the first apply, a new file appears: terraform.tfstate. It is a JSON file that maps each resource address to the real object in AWS, with all its attributes: instance ID, ARN, AMI, availability zone, IP addresses, security groups and more.

How plan decides what to change
Running terraform plan again without editing anything reports no changes.

A common assumption is that Terraform compares the .tf files only with the local state file. The line Refreshing state... [id=i-0ca1640cbaed4eaf0] shows otherwise: by default, plan and apply first ask AWS for the current attributes of every resource in the state, then work through three elements:
- the configuration (
.tffiles), - the state file, refreshed with the real values from AWS,
- and from that, the actions needed to make AWS match the configuration.
The state file tells Terraform which real objects it manages. The refresh tells it what they look like now.
To test an update, add an owner tag in instance.tf. The plan shows an update in place (~), not a replacement:

A plan changes nothing in AWS. The console still shows only the old tags:

After terraform apply, the new tag is on the instance:

State backup and destroy
After this second apply, Terraform also wrote terraform.tfstate.backup.

With the default local backend, Terraform keeps one backup: the state as it was before the last write. The backup helps to check what changed or to recover from a corrupted state file. It does not roll back the infrastructure, and it covers only one step.
terraform destroy deletes everything in the state. Afterwards terraform.tfstate has an empty resources list, and the backup still holds the instance that was just destroyed:
$ terraform destroy
Split the project into files
Terraform ignores file names; it loads every .tf file in the directory. Splitting files by purpose makes the project easier to read. A typical layout:
| File | Contents |
|---|---|
main.tf or instance.tf | Resources |
providers.tf | terraform block with required_providers, and provider blocks |
variables.tf | Input variables: values that change between runs or environments, such as AMIs, instance types, security groups and zones |
outputs.tf | Values to print after apply |
terraform.tfvars | Actual values for the variables |
Move the hardcoded values into variables:
resource "aws_instance" "demo_server_dipendra" {
ami = var.AMIS
instance_type = var.INSTANCE_TYPE
vpc_security_group_ids = [var.SECURITY_GROUP]
availability_zone = var.ZONE
tags = {
Name = "demo-vm-dipendra-Bhatta"
created_by = "terraform"
}
}# The default is used when no other value is given.
variable "REGION" {
description = "The region where resources are created"
default = "us-east-1"
type = string
}
variable "ZONE" {
description = "The availability zone for the instance"
default = "us-east-1a"
type = string
}
variable "SECURITY_GROUP" {
description = "Security group ID"
default = "sg-05694bdfc51f0d457"
type = string
}
variable "AMIS" {
description = "The AMI ID of the instance"
default = "ami-0360c520857e3138f"
type = string
}
variable "INSTANCE_TYPE" {
default = "t2.nano"
type = string
}providers.tf stays as before. The upper-case variable names used here work, but the common convention is lower-case snake_case, for example instance_type.

Then run the standard cycle:
$ terraform init
$ terraform validate
$ terraform plan
$ terraform applyterraform validate checks the syntax and references without calling AWS.
Drift: when AWS and the configuration disagree
Drift means the real infrastructure no longer matches what Terraform expects. It happens when someone changes resources in the console or CLI, when another script or tool changes them, or when AWS itself replaces or removes something. The three tests below each make a manual change outside Terraform. The official drift tutorial goes deeper.
The instance was deleted
After the instance is terminated from the console, terraform apply discovers during the refresh that it is gone and plans to create it again:

A tag was added in the console
Next, add a class = DevOps tag in the console:

The local state does not include the tag yet:

After terraform refresh, the tag appears in the state:

Two points matter here:
terraform refreshis deprecated. The current way isterraform apply -refresh-only, which shows what will change in the state and asks before writing it.terraform plan -refresh-onlyonly shows it.- Refreshing updates the state, not the configuration. The tag is still missing from
instance.tf, so the next normalterraform applywill remove it to match the code. If a manual change should stay, add it to the configuration.
The instance was stopped
After the instance is stopped in the console, a refresh records the new instance_state:

Run terraform plan (or terraform plan -refresh-only) regularly so drift surfaces early rather than during an urgent change.
Map variables for region-specific values
AMI IDs differ between regions. The same Ubuntu 24.04 image has these IDs:
| Region | AMI ID |
|---|---|
| us-east-1 | ami-0360c520857e3138f |
| us-east-2 | ami-0cfde0ea8edd312d4 |
A map variable stores one value per key, and var.AMIS[var.REGION] selects the matching AMI.
variable "REGION" {
description = "The region where resources are created"
default = "us-east-2"
type = string
}
variable "ZONE" {
description = "The availability zone for the instance"
default = "us-east-1a"
type = string
}
variable "SECURITY_GROUP" {
description = "Security group ID"
default = "sg-05694bdfc51f0d457"
type = string
}
variable "AMIS" {
description = "The AMI ID for each region"
type = map(string)
default = {
us-east-1 = "ami-0360c520857e3138f"
us-east-2 = "ami-0cfde0ea8edd312d4"
}
}
variable "INSTANCE_TYPE" {
default = "t2.nano"
type = string
}resource "aws_instance" "demo_server_dipendra" {
ami = var.AMIS[var.REGION]
instance_type = var.INSTANCE_TYPE
vpc_security_group_ids = [var.SECURITY_GROUP]
availability_zone = var.ZONE
tags = {
Name = "demo-vm-dipendra-Bhatta"
created_by = "terraform"
}
}provider "aws" {
region = var.REGION
}With REGION = "us-east-2", the plan picks the us-east-2 AMI:
$ terraform plan | grep region
$ terraform plan | grep ami
With the default changed to us-east-1, the plan selects the us-east-1 AMI:

Meta-arguments
Meta-arguments work on any resource type and change how Terraform handles the resource, not what the resource is.
depends_on
Terraform derives the order from references: if resource B uses an attribute of resource A, A is created first. depends_on is for the rare case where a dependency exists but is not visible in the code, so B must wait until A is fully done.
resource "aws_instance" "app" {
# ...
depends_on = [aws_iam_role_policy.example]
}See the depends_on documentation.
lifecycle
Some changes cannot be made in place, for example a new AMI. By default, Terraform destroys the old instance first and then creates the new one, which causes downtime. The lifecycle block changes this behavior:
resource "aws_instance" "web" {
# ...
lifecycle {
create_before_destroy = true
}
}The three most common rules:
| Rule | Effect |
|---|---|
create_before_destroy | Create the replacement first, then destroy the old object |
prevent_destroy | Fail any plan that would destroy this resource |
ignore_changes | Ignore changes to the listed attributes, for example tags managed by another tool |
count and for_each
Both create several copies of a resource from one block.
count = 4creates four instances, addressed by index:aws_instance.web[0]toaws_instance.web[3].for_eachtakes a map or a set of strings and creates one instance per key, addressed by key:aws_instance.web["frontend"].
Prefer for_each in most cases. With count, the instances form a list. Removing an item from the middle shifts every later item down one index, so Terraform plans to change or replace those instances as well. With for_each, removing a key removes only that instance.
provider
A resource uses the default aws provider unless told otherwise. To use a second region in the same project, add a provider with an alias and select it with the provider meta-argument:
provider "aws" {
alias = "ohio"
region = "us-east-2"
}
resource "aws_instance" "replica" {
provider = aws.ohio
# ...
}Provisioners, and why they are a last resort
A provisioner runs a command or copies files as part of creating (or destroying) a resource. HashiCorp's documentation titles the page Provisioners are a Last Resort, for these reasons:
- Plan cannot show them.
terraform planshows resource changes, but not what a provisioner will do. A bad script is only found during apply. - They need direct access. Most provisioners connect over SSH or WinRM, so Terraform needs network access to the server and login credentials. That widens the attack surface and puts more secrets in play.
- More moving parts. The right software must be installed, the server must be reachable at the right time, and a failure leaves a half-configured resource that Terraform marks as tainted.
Better options for common cases:
- Pass a startup script with
user_data(cloud-init) on the instance. - Bake software into the image with a tool like Packer.
- Use configuration management such as Ansible after Terraform creates the server.
- Use a provider resource if one exists for the task.
Types of provisioners
| Provisioner | Runs where | Needs a connection block |
|---|---|---|
local-exec | On the machine running Terraform | No |
remote-exec | On the new resource, as inline commands or a script | Yes |
file | Copies files or directories from the local machine to the new resource | Yes |
A minimal local-exec example:
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
command = "echo The server's IP address is ${self.private_ip}"
}
}All provisioners also accept when (for example, run only at destroy time) and on_failure (fail or continue).
The connection block tells Terraform how to log in: the user, the private key (or password), and the host. self.public_ip refers to the instance being created.
Hands-on: deploy a website with file and remote-exec
Without Terraform, the manual approach is to copy a script with scp and run it over SSH:
$ scp -i demo-key deploy_app.sh ubuntu@54.212.10.0:/tmpWith Terraform, the file provisioner copies the script, remote-exec runs it, and connection holds the SSH details. The instance also needs key_name, so AWS installs the matching public key on it.
#!/bin/bash
# Runs as root through sudo from remote-exec.
apt install -y apache2 wget unzip
systemctl start apache2
systemctl enable apache2
cd /tmp
wget https://www.tooplate.com/zip-templates/2129_crispy_kitchen.zip
unzip -o 2129_crispy_kitchen.zip
cp -r 2129_crispy_kitchen/* /var/www/html/
systemctl restart apache2resource "aws_instance" "demo_server_dipendra" {
ami = var.AMIS[var.REGION]
instance_type = var.INSTANCE_TYPE
key_name = "kp-dipendra-bhatta-aug4"
vpc_security_group_ids = [var.SECURITY_GROUP]
availability_zone = var.ZONE
tags = {
Name = "demo-vm-dipendra-Bhatta"
created_by = "terraform"
owner = "Deependra-Bhatta"
}
# Copy the script from the local machine to the instance
provisioner "file" {
source = "deploy_app.sh"
destination = "/tmp/deploy_app.sh"
}
# Run the script on the instance
provisioner "remote-exec" {
inline = [
"chmod u+x /tmp/deploy_app.sh",
"sudo /tmp/deploy_app.sh"
]
}
# How Terraform logs in for the two provisioners above
connection {
type = "ssh"
user = var.USER
private_key = file("kp-dipendra-bhatta-aug4.pem")
host = self.public_ip
}
}Add the SSH user to variables.tf (the default user on Ubuntu AMIs is ubuntu):
variable "USER" {
default = "ubuntu"
type = string
}The security group must allow SSH (port 22) from your IP for the provisioners, and HTTP (port 80) for the website.
During terraform apply, Terraform prints Provisioning with 'file'..., then connects over SSH and streams the script output:


The instance's public IP, shown in the console, serves the site:


Connecting through a bastion host
In a common setup, the frontend server has a public IP, but the database server sits in a private subnet with no public IP and no NAT gateway, so the internet cannot reach it. To configure the database server, connect through a bastion host (also called a jump host): a hardened server in a public subnet that you SSH into first, then hop to the private server.
The SSH connection block supports this directly with the bastion_* arguments:
connection {
type = "ssh"
user = "ubuntu"
private_key = file("db-key.pem")
host = self.private_ip
bastion_host = aws_instance.bastion.public_ip
bastion_user = "ubuntu"
bastion_private_key = file("bastion-key.pem")
}I have not run this configuration yet; it is the pattern to use when a provisioner must reach a private instance.
Output values
Without outputs, finding the site's IP means searching the console or the state file. Output values print chosen attributes at the end of terraform apply. They also let a child module pass values to its parent, and let other configurations read them through the terraform_remote_state data source.
output "My_instance_public_ip_address" {
value = aws_instance.demo_server_dipendra.public_ip
}
output "My_instance_private_ip" {
value = aws_instance.demo_server_dipendra.private_ip
}
output "My_instance_public_url" {
value = aws_instance.demo_server_dipendra.public_dns
}Outputs can also sit at the bottom of instance.tf, but a separate outputs.tf is easier to find. The plan lists them as known after apply:

terraform apply then prints the real values:

terraform output prints them again at any time without applying.
Remote state in Amazon S3
With the default local backend, terraform.tfstate exists only on the laptop of the person who ran apply. The code is in GitHub, but a teammate who clones it has no state. Terraform then assumes nothing exists and plans to create everything again, or the two people overwrite each other's work.
A backend determines where the state is stored. With the S3 backend, the state lives in a bucket that the whole team (and CI) can reach.
Create a bucket with default settings (here backend-bucket-dipendra-bhatta) and add one file to the provisioner project:
terraform {
backend "s3" {
bucket = "backend-bucket-dipendra-bhatta"
key = "terraform" # object name of the state file in the bucket
region = "us-east-1"
}
}The bucket must exist before terraform init; Terraform does not create it. The S3 backend docs strongly recommend turning on bucket versioning, so an old state can be recovered after a mistake. A path-like key such as ec2-demo/terraform.tfstate also lets one bucket hold the state of several projects.
$ terraform init
After terraform apply, the project directory no longer contains terraform.tfstate:

The state is now the terraform object in the bucket:

Opening the object shows the same JSON as a local state file, including the outputs:

To simulate a teammate, copy only the code into a new directory (example6), with no state file, and run terraform init there. terraform refresh and terraform plan read the state from S3 and find the existing instance, with no changes needed:

State locking
If two people run terraform apply on the same state at the same time, both write the state and one change can be lost or the state can break. State locking prevents this: while one run holds the lock, any other run that could write state waits or fails until the lock is released.
The backend.tf above has no locking. In current Terraform, the S3 backend can lock with a lock file stored next to the state in the same bucket:
terraform {
backend "s3" {
bucket = "backend-bucket-dipendra-bhatta"
key = "terraform"
region = "us-east-1"
+ use_lockfile = true
}
}Run terraform init again after changing backend settings. Older guides use a DynamoDB table (dynamodb_table) for the lock; the S3 backend docs now mark DynamoDB-based locking as deprecated.
If a run crashes and leaves a lock behind, terraform force-unlock <LOCK_ID> releases it. Use it only after confirming that no other run is active.
Workspaces
Running dev, stage and prod from copies of the same code leads to duplicated files, harder maintenance and accidental changes to the wrong environment. Workspaces let one configuration keep several separate states. Each workspace has its own state, so the same code can create one set of resources per environment.
The terraform workspace subcommands:
| Command | What it does |
|---|---|
terraform workspace list | List workspaces; * marks the current one |
terraform workspace show | Print the current workspace name |
terraform workspace new <name> | Create a workspace and switch to it |
terraform workspace select <name> | Switch to an existing workspace |
terraform workspace delete <name> | Delete a workspace |
Every project starts with a workspace named default. Create three more:
$ terraform workspace new dev
$ terraform workspace new stage
$ terraform workspace new prod
$ terraform workspace select prod
Switched to workspace "prod".

The current workspace name is stored in .terraform/environment:

Using the workspace name in the code
terraform.workspace holds the current workspace name. The configuration below uses it to set the name tag and to choose an instance type per environment:
resource "aws_instance" "demo_server_dipendra" {
ami = var.AMIS[var.REGION]
key_name = "kp-dipendra-bhatta-aug4"
instance_type = lookup(var.INSTANCE_TYPE, terraform.workspace, "t2.micro")
vpc_security_group_ids = [var.SECURITY_GROUP]
availability_zone = var.ZONE
tags = {
Name = "${terraform.workspace}-vm-dipendra-bhatta"
created_by = "Terraform-code"
owner = "Deependra-Bhatta"
}
}
output "instance_id" {
value = aws_instance.demo_server_dipendra.id
}
output "instance_name" {
value = terraform.workspace
}variable "REGION" {
description = "The region where resources are created"
default = "us-east-1"
type = string
}
variable "ZONE" {
description = "The availability zone for the instance"
default = "us-east-1b"
type = string
}
variable "SECURITY_GROUP" {
description = "Security group ID"
default = "sg-05694bdfc51f0d457"
type = string
}
variable "AMIS" {
description = "The AMI ID for each region"
type = map(string)
default = {
us-east-1 = "ami-0360c520857e3138f"
us-east-2 = "ami-0cfde0ea8edd312d4"
}
}
variable "INSTANCE_TYPE" {
type = map(string)
default = {
dev = "t2.micro"
stage = "t2.nano"
prod = "t2.small"
}
}providers.tf is the same as before, with region = var.REGION.
The lookup function
lookup(map, key, default) returns the value for key from map, or default if the key is not there. Here, lookup(var.INSTANCE_TYPE, terraform.workspace, "t2.micro") gives t2.small in prod and falls back to t2.micro in any workspace that is not in the map, such as default. The default argument is technically optional, but leaving it out is deprecated; without a fallback, plain indexing var.INSTANCE_TYPE[terraform.workspace] does the same thing and fails on a missing key.
Result
Running terraform apply in each workspace creates three instances from the same code, with different names and types:

Note the stage instance: it is named statge and got t2.micro, not t2.nano, because I created that workspace with a typo. statge is not a key in the map, so lookup silently used the fallback. A fallback default is convenient, but it can hide mistakes like this one.
With the local backend, each workspace's state is stored under terraform.tfstate.d/<workspace>/:

The .tfvars files in that tree are empty for now; they are the place for environment-specific values, passed with terraform apply -var-file=prod.tfvars.
terraform destroy only touches the current workspace. Destroying in the stage workspace terminated only that instance:

Without workspaces: one directory per environment
The other common approach is a directory per environment, each with its own main.tf, variables.tf, outputs.tf and terraform.tfvars, sharing code through modules:

Here variables.tf declares the variables, and each terraform.tfvars sets the actual values for that environment. Values that change often stay out of the main code.
Modules
A module is a directory of .tf files used as one unit. Modules let you define a piece of infrastructure once and reuse it, much like a function in a program.
- Root module: the
.tffiles in the directory where you run Terraform. Every configuration has one. - Child module: a module called from another module with a
moduleblock. One child module can be called many times, with different inputs. - Published module: a module loaded from a registry instead of a local path. The Terraform Registry has many public modules, and HCP Terraform and Terraform Enterprise offer private registries.
Calling a local module:
module "servers" {
source = "./app-cluster"
servers = 5
}Calling a module from the registry, pinned to a version:
module "consul" {
source = "hashicorp/consul/aws"
version = "0.0.5"
servers = 3
}Run terraform init after adding a module so Terraform can download it. For common building blocks such as a VPC, a well-maintained registry module is usually a better starting point than writing everything from scratch.
The dependency lock file
terraform init writes .terraform.lock.hcl, which records the exact provider version and its checksums:

In a team, the lock file keeps provider versions consistent. If developer A built the infrastructure with AWS provider 6.10.0 and developer B clones the repository months later, terraform init without a lock file would select the newest provider, and a different provider version can plan different changes. With the lock file committed to Git, everyone gets the same version:

To move to a newer provider on purpose, run terraform init -upgrade and commit the updated lock file.
A .gitignore for a Terraform project should contain at least:
.terraform/
*.tfstate
*.tfstate.*
*.pemCommit .terraform.lock.hcl; ignore the .terraform/ directory.
Command reference
| Command | What it does |
|---|---|
terraform -help | List all commands |
terraform init | Prepare the directory: download providers and modules, configure the backend |
terraform fmt | Rewrite .tf files in the standard style |
terraform validate | Check syntax and references |
terraform plan | Show the changes needed to match the configuration |
terraform apply | Make the changes (asks for yes) |
terraform apply -auto-approve | Apply without asking. Use only in automation or immediately after reviewing the plan |
terraform apply -refresh-only | Update the state from real infrastructure (replaces terraform refresh) |
terraform destroy | Destroy everything in the current state |
terraform output | Print output values |
terraform show | Show the current state or a saved plan |
terraform graph | Print the dependency graph in DOT format, for example terraform graph | dot -Tsvg > graph.svg with Graphviz |
terraform import | Bring an existing resource under Terraform management |
terraform force-unlock | Release a stuck state lock |
terraform workspace | Manage workspaces |
terraform state | Inspect and change the state (see below) |
terraform console | Try expressions interactively |
terraform console evaluates expressions and functions interactively before they go into code, for example to check a variable or read a file:
$ terraform console
> length(var.ZONE)
10
The terraform state subcommands:
| Command | What it does |
|---|---|
terraform state list | List resources in the state |
terraform state show <address> | Show one resource |
terraform state mv | Move or rename an item in the state |
terraform state rm | Stop managing a resource without destroying it |
terraform state pull | Print the current state, for example from S3 |
terraform state push | Overwrite the remote state with a local file (use with great care) |
terraform state replace-provider | Change the provider source recorded in the state |
Troubleshooting
The following problems came up, or nearly did, while building these examples.
| Problem | Cause | Fix |
|---|---|---|
region = us-east-1 gives an invalid reference error | Without quotes, Terraform reads it as an expression, not text | Quote strings: region = "us-east-1" |
| File provisioner cannot find the script | source = "deployapp.sh" did not match the real file name deploy_app.sh | Use the exact file name, relative to the directory where you run Terraform |
| Provisioner times out connecting over SSH | The instance had no key_name, so the key in connection did not match; or port 22 was closed | Set key_name, open SSH from your IP in the security group |
sudo cd /tmp/ fails in the script | cd is a shell built-in, so sudo cannot run it | Use plain cd /tmp; the whole script already runs through sudo |
| An environment gets the wrong instance type | Workspace created as statge; lookup fell back to the default | Check terraform workspace show; consider plain indexing so a missing key fails |
| Apply fails after switching region | AMI, availability zone and security group IDs are region-specific | Map every regional value, not only the AMI |
| Manual console change disappears on next apply | Refresh updated the state, but the configuration still differs | Add the change to the .tf files if it should stay |
| Every run reports a lock error | A crashed run left the state lock | terraform force-unlock <LOCK_ID> after confirming no run is active |
Key takeaways
planrefreshes real resources from AWS before comparing; the state file tells Terraform which objects it owns.- Keep state out of Git and in a remote backend such as S3, with versioning and locking (
use_lockfile = true). - Commit
.terraform.lock.hclso everyone uses the same provider versions. - Detect drift with
terraform plan -refresh-onlyand move manual changes back into code. - Use provisioners only when nothing else works; prefer
user_data, images or Ansible. - Workspaces give one state per environment from the same code, but defaults in
lookupcan hide typos.
Next in this series: OpenTofu.
Keep reading
- OpenTofu: Why It Exists, Installation and Migrating from Terraform
Why OpenTofu was forked from Terraform, how to install it on Ubuntu, and how to migrate an existing Terraform project with tofu init, including the lock file warning.
- Amazon EC2 Hands-On: Launch, Scale and Monitor Instances
Launch an EC2 instance and connect over SSH, then add a launch template, an Auto Scaling group, an Application Load Balancer and a CloudWatch alarm, with fixes for common errors.
- Ansible Templates, Handlers, Roles and Vault
Push chrony NTP config with templates, edit sshd_config with lineinfile, restart services only on change with handlers, then organize it all into a role and encrypt secrets with Vault.