AWS CodeBuild fails when changing to a folder directory with a space

I write my articles when some technical issue really frustrates me and when there’s not much information available about it on the Internet.

There’s an issue a hit recently in AWS CodeBuild – when you cd into a directory with a space in it’s name, CodeBuild breaks on the very next command and “resets” your current directory. If you next commands depends on your current directory this could lead to Build Failures.

Error hit: “/codebuild/output/tmp/script.sh: 1: cd: can’t cd to XXXXXX

Reason behind seems a wrapper script(/codebuild/output/tmp/script.sh) used by AWS CodeBuild to keep hold of the directory you’re currently in. It stores in a temporary txt file the directory path and on the next command it tries to read the directory from the temp file and cd into it. Problem comes when there’s a space in the directory name which make the wrapper script interprets the content of the temp file as 2 strings rather than 1.

This is how the wrapper script “collects” the current directory:
pwd > /codebuild/output/tmp/dir.txt

And that’s how it tries to “load it back”
cd $(cat /codebuild/output/tmp/dir.txt) (in bash this will throw “-bash: cd: too many arguments”, in sh – “sh: 1: cd: can’t cd to” when dir.txt contains a space”

Here’s a sample buildspec to reproduce the issue.

version: 0.2
phases:
  build:
    commands:
      - pwd && echo "codebuild starts initially in this directory"
      - cat /codebuild/output/tmp/script.sh
      - cd /tmp
      - pwd && echo "obviously we are in tmp now"
      - mkdir /tmp/folder\ with\ space
      - touch /tmp/folder\ with\ space\somefile.txt
      - cd /tmp/folder\ with\ space
      - ls -lah && echo "expecting this to list somefile.txt"
      - pwd && echo "codebuild has reset the current directory"

Posted the same on AWS Forums https://forums.aws.amazon.com/thread.jspa?messageID=997823&tstart=0

Hopefully Amazon will fix it soon.