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:
- Static credentials
- Environment variables
- Shared credentials file
- 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
- EC2 Instances
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
- S3 Buckets
resource "aws_s3_bucket" "b" {
bucket = "my-tf-test-bucket"
}
- 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
- Use IAM roles for EC2 instances instead of hardcoding credentials
- Implement least privilege principle for IAM policies
- Use Terraform workspaces or separate state files for different environments
- Utilize AWS-specific modules from the Terraform Registry
Advanced Topics
- Working with Auto Scaling Groups
- Managing RDS instances
- Setting up Elastic Load Balancers
- 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.