WS User Data with Multiple Files using Template function
I want to create multiple aws ec2 instances resources (NOTE: 4 instances, The example only shows 2) with, a different set of configurations, a core user_data script and a custom user-data scripts for each type of the aws instances to also be run via user_data. I used this provided terraform solution. AWS User Data with Multiple Files using Templatefile
Based on the configuration’s files below, the common.sh is being copied and executed on both instances. However, the configure.sh is being copied to both instances’ but it’s only executed on the GritfyWeb server.
Please advise.
main.tf
data "cloudinit_config" "example" {
for_each = var.servers
part {
filename = "common.sh"
content_type = "text/x-shellscript"
content = templatefile("${path.cwd}/scripts/common.sh", {
})
}
part {
filename = "configure.sh"
content_type = "text/x-shellscript"
#content = templatefile("${path.cwd}/scripts/each.value.appl_name}", {
content = templatefile("/home/ec2-user/stage2/scripts/${each.value.appl_name}", {
})
}
}
resource "aws_instance" "server" {
for_each = var.servers
ami = each.value.ami_id
instance_type = each.value.instance_type
subnet_id = each.value.subnet_id
security_groups = [ "sg-04b403faf33f968ad" ]
key_name = var.key_name
user_data = data.cloudinit_config.example[each.key].rendered
tags = {
Name = "${each.value.environment}-server"
}
}
variables.tf
variable "servers" {
description = "Map of servers names to configuration."
type = map(any)
default = {
client-webapp = {
ami_id = "ami-06640050dc3f556bb",
instance_type = "t2.micro",
subnet_id = "subnet-02ef6d33efadfef5a"
environment = "GritfyApp"
appl_name = "GritfyApp-test.tpl"
},
internal-webapp = {
ami_id = "ami-057b76da478f6105c",
instance_type = "t3.micro",
subnet_id = "subnet-02ef6d33efadfef5a"
environment = "GrityWeb-dev"
appl_name = "GrityWeb-dev.tpl"
}
}
}
variable "aws_region" {
description = "AWS region for all resources."
type = string
default = "us-east-2"
}
variable "key_name" {
description = "Key Name"
type = string
default = "em-test"
}
variable "security_group_id" {
description = "ID of existing security group whose rules we will manage"
type = string
default = "sg-04b403faf33f968ad"
}
user_data_scripts
ls scripts/
scripts/
common.sh GritfyApp-test.tpl GrityWeb-dev.tpl