How Do You Write a Terraform Module in AWS?

Problem scenario
You want to write a Terraform module in AWS. What do you do?

Solution
You will use the keyword "module" in a .tf file, and you will use either "terraform init" or "terraform get" to install the module. The directions below were adapted from https://www.howtoforge.com/how-to-create-a-terraform-module/.

Prerequisite
You need to have Terraform installed; if you need assistance, see this posting.

Procedures

  1. On the Linux server with Terraform, go to a directory where you can place some .tf files. The user's home directory may be acceptable.
  2. Create a file called main.tf with this as the content:

provider "aws" {
region = var.region
access_key = var.access_key
secret_key = var.secret_key
}

module "contint_s3_bucket" {
source = "./submod"
bucket_name = var.bucket_name

tags = {
Terraform = "true"
Environment = "dev"
}
}

  1. Create a file called variables.tf with this as the content:

variable "access_key" {
description = "Insert an access key here"
}
variable "secret_key" {
description = "Put the secret access key that corresponds to the Access Key above"
}
variable "region" {
description = "AWS has different regions, i.e., us-west-2, us-east-1. Insert one here"
}
variable "bucket_name" {
description = "This is a Required field. Enter a name that will be unique in S3"
type = string
default = "test-bucket-contint-delete"
}

  1. Create a file called terraform.tfvars with this as the content:

region = "us-west-1"
access_key = "123somestring"
secret_key = "ZYX987/variousletters"

  1. Create a directory for the modules called submod: mkdir submod
  2. Change directories to be in this new directory named submod.
  3. Create a file called main.tf with this as the content (this was taken from https://www.howtoforge.com/how-to-create-a-terraform-module/):

resource "aws_s3_bucket" "s3_bucket" {
bucket = var.bucket_name
acl = "public-read"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::${var.bucket_name}/"
]
}
]
}
EOF
website {
index_document = "index.html"
error_document = "error.html"
}
tags = var.tags
}

  1. Create a file called variables.tf with this as the content:

variable "bucket_name" {
description = "Each s3 bucket must have a unique name (among every bucket regardless of what region it is in)."
type = string
}

variable "tags" {
description = "A bucket can have tags; that is what this variable does."
type = map(string)
default = {}
}

Leave a comment

Your email address will not be published. Required fields are marked *