terraform-aws-modules / terraform-aws-ec2-instance

Terraform module to create AWS EC2 instance(s) resources 🇺🇦
https://registry.terraform.io/modules/terraform-aws-modules/ec2-instance/aws
Apache License 2.0
754 stars 1.87k forks source link

feat: Add wrapper #270

Closed SlavaSubotskiy closed 2 years ago

SlavaSubotskiy commented 2 years ago

Description

A single module wrapper pattern, which allows managing several copies of a module in places where using the native Terraform 0.13+ for_each feature is not feasible (e.g., with Terragrunt).

Inspired by https://github.com/terraform-aws-modules/terraform-aws-s3-bucket/tree/master/wrappers

Motivation and Context

We are using Terragrunt to launch multiple EC2 instances with similar configuration. To keep DRY, we had to implement a wrapper module with for_each implementation. The only difference between this wrapper and the https://github.com/terraform-aws-modules/terraform-aws-s3-bucket/tree/master/wrappers, is that the defaults variable was added, to support more DRY configurations in case of similar instances configuration(see example in the README) The main.tf was generated by a dummy bash script:

#!/usr/bin/env bash

VARS=$(cat variables.tf| grep -e '^variable ' -e '  default     =' | perl -p -e 's/variable "//g;s/" {\n//;s/  default     = / /g')

# Get the longest variable
THE_LONGEST_VAR_SIZE=0
while read -r line;
do
   var="$(echo ${line} | awk '{print $1}')"
   VAR_SIZE=${#var}
   if [ ${VAR_SIZE} -gt ${THE_LONGEST_VAR_SIZE} ]; then THE_LONGEST_VAR_SIZE=${VAR_SIZE}; fi
done < <(echo "${VARS}")

# Generate wrapper content

cat << EOF
module "wrapper" {
  source = "../"

  for_each = var.items

EOF

while read -r line;
do
   var="$(echo ${line} | awk '{print $1}')"
   value="$(echo ${line} | awk '{print $2}')"
   VAR_SIZE=${#var}
   SPACES=$((${THE_LONGEST_VAR_SIZE} - ${VAR_SIZE}))

   echo "  ${var} $(perl -E "print ' ' x ${SPACES}")= try(each.value.${var}, var.defaults.${var}, ${value})"

done < <(echo "${VARS}")

echo '}'

Breaking Changes

No breaking changes introduced

How Has This Been Tested?

antonbabenko commented 2 years ago

Very good timing :) I have just started implementing this as a pre-commit-hook in https://github.com/antonbabenko/pre-commit-terraform/issues/202 an hour ago.

I will extend it with the support for defaults like you propose.

Let's keep this PR open for a while.

antonbabenko commented 2 years ago

This issue has been resolved in version 3.6.0 :tada:

github-actions[bot] commented 1 year ago

I'm going to lock this pull request because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues. If you have found a problem that seems related to this change, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.