How can I place a CodeBuild envrionment variable inside a command parameter?

2.1k Views Asked by At

I have an environment variable for my CodeBuild environment, DiscordWebhook. This contains a URL as plaintext. I am trying to run the sed command as below. This is specified in the BuildSpec.yml file.

sed -i 's/discordWebhookAddressLocal/${DiscordWebhook}/g' scripts.js

Obviously, this just replaces all instances of discordWebhookAddressLocal with "${DiscordWebhook}". I have tried some other methods such as using an alias command, but when I try to execute the alias, CodeBuild fails saying that the command could not be found.

How can I specify an environment variable into the command?

2

There are 2 best solutions below

4
On BEST ANSWER

This probably happens because you are using single quotes. Normally you would use double quotes to resolve the variables:

sed -i "s/discordWebhookAddressLocal/${DiscordWebhook}/g" scripts.js
0
On

It turns out that there were two separate problems in my case.

First of all, as Marcin has pointed out - double quotes should be used instead of single quotes when using variables. Secondly, the environment variable in question was a URL and had \ characters in it. This was the same character being used as a delimiter in the sed command. To remedy this, I changed the delimiter used in the sed command.

The new, complete working command looks like this:

sed -i "s|discordWebhookAddressLocal|${DiscordWebhook}|g" scripts.js

The commnad now returns no errors at all, and replaces strings inside scripts.js as expected.