Search code examples
bashterraformterraform-template-file

Templatefile and Bash script


I need to be able to run bash script as userdata for launchtemplate and this is how I try to do it :


resource "aws_launch_template" "ec2_launch_template" {
  name = "ec2_launch_template"

  image_id = data.aws_ami.latest_airbus_ami.id

  instance_type = var.instance_type[terraform.workspace]

  iam_instance_profile {
    name = aws_iam_instance_profile.ec2_profile.name
  }

  vpc_security_group_ids = [data.aws_security_group.default-sg.id, aws_security_group.allow-local.id] # the second parameter should be according to the user

  monitoring {
    enabled = true
  }

  block_device_mappings {
    device_name = "/dev/sda1"

    ebs {
      volume_size = 30
      encrypted   = true
      volume_type = "standard"
    }
  }

  tags = {
    Name = "${var.app_name}-${terraform.workspace}-ec2-launch-template"
  }

  #user_data = base64encode(file("${path.module}/${terraform.workspace}-script.sh")) # change the base encoder as well
  user_data = base64encode(templatefile("${path.module}/script.sh", {app_name = var.app_name, env = terraform.workspace, high_threshold = var.high_threshold, low_threshold = var.low_threshold})) # change the base encoder as well
}

as you can see, I pass parameters as map in the "templatefile" function, I managed to retrieve them doing this :

#!/bin/bash -xe

# Activate logs for everything
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1

# Retrieve variables from Terraform
app_name = ${app_name}
environment = ${env}
max_memory_perc= ${high_threshold}
min_memory_perc= ${low_threshold}

instance_id=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
ami_id=$(wget -q -O - http://169.254.169.254/latest/meta-data/ami-id)
instance_type=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-type)

scale_up_name=$${app_name}"-"$${environment}"-scale-up"
scale_down_name=$${app_name}"-"$${environment}"-scale-down" 

Then, when I look at launchtemplate in AWS console, I can see that the values used in parameters are filled in :

app_name = test-app
environment = prod
max_memory_perc= 80
min_memory_perc= 40

the problem that I have is, when I run that, I get this error :

 + app_name = test-app
 /var/lib/cloud/instances/scripts/part-001: line 7: app_name: command not found

I assume there is a problem with interpretation or something like that but cannot put the finger on it

any ideas ?

Thanks


Solution

  • As they said, it was a problem with spaces, it's fixed now

    thanks