'Bash - Gitlab CI not converting variable to a string

I am using GitLab to deploy a project and have some environmental variables setup in the GitLab console which I use in my GitLab deployment script below:

- export S3_BUCKET="$(eval \$S3_BUCKET_${CI_COMMIT_REF_NAME^^})"
- aws s3 rm s3://$S3_BUCKET --recursive

My environmental variables are declared like so:

Key: s3_bucket_development
Value: https://dev.my-bucket.com

Key: s3_bucket_production
Value: https://prod.my-bucket.com

The plan is that it grabs the bucket URL from the environmental variables depending on which branch is trying to deploy (CI_COMMIT_REF_NAME).

The problem is that the S3_BUCKET variable does not seem to get set properly and I get the following error:

> export S3_BUCKET=$(eval \$S3_BUCKET_${CI_COMMIT_REF_NAME^^})
> /scripts-30283952-2040310190/step_script: line 150: https://dev.my-bucket.com: No such file or directory

It looks like it picks up the environmental variable value fine but does not set it properly - any ideas why?



Solution 1:[1]

You are basically telling bash to execute command, named https://dev.my-bucket.com, which obviously doesn't exist.

Since you want to assign output of command when using VAR=$(command) you should probably use echo

export S3_BUCKET=$(eval echo \$S3_BUCKET_${CI_COMMIT_REF_NAME^^})

Simple test:

VAR=HELL; OUTPUT="$(eval echo "\$S${VAR^^}")"; echo $OUTPUT
/bin/bash

It dynamically creates SHELL variable, and then successfully prints it

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew