Terraform on AWS :: Get Started
Purely hands-on, no detailed instructions.
Table of Contents
Install Terraform 1 2
$ wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
$ echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
$ sudo apt update && sudo apt install terraform
$ terraform -help
$ terraform -install-autocomplete
Install AWS CLI 3
$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ aws --version
$ which aws
$ ls -l /usr/local/bin/aws
AWS IAM user credentials
$ export AWS_ACCESS_KEY_ID=AKABC************123
$ export AWS_SECRET_ACCESS_KEY=XYZ**********************************789
Terraform configuration
$ mkdir terraform-on-aws
$ cd terraform-on-aws
$ touch terraform.tf main.tf variables.tf outputs.tf
Here’s a basic, simple, and complete example:
terraform {
required_version = ">= 1.3.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 4.37.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_instance" "app_server" {
ami = "ami-0bba69335379e17f8"
instance_type = "t2.micro"
tags = {
Name = var.instance_name
}
}
variable "instance_name" {
description = "Value of the Name tag for the EC2 instance"
type = string
default = "ExampleAppServerInstance"
}
output "instance_id" {
description = "ID of the EC2 instance"
value = aws_instance.app_server.id
}
output "instance_public_ip" {
description = "Public IP address of the EC2 instance"
value = aws_instance.app_server.public_ip
}
Initialize the directory
$ terraform init
Format and validate the configuration
$ terraform fmt
$ terraform validate
Create infrastructure
$ terraform apply
Inspect state
$ terraform show
$ terraform state list
Inspect output values
$ terraform output
Destroy infrastructure
$ terraform destroy
Read other posts