Skip to main content

Using shell conditionals in AWS Codebuild

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.

Avoiding COMMAND_EXECUTION_ERROR

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.

First post!

This is the obligatory "first post" of my new blog. My last blog was from a few years ago, pre-Life Changes, and I've needed something to place random geekery. I love static sites and have opinions, so this is Nikola with Markdown posts and markdown meta-data posts. I tend to write in Markdown even when I never render the content, so .. may as well.

things to write about:

  • how I sync to s3
  • my config changes

todo:

  • sync to s3
  • figure out how to add images to posts
  • smugmug?