Run multiple userdata scripts on EC2 instance | AWS

I have multiple powershell scripts which i need to run in ec2 userdata.

data “template_file” “userdata” {
template = file(“userdata.ps1”)
}
data “template_file” “userdata1” {
template = file(“userdata1.ps1”)
}
data “template_cloudinit_config” “cloudinit-example” {
gzip = false
base64_encode = false
part {
filename = “userdata.ps1”
content_type = “text/cloud-config”
content = data.template_file.userdata.rendered
}
part {
filename = “userdata1.ps1”
content_type = “text/cloud-config”
content = data.template_file.userdata1.rendered
}
}
resource “aws_instance” “ec2” {
ami = “ami-0e484c84e6d59f3a3”
instance_type = “t2.medium”
key_name = “cp-dev-GA”
iam_instance_profile = “admin-access-test”
user_data = data.template_cloudinit_config.cloudinit-example.rendered
}

none of the powershell scripts gets executed. Anything i am missing here

did you find answer to this question?

you could try to use something like

provisioner "file" {
    source = "userdata.ps1"
    destination = "c:\\userdata.ps1"
  }
provisioner "remote-exec" {
    inline = [
      "powershell c:\\userdata.ps1",
      
    ]
    on_failure = "continue"
  }

provisioner “file” will copy the file to your windows instance and remote-exec will execute it on the instance. Hope that helps.

You can run multiple scripts using the join function.

user_data = join(“\n”, [data.template_file.userdata.rendered, data.template_file.userdata1.rendered])

1 Like

This works as expected, but is there a way to ignore null values? As in my case I use first template file as a common user data within module and second is a variable as var.user_data, to which, user_data can be passed when the module is called and this works fine when a value is passed to user_data, but it does not work if user_data is null. I get the following:

  31:   user_data                   = join("\n", [templatefile("../../files/${var.user_data_file}", {
  32:     hostname = "${var.instance_name_tag}-${format("%02d", count.index + 1)}"
  33:   }), var.user_data])
    |----------------
    |xxxx
    |xxxx
    |xxxx
    | var.user_data is null

Invalid value for "lists" parameter: element 1 is null; cannot concatenate
null values.

Am I doing this incorrectly?