The most comfortable solution I've found is to create a non-root user account only if it's not already included in the image and use the gosu utility to set it for executed commands.
Pipelines' build
step is already setting the chmod 777
on the $BUILD_DIR
so additional chown
is not required.
So, to be able to change to a non-root user in Bitbucket Pipelines Docker container you have to:
- add an additional shell script to your repository that installs the gosu utility (it can also be included directly as a step in Pipelies config)
- call the
install-gosu.sh
script as the first step in Pipelines config,
- create a non-root user (checking whether it already exists first) with
id -u {user} &>/dev/null || useradd ...
,
- use gosu to run commands as a non-root user.
install-gosu.sh
#!/bin/bash
GOSU_VERSION=1.10
GNUPGHOME="$(mktemp -d)"
set -x
apt-get update && apt-get install -y --no-install-recommends ca-certificates wget && rm -rf /var/lib/apt/lists/* \
&& dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')" \
&& wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch" \
&& wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc" \
&& gpg --keyserver ha.pool.sks-keyservers.net --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 \
&& gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu \
&& rm -r "$GNUPGHOME" /usr/local/bin/gosu.asc \
&& chmod +x /usr/local/bin/gosu \
&& gosu nobody true \
&& apt-get purge -y --auto-remove ca-certificates wget
bitbucket-pipelines.yml
image: node:6
pipelines:
default:
- step:
script:
- bash $BITBUCKET_CLONE_DIR/install-gosu.sh
- id -u node &>/dev/null || useradd --user-group --create-home --shell /bin/false node
- gosu node npm install
- gosu node npm test
This can easily be adapted for other languages/users/commands. Just swap the node
user and npm
commands to whatever you need.
I've tested this method with nodejs
and python
images.