Skip to content

Instantly share code, notes, and snippets.

@jwatson3d
Last active August 13, 2022 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwatson3d/7f977da0c1db9c4ed1c3c75711081e03 to your computer and use it in GitHub Desktop.
Save jwatson3d/7f977da0c1db9c4ed1c3c75711081e03 to your computer and use it in GitHub Desktop.
A simple Bash script to scaffold a new Terraform project using HCL syntax.
#!/bin/bash
# default project name to 'test' unless specified
PROJ_NAME=${1:-test}
echo -e "Using PROJ_NAME '${PROJ_NAME}'\n"
# pause to allow inspection
echo "Press any key to proceed or Ctl+C to quit"
read -n 1 -s
mkdir ${PROJ_NAME} && cd ${PROJ_NAME}
cat << README > README.md
# ${PROJ_NAME} - A Terraform Project
README
cat << DATA > data.tf
# lookup the identity info for the user account running this plan
data "aws_caller_identity" "current" {}
DATA
cat << MAIN > main.tf
# random allows you to create unique resource names
resource "random_id" "random" {
byte_length = 2
}
MAIN
cat << PROVIDER > providers.tf
terraform {
required_version = "~> 1.2.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.1.0"
}
}
}
provider "aws" {
region = var.region
}
PROVIDER
cat << VARS > variables.tf
locals {
caller_arn = data.aws_caller_identity.current.arn
user_name = split("/", local.caller_arn)[length(split("/", local.caller_arn)) - 1]
standard_tags = {
Environment = var.env_name
Owner = local.user_name
Product = var.product_name
Service = var.service_name
}
}
variable "env_name" {
description = "The environment where this infrastructure will be provisioned"
type = string
default = "dev"
validation {
condition = contains(["local", "dev", "test", "stage", "prod"], var.env_name)
error_message = "Valid values for env_name are (local, dev, test, stage, prod)."
}
}
variable "product_name" {
description = "The product this infra is supporting"
}
variable "region" {
description = "AWS region"
type = string
}
variable "service_name" {
description = "The product this infra is supporting"
}
variable "standard_tags" {
description = "Standard tags to apply to all resources"
type = map(any)
default = null
}
VARS
cat << OUTS > outputs.tf
output "caller_arn" {
value = data.aws_caller_identity.current.arn
}
output "caller_user" {
value = local.user_name
}
OUTS
cat << AUTOS > terraform.auto.tfvars
env_name = "dev"
product_name = "MyProduct"
region = "us-east-2"
service_name = "MyService"
AUTOS
echo -e "\nSuccess!! '${PROJ_NAME}' has been scaffolded with the following files:\n"
ls -la
echo -e "\nUse 'code .' to launch Visual Studio Code and view/edit this project"
echo -e "\nUse 'terraform init' to initialize the Terraform providers"
echo -e "\nUse 'terraform plan' to see what this project will do"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment