I was working on AWS Codebuild and having trouble getting a conditional to work. In my case, I wanted a "dry run" type flag. I'll use that as the example here.
Conditionals support in Codebuild's buildspec
My first problem was figuring out what shell AWS uses. I didn't find anything on the "Shells and Commands in Build Environments" documentation page, so I decided to keep it really vanilla- avoid using
bash specifics and stay close to a POSIX shell. Here was my first try:
post_build: commands: - [ "$DRY_RUN" -gt "0" ] && echo "run my command"
Looks great, right? Well, except I forgot the first rule of yaml: always run a linter. That would have shown me that I was using square brackets in a scalar, which is never a good idea.
So, I quoted the whole thing:
post_build: commands: - '[ "$DRY_RUN" -gt "0" ] && echo "run my command"' - |- [ "$DRY_RUN" -gt "0" ] && echo "alternate quoting syntax"
And that's what led me to write up this blog entry. That was returning
COMMAND_EXECUTION_ERROR in the build:
[Container] 2019/02/28 21:14:25 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: [ "$DRY_RUN" -gt "0" ] && echo "run my command". Reason: exit status 1
When I google for this, I only found a couple lines of linkspam, nothing relevant. I had to iterate several times to solve it, and I ended up just using an if-fi block instead.
post_build: commands: - |- if [ "$DRY_RUN" -gt "0" ]; then echo "run my command" fi
And that works! So, TLDR: use the if-fi syntax in a quoted yaml section.