Skip to content

Terraform with AWS

Introduction to AWS Provider

The AWS (Amazon Web Services) provider is used to interact with the many resources supported by AWS. It needs to be configured with proper credentials before it can be used.

Provider Configuration

provider "aws" {
  region = "us-west-2"
}

Authentication

There are several ways to authenticate:

  1. Static credentials
  2. Environment variables
  3. Shared credentials file
  4. EC2 Instance Profile

Example using environment variables:

provider "aws" {
  region     = "us-west-2"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

Common AWS Resources

  1. EC2 Instances
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
  1. S3 Buckets
resource "aws_s3_bucket" "b" {
  bucket = "my-tf-test-bucket"
}
  1. VPCs and Subnets
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"
}

Best Practices

  1. Use IAM roles for EC2 instances instead of hardcoding credentials
  2. Implement least privilege principle for IAM policies
  3. Use Terraform workspaces or separate state files for different environments
  4. Utilize AWS-specific modules from the Terraform Registry

Advanced Topics

  1. Working with Auto Scaling Groups
  2. Managing RDS instances
  3. Setting up Elastic Load Balancers
  4. Implementing CloudFront distributions

Remember to always refer to the official Terraform AWS provider documentation for the most up-to-date information on available resources and their arguments.