Issue
I'm trying to create my first module and believe I've ended up confusing myself somewhere.
I am testing a variable called ami_key
. I have set a default value in my variables.tf
file as:
variable "ami_key" {
type = string
description = "Key Pair"
default = "key-default"
}
But in my module I defined it as:
module "compute" {
source = "./module/dev"
instance_type = "t2.micro"
name_tag = "VM"
env = "dev"
number_of_instances = 1
ami = "ami-0a3c3a20c09d6f377"
aws_region = "us-east-1"
ami_key = "key"
}
Now my basic understanding is that the ami_key
defined in my module compute
will override the default value in variables.tf
, but that doesn't happen when I run terraform plan
, the key is set to the variables.tf
default value:
+ key_name = "key-default"
What am I missing or doing wrong here as I expect the output to be:?
+ key_name = "key"
My structure of my directory is:
Terraform_EC2
|-main.tf
|-provider.tf
|-variables.tf
|-output.tf
|-module
|-dev
|-compute.tf
main.tf
provider "aws" {
access_key = var.aws_access_key_id
secret_key = var.aws_secret_access_key
region = var.aws_region
}
resource "aws_instance" "aws_vm" {
ami = var.ami
instance_type = var.instance_type
count = var.number_of_instances
key_name = var.ami_key
tags = {
ec2_dev_name = "${var.name_tag}${var.env}${count.index}"
}
}
module/dev/compute.tf
module "compute" {
source = "./module/dev"
instance_type = "t2.micro"
name_tag = "VM"
env = "dev"
number_of_instances = 1
ami = "ami-0a3c3a20c09d6f377"
aws_region = "us-east-1"
ami_key = "key"
}
variables.tf
variable "instance_type" {
type = string
description = "Instance Type"
default = "t2.micro"
}
variable "name_tag" {
type = string
description = "Name"
default = "VM"
}
variable "env" {
type = string
description = "Environment of EC2"
default = "dev"
}
variable "number_of_instances" {
type = number
description = "Instances"
default = 1
}
variable "ami" {
type = string
description = "AMI ID"
default = "ami-0a3c3a20c09d6f377"
}
variable "aws_region" {
type = string
description = "US East 1"
default = "us-east-1"
}
variable "ami_key" {
type = string
description = "Key Pair"
default = "key-default"
}
variable "aws_access_key_id" {}
variable "aws_secret_access_key" {}
providers.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.27.0"
}
}
}
Solution
It appears your understanding of modules and their paths is a bit mixed up/incorrect. Below is how you could keep your files for use of the module:
|-module
|ec2
|-main.tf
|-provider.tf
|-variables.tf
|-output.tf
|-dev
compute.tf
Within compute.tf, you can use the ec2 module like below:
module "compute" {
source = "../module/ec2"
instance_type = "t2.micro"
name_tag = "VM"
env = "dev"
number_of_instances = 1
ami = "ami-0a3c3a20c09d6f377"
aws_region = "us-east-1"
ami_key = "key"
}
You run your terraform apply from the dev folder. Let us know if you face any issues after this.
Answered By - Technowise Answer Checked By - Marilyn (WPSolving Volunteer)