Authenticating Terraform to AWS using IAM user

In my previous note, I mentioned the steps to authenticate Azure. Here in this note, I’ll list the steps to authenticate to AWS. The approach will be quite similar -we create an IAM user with appropriate policies, create/update terraform configuration files, and run the configuration files.

Step 1: Create an IAM user
To work with resources in AWS, we need appropriate access -read/modify. In this case, we need an IAM user with programmatic access permission (full access) to S3. Please attach appropriate policy (AmazonS3FullAccess) and store the Access key ID and Secret Access key securely. We need those in the next step.

Terraform-AWS-Image2

Step 2: Update terraform configuration files
I followed the instructions here to create the AWS provider usage, authentication, and the instructions to create an S3 bucket were provided here. As stated in my previous note, the secured credentials (access_key and secret_key) are stored in a .tfvars file. This .tfvars file should not be added to the repository (update .gitignore accordingly).


terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "3.13.0"
}
}
}
provider "aws" {
region = var.region
access_key = var.access_key
secret_key = var.secret_key
}
resource "random_integer" "rand_int" {
min = 10000
max = 99999
}
resource "aws_s3_bucket" "aws-b1" {
bucket = "${var.bucket_name}${random_integer.rand_int.result}"
acl = "private"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}

view raw

main-aws.tf

hosted with ❤ by GitHub


variable "region" {
description = "The region where to provision resources"
type = string
}
variable "access_key" {
description = "The access_key that belongs to the IAM user"
type = string
}
variable "secret_key" {
description = "The secret_key that belongs to the IAM user"
type = string
}
variable "bucket_name" {
description = "The name of S3 bucket"
default = "terraform-bucket"
type = string
}

view raw

variable-aws.tf

hosted with ❤ by GitHub

Step 3: Execute terraform trial commands (init -> plan -> apply)

Terraform-AWS-Image4

After terraform apply I was able to verify that an S3 bucket was created under my AWS profile using Terraform configuration files.
Terraform-AWS-Image3

Conclusion:
The purpose of this note was to authenticate Terraform, and we saw that with the creation of the bucket in AWS S3.
image of newly created bucket

Other ideas to explore:
Is this the best method to authenticate Terraform?
How to provision an EC2 instance in AWS using Terraform?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s