Search code examples
amazon-web-servicesshellvalidationterraformuser-data

Terraform throwing this error Getting Extra characters after interpolation expression;


I'm trying to associate the Elastic IP address with Auto scaling group, so whenever the autoscaling triggers it will automatically associate with the EIP.

For this I'm trying to add the script in user data.

My intention is to we have 2 servers so its associated with 2 EIP's, whenever the autoscaling triggers it has to check whether the EIP is free or not if its free it has to associate with that instance using the instance id.

Below is my script where I'm getting the error

In EIP_LIST im getting this error Extra characters after interpolation expression; Expected a closing brace to end the interpolation expression, but found extra characters.

INSTANCE_ID=$(ec2-metadata --instance-id | cut -d " " -f 2);
            MAXWAIT=10
            # Get list of EIPs
              EIP_LIST=${"eipalloc-09e7274dd3c641ae6" "eipalloc-05e8e926926f9de55"}
            # Iterate over EIP list
              for EIP in ${EIP_LIST}; do
                echo "Checking if EIP with ALLOC_ID[$EIP] is free...."
                  ISFREE=$(aws ec2 describe-addresses --allocation-ids $EIP --query Addresses[].InstanceId --output text --region ap-south-1)
                  STARTWAIT=$(date +%s)
                    while [ ! -z "$ISFREE" ]; do
                      if [ "$(($(date +%s) - $STARTWAIT))" -gt $MAXWAIT ]; then
                      echo "WARNING: We waited 30 seconds, we're forcing it now."
                      ISFREE=""
                      else
                      echo "Waiting for EIP with ALLOC_ID[$EIP] to become free...."
                      sleep 3
                      ISFREE=$(aws ec2 describe-addresses --allocation-ids $EIP --query Addresses[].InstanceId --output text --region ap-south-1)
                    fi
                    done
                      echo Running: aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $EIP --allow-reassociation --region ap-south-1
                      aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $EIP --allow-reassociation --region ap-south-1

Solution

  • $ is TF symbol used for interpolation of variables. It clashes with the same symbol used in bash. You have to escape it using $$ if you want to us $ in bash, not in TF, e.g.

    $${EIP_LIST}
    

    will result in ${EIP_LIST} in your script.