Infrastructure as Code (IaC) tool that lets you define cloud resources in human-readable configuration files
- provider: plugin that allows Terraform to interact with cloud platforms (AWS, Azure, GCP)
- resource: infrastructure object you want to manage (EC2 instance, S3 bucket)
- state: Terraform's record of all managed infrastructure
- module: directory with
.tffiles- enables reusability
- 2 types:
- root module: directory where
terraform initandterraform applyis run, the entry point - child module: any module referenced from another modul
- root module: directory where
# Provider configuration
provider "aws" {
region = "us-west-2"
}
# Resource example
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}- install terraform
- export provider credential variables: e.g.
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY - run
terraform initin project's root directory - create terraform files (
.tfextension) - run
terraform plan -var-file="terraform.tfvars" -out=tfplan - run
terraform apply tfplan
terraform init: initialize working directory, download providersterraform plan: preview changes before applyingterraform plan -var-file="terraform.tfvars" -out=tfplan-var-file="terraform.tfvars": loads variable values from a file namedterraform.tfvars-out=tfplan: seves the plan to a file namedtfplan, apply it withterraform apply tfplan
terraform apply: apply changes to create/modify resourcesterraform destroy: remove all resources managed by Terraformterraform fmt: format code per HCL standardsterraform validate: validate configuration filesterraform output ec2_public_ip: print terraform variables
terraform apply -var-file="terraform.tfvars"you can destroy resources with:
terraform apply -destroy -target=aws_instance.app_instance -auto-approve
terraform apply -auto-approve- version control your terraform code
- use variables for reusable values
- organize code into modules
- always review plan before applying
- store state files securely
- use workspaces for different environments
aws_instance: EC2 instanceaws_vpc: Virtual Private Cloudaws_subnet: subnet within a VPCaws_security_group: security group for EC2 instancesaws_s3_bucket: S3 bucketaws_iam_role: Identity and Access Management role