TerraformIntermediate

How to Write Your First Terraform Script for AWS Infrastructure

Admin
9 min read

TL;DR

A step-by-step guide to getting started with Infrastructure as Code using Terraform to manage AWS resources.

How to Write Your First Terraform Script for AWS Infrastructure

Executive Summary

Your first Terraform configuration teaches you the whole model in miniature: declare resources in a file, preview the changes with plan, create them with apply, and let Terraform track everything in state. This guide walks through a complete first script for AWS — a VPC and a public subnet — explaining each concept as it appears: providers, resources, variables, outputs, and state. After reading it, you should be able to write, run, modify, and destroy a small AWS configuration with confidence, using the safety habits worth adopting while the stakes are low.

Why This Matters

The first configuration is where habits form, and habits formed on a tutorial have a way of surviving into production. A first script that hard-codes credentials teaches a pattern that later leaks. A first script run against local state teaches a workflow that breaks the day a colleague needs to collaborate. Conversely, a first script that pins the provider, takes inputs as variables, exposes results as outputs, and runs plan before apply scales directly into real work — the files get bigger, but the shape stays the same. Treat this exercise as building the template your future projects start from, not as a disposable demo.

Core Concepts

The Moving Parts

Five concepts cover everything in a first script:

  • Provider: the plug-in that connects Terraform to a platform. Here, the AWS provider.
  • Resource: one piece of infrastructure, such as aws_vpc or aws_subnet, declared with a type and a name.
  • State: the file where Terraform records the real resources it created, so later runs know what already exists.
  • Variable: an input to the configuration, so the same code can build different environments.
  • Output: a value the configuration returns after apply, such as the ID of the VPC it created.
  • The workflow tying them together is always the same loop: terraform init prepares the working directory, terraform plan previews changes, terraform apply makes them, and terraform destroy removes everything when you are done.

    Prerequisites

    You need three things before starting:

  • Terraform CLI, installed from HashiCorp's packages or a package manager such as Homebrew, apt, or Chocolatey.
  • An AWS account with permissions to create VPC resources — for learning, an account you can empty afterwards.
  • AWS credentials configured on your machine, typically via the AWS CLI's aws configure, environment variables, or an SSO login. Terraform's AWS provider finds them through the standard credential chain; you never paste keys into a .tf file.
  • The First Configuration

    Create a directory and a main.tf containing a provider and two resources — a VPC, and a subnet inside it that references the VPC's ID:

    # Configure AWS Provider
    provider "aws" {
      region = "us-west-2"
    }
    
    # Create VPC
    resource "aws_vpc" "main" {
      cidr_block = "10.0.0.0/16"
    
      tags = {
        Name        = "main"
        Environment = "production"
      }
    }
    
    # Create Subnet
    resource "aws_subnet" "public" {
      vpc_id     = aws_vpc.main.id
      cidr_block = "10.0.1.0/24"
    
      tags = {
        Name = "public"
      }
    }

    The reference aws_vpc.main.id is the important idea. Terraform sees that the subnet depends on a value only the VPC can provide, so it creates the VPC first and the subnet second — and destroys them in reverse order. You never write sequencing code; the dependency graph falls out of the references.

    In practice you would also pin the provider version in a terraform block, so the configuration behaves identically on every machine:

    terraform {
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }

    Running It

    terraform init     # download the provider, set up the working directory
    terraform plan     # show what will be created, change nothing
    terraform apply    # create the resources after you confirm the plan

    Read the plan output before confirming. It lists every resource to be added, changed, or destroyed, and the attribute values Terraform already knows. After apply, Terraform writes terraform.tfstate in the directory — that file is the record linking aws_vpc.main to a real VPC ID, and it is why a second terraform plan correctly reports no changes. Change the subnet's CIDR in the file, plan again, and you will see Terraform propose replacing the subnet, because a subnet's CIDR block cannot be modified in place. That destroy-and-recreate behaviour, visible in the plan before anything happens, is the core safety property of the tool.

    Variables and Outputs

    Hard-coded values are fine for a first run and wrong for a second environment. Promote them to variables:

    variable "region" {
      description = "AWS region to deploy into"
      type        = string
      default     = "us-west-2"
    }
    
    variable "vpc_cidr" {
      description = "CIDR block for the VPC"
      type        = string
      default     = "10.0.0.0/16"
    }
    
    provider "aws" {
      region = var.region
    }

    Outputs surface the values other people — or other configurations — will need:

    output "vpc_id" {
      description = "ID of the created VPC"
      value       = aws_vpc.main.id
    }
    
    output "public_subnet_id" {
      description = "ID of the public subnet"
      value       = aws_subnet.public.id
    }

    Run terraform output any time to read them back from state. A third mechanism, locals, names a computed expression once — a standard tag set, for example — and reuses it across resources.

    State: Handle With Care From Day One

    State commands you will meet early: terraform state list shows everything Terraform manages, terraform state show aws_vpc.main shows one resource's recorded attributes, and terraform state mv renames a resource in state when you refactor its label. Two rules matter more than any command. First, never edit the state file by hand. Second, the moment anyone else needs to run this configuration, move state out of the directory into a remote backend (for AWS, an S3 bucket with locking) — a state file on one laptop is a single point of failure and a collaboration blocker. State also contains resource attributes in plain text, so treat the file as sensitive even in a learning project.

    Common First-Script Problems

  • Authentication errors mean the provider found no credentials or the wrong ones. Confirm with aws sts get-caller-identity, and check that the credentials you configured are the ones in the shell running Terraform.
  • State lock errors mean a previous run was interrupted or another run is in progress. Confirm nothing is running before considering terraform force-unlock; on a solo learning project with local state this is rare, but the habit of checking first is the point.
  • Plan shows unexpected replacements usually means an attribute that cannot change in place was edited — a CIDR block, an availability zone, a name the provider treats as immutable. The plan is telling the truth; decide whether the replacement is acceptable before applying.
  • Syntax and reference errors are caught by terraform validate and by plan itself. Run terraform fmt to normalise formatting; most editors also flag HCL errors as you type.
  • Security Basics Worth Starting With

    Three practices cost nothing at this scale and everything if retrofitted later. Keep credentials out of code — use the credential chain described above. Encrypt state once it moves to a remote backend, and restrict who can read it. And apply least privilege to the credentials Terraform runs with: a learning project needs VPC permissions, not administrator access to the whole account.

    Decision Framework

    SituationRecommendation
    Just learning, solo, disposable accountLocal state, one file, hard-coded region is acceptable — destroy everything afterwards
    Configuration will be reused or sharedVariables for inputs, outputs for IDs, provider pinned, state moved to a remote backend
    Need compute or storage nextAdd aws_instance or aws_s3_bucket resources the same way; look up AMIs with a data source instead of hard-coding an ID
    Same layout needed in several environmentsKeep one configuration, vary it with variable files per environment
    Script is growing past a few hundred linesSplit into main.tf, variables.tf, outputs.tf, then extract repeated patterns into modules
    Unsure whether a change is safeRun plan and read the replacement lines; never apply a plan you have not read

    Implementation Checklist

  • [ ] Terraform CLI installed and terraform version runs
  • [ ] AWS credentials resolve through the standard chain; no keys appear in any .tf file
  • [ ] Provider version is pinned in a terraform block
  • [ ] terraform init, plan, and apply complete; a second plan reports no changes
  • [ ] Inputs are variables with types and descriptions; created IDs are exposed as outputs
  • [ ] terraform fmt and terraform validate pass
  • [ ] State file is kept out of source control and treated as sensitive
  • [ ] terraform destroy has been run at least once, so cleanup is a known quantity, not a fear
  • Trade-offs

    A first script hides the costs that arrive with scale. Local state is effortless now and a liability later; the migration to a remote backend is easy but must actually happen. Terraform also only manages what it creates — it will not adopt the resources already in your account until you import them, and it cannot see changes made in the console except by refreshing state at plan time, which is why console edits and Terraform fight each other. Finally, the apply model is all-or-nothing per run: a failure halfway leaves some resources created and recorded in state, which is recoverable but surprises beginners who expected a transaction.

    When Not to Use

  • One resource, one time, never again: the AWS Console or a single CLI command is faster than a configuration you must store state for.
  • Configuring software inside an instance — packages, users, application files: that is Ansible's or a user-data script's job; Terraform should hand the instance its bootstrap and stop.
  • Highly dynamic, short-lived resources such as per-request test environments created by application code: use the AWS SDK from the application instead of shelling out to Terraform.
  • You need a general-purpose programming language for complex logic: look at Pulumi or AWS CDK rather than forcing loops and conditionals into HCL.
  • Conclusion

    A VPC, a subnet, and the init-plan-apply loop contain the entire Terraform model: declarative resources, a dependency graph built from references, and state recording the result. Learn it with the safety habits already in place — pinned providers, variables and outputs, no credentials in code, plans always read — and the step from this script to production configurations is one of size, not of kind.

    References

  • Terraform Documentation
  • AWS Provider Documentation
  • Terraform Best Practices
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.