Deploy EC2 instance with Terraform
Make sure you do this setup first:
-
Install Terraform via Homebrew:
# install brew tap hashicorp/tap brew install hashicorp/tap/terraform # verify terraform -help
Configure the project:
source configure.sh
Format configuration:
terraform fmt
Validate configuration:
terraform validate
Preview infrastructure:
terraform plan -out terraform.plan
Create infrastructure:
terraform apply terraform.plan
Check state:
terraform show
Check that you can browse the nginx
default site:
instance_public_ip=$(terraform output -json | jq -r '.instance_public_ip.value')
open http://$instance_public_ip
Connect to instance via SSH:
key="aws-ec2-key"
instance_public_ip=$(terraform output -json | jq -r '.instance_public_ip.value')
ssh -i ~/.ssh/$key ec2-user@$instance_public_ip
Review the changes and verify the execution plan:
terraform plan -destroy
Delete the resources:
terraform destroy
# create main.tf
cat << 'EOF' > main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
# AWS config
# leave empty to read the settings from the AWS CLI configuration
provider "aws" {}
EOF
# initialize the project
# this will download provider plugin into .terraform subdir
terraform init