AWS Credentials
ways
Great 🎉 You’re on the right track. Let’s break it down piece by piece:
check in 4rd stwp
1. Your S3 Bucket Resource
resource "aws_s3_bucket" "this" {
bucket = var.bucket_name
tags = {
Environment = var.environment
ManagedBy = "Terraform"
}
}bucket = var.bucket_name→ the bucket name will come from a variable calledbucket_name.It’s not hardcoded here — you’ll define it in
variables.tfand pass it throughenvironments/dev.tfvars(orstage.tfvars,prod.tfvars).This makes it customizable per environment.
Example in environments/dev.tfvars:
bucket_name = "mycompany-dev-bucket-1234"
environment = "dev"In environments/prod.tfvars:
bucket_name = "mycompany-prod-bucket-1234"
environment = "prod"2. Lifecycle Rule (Compliance Example)
resource "aws_s3_bucket_lifecycle_configuration" "this" {
bucket = aws_s3_bucket.this.id
rule {
id = "expire_old_objects"
status = "Enabled"
expiration {
days = 365
}
}
}This adds a lifecycle rule → automatically deletes objects older than 365 days.
Enterprises use this for cost optimization and compliance.
You can add multiple rules (e.g., transition to Glacier after 90 days, delete after 1 year).
3. AWS Authentication
Since you already ran:
aws configureTerraform will automatically pick up credentials from your AWS CLI profile:
~/.aws/credentials(contains Access Key + Secret Key)~/.aws/config(contains region, output format)
✅ So you don’t need to hardcode credentials in Terraform. Terraform’s AWS provider automatically looks for them in this order:
Environment variables (
AWS_ACCESS_KEY_ID, etc.)Shared credentials file (
~/.aws/credentials)AWS CLI config (
~/.aws/config)EC2/ECS instance roles (if running inside AWS)
That means your setup is secure and enterprise-friendly. 🚀
4. Custom Variables
You can add any variable you want in variables.tf and override them in *.tfvars.
Example variables.tf:
variable "bucket_name" {
description = "The name of the S3 bucket"
type = string
}
variable "environment" {
description = "Environment name (dev/stage/prod)"
type = string
}Example dev.tfvars:
bucket_name = "mycompany-dev-bucket-1234"
environment = "dev"Then run:
terraform plan -var-file=environments/dev.tfvars
terraform apply -var-file=environments/dev.tfvars✅ So to answer your exact questions:
What is bucket name here? → It comes from
var.bucket_name, defined invariables.tfand set inenvironments/dev.tfvars(or stage/prod).Do I need to pass credentials? → No, Terraform will use the AWS CLI credentials you configured via
aws configure.What about custom variables? → You define them in
variables.tf, and override values per environment indev.tfvars,stage.tfvars,prod.tfvars.
👉 Do you want me to now show you the exact working code for each file in your structure (with variables.tf, dev.tfvars, main.tf calling the module, etc.) so you can just terraform init && terraform apply?
Last updated