TerraformUser data is commonly used in launch configuration to run scripts during instance initialization. Launch configuration is usually used along with auto scaling groups to launch instances with similar instance settings. Userdata can be templatized in terraform. Templatizing helps in adding dynamic values to the user data scripts. In the userdata template file refer template variables using ${variable_name} . These variable values can be populated in the resource “template_file” vars option.


Template file example: app_install.tpl


apt-get update
apt-get install --yes ${application}

Resource Template file

resource "template_file" "user_data" {
  template = "app_install.tpl"
  vars {
    cluster = "apache2"
  lifecycle {
    create_before_destroy = true

Launch configuration

resource "aws_launch_configuration" "collaborator" {
  name = "collaborator"
  image_id = "${var.ami}"
  instance_type = "t2.medium"
  security_groups = ["${aws_security_group.security_group.id}"]
  vpc_classic_link_security_groups = []
  associate_public_ip_address = false
  ebs_optimized = false
  key_name = "${var.key_name}"
  iam_instance_profile = "${aws_iam_instance_profile.iam_profile.id}"
  user_data = "${template_file.user_data.rendered}"

  lifecycle {
    create_before_destroy = true