AWS CodeBuild as non-root user

To run CodeBuild as non root you need to specify a Linux username using the run-as tag in your buildspec.yaml as shown in the docs

version: 0.2

run-as: Linux-user-name

env:
  variables:
   key: "value"
   key: "value"
parameter-store:
key: "value"
key: "value"

phases:
  install:
  run-as: Linux-user-name
  runtime-versions:
    runtime: version

Thank you for this feature request. Currently you cannot run as a non-root user in CodeBuild, I have passed it to the team for further review. Your feedback is very much appreciated.


I am succeeded in using non-root user in AWS CodeBuild.
It takes much more than knowing some CodeBuild options to come up with a practical solution.

Everyone should spot run-as option quite easily.
The next question is "which user?"; you cannot just put any word as a username.

In order to find out which users are available, the next clue is at Docker images provided by CodeBuild section. There, you'll find a link to each image definition. For me, the link leads me to this page on GitHub
After inspecting the source code of Dockerfile, we'll know that there is a user called codebuild-user available. And we can use this codebuild-user for our run-as in the buildspec.

Then we'll face with a whole lot of other problems because the standard image only installs runtime of each language for root only. This is as far as generic explanations can go.

For me, I wanted to use the Ruby runtime, so my only concern is the Ruby runtime. If you use CodeBuild for something else, you are on your own now.

In order to utilize Ruby runtime as codebuild-user, we have to expose them from the root user. To do that, I change the required permissions and owner of .rbenv used by the CodeBuild image with the following command.

chmod +x ~
chown -R codebuild-user:codebuild-user ~/.rbenv

 
The bundler (Ruby's dependency management tool) still wants to access the home directory, which is not writable. We have to set up an environment variable to make it use other writable location as the home directory. The environment variable is BUNDLE_USER_HOME.

Put everything together; my buildspec looks like:

version: 0.2

env:
  variables:
    RAILS_ENV: test
    BUNDLE_USER_HOME: /tmp/bundle-user
    BUNDLE_SILENCE_ROOT_WARNING: true

run-as: codebuild-user

phases:
  install:
    runtime-versions:
      ruby: 2.x
    run-as: root
    commands:
      - chmod +x ~
      - chown -R codebuild-user:codebuild-user ~/.rbenv
      - bundle config set path 'vendor/bundle'
      - bundle install
  build:
    commands:
      - bundle exec rails spec

cache:
  paths:
    - vendor/bundle/**/*

My points are:

  • It is, indeed, possible.
  • Show how I did it for my use case.