red house 87
red house 87

Reputation: 2415

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?

Upvotes: 0

Views: 793

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

It seems like you are trying to get the value of the variables S3_BUCKET_DEVELOPMENT and S3_BUCKET_PRODUCTION based on the value of CI_COMMIT_REF_NAME, you can do this by using parameter indirection:

$ a=b
$ b=c
$echo "${!a}" # c

and in your case, you would need a temporary variable as well, something like this might work:

- s3_bucket_variable=S3_BUCKET_${CI_COMMIT_REF_NAME^^}
- s3_bucket=${!s3_bucket_variable}
- aws s3 rm "s3://$s3_bucket" --recursive

Upvotes: 1

Andrew
Andrew

Reputation: 4622

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

Upvotes: 0

Related Questions