I'd like to dynamically pass the variable count.index
from an instance resource to a cloud_init data block. This index aims to set the instance hostname.
Here is the data block :
data "template_file" "script" {
template = "${file("${path.module}/templates/init.yml")}"
vars = {
username = "${var.username}"
private_key = "${var.ssh_private_key}"
public_key = "${var.ssh_public_key}"
aws_access_key_id = "${var.aws_access_key_id}"
aws_secret_access_key = "${var.aws_secret_access_key}"
aws_session_token = "${var.aws_session_token}"
aws_region = "${var.aws_region}"
ips = "10.0.1.0/24"
dbpasswd = "abc123"
hname = "${var.hostname}"
}
}
data "template_cloudinit_config" "config" {
gzip = true
base64_encode = true
part {
content_type = "text/cloud-config"
content = "${data.template_file.script.rendered}"
}
}
And here the resource :
resource "aws_instance" "controller" {
count = var.count_clt
ami = data.aws_ami.centos.id
instance_type = var.itype
key_name = var.keyname
user_data = var.cloudinit_config
network_interface {
network_interface_id = aws_network_interface.controller.id
device_index = 0
}
tags = {
Name ="egu-${var.hostname_prefix}-${count.index + 1}"
}
}
I'm wondering whether it's some how possible to pass variable at line user_data
which actually contains data.template_cloudinit_config.config.rendered
Thanks.
I figured out.
I generate n template_cloudinit_config.config
data and pick up one with count.index
in the resource.
Here is the code :
data "template_file" "script" {
template = "${file("${path.module}/templates/init.yml")}"
count = var.count_clt
vars = {
username = "${var.username}"
private_key = "${var.ssh_private_key}"
public_key = "${var.ssh_public_key}"
aws_access_key_id = "${var.aws_access_key_id}"
aws_secret_access_key = "${var.aws_secret_access_key}"
aws_session_token = "${var.aws_session_token}"
aws_region = "${var.aws_region}"
ips = "10.0.1.0/24"
dbpasswd = "abc123"
hname = "${var.hostname_prefix}-${count.index + 1}"
}
}
data "template_cloudinit_config" "config" {
gzip = true
base64_encode = true
count = var.count_clt
part {
content_type = "text/cloud-config"
content = element(data.template_file.script.*.rendered, count.index)
}
}
resource "aws_instance" "controller" {
count = var.count_clt
ami = data.aws_ami.centos.id
instance_type = var.itype
key_name = var.keyname
user_data = element(data.template_cloudinit_config.config.*.rendered, count.index)
network_interface {
network_interface_id = aws_network_interface.controller[count.index].id
device_index = 0
}
tags = {
Name = element(local.hostsnames,count.index)
}
}
Thanks for having tried to help.