Bitbucket Pipelines使用Docker容器执行任务,默认情况下,Docker容器以root身份运行。这是NPM生命周期脚本的问题,因为NPM在运行脚本时会尝试降级其特权。
当执行postinstall
脚本,NPM抛出一个错误,它cannot run in wd %s %s (wd=%s)
。最简单的解决方案是运行带有--unsafe-perm
标志的npm install ,但是我不喜欢这种方法。
Docker编写Dockerfile的最佳实践指出:
如果服务可以在没有特权的情况下运行,请使用USER更改为非root用户。
在配置典型的Docker容器时,我将创建一个新的非root用户,并以该用户身份运行npm脚本。
阅读管道文档后,我找不到与Docker的USER命令等效的任何内容。我也许能使用useradd
,chown
并且su
(没有测试尚未),但有一个简单的解决方案?
不幸的是useradd
,在脚本部分添加chown
和su
会bitbucket-pipelines.yml
中断管道,并导致repo:push
webhook失败。
image: node:6.2
pipelines:
default:
- step:
script:
- useradd --user-group --create-home --shell /bin/false node
- chown -R node: /opt/atlassian/bitbucketci/agent/build
- su -s /bin/sh -c "npm install" node
- su -s /bin/sh -c "npm run test:coverage --silent" node
管道回应
{
"code": 500,
"message": "There was an error processing your request. It has been logged (ID <removed>)."
}
我发现最舒适的解决方案是仅在映像中未包含非root用户帐户时创建该帐户,然后使用gosu实用程序为执行的命令设置该帐户。
管道的build
步骤已设置为chmod 777
on,$BUILD_DIR
因此chown
不需要其他操作。
因此,要在Bitbucket Pipelines Docker容器中更改为非root用户,您必须:
install-gosu.sh
在“管道”配置中将脚本称为第一步,id -u {user} &>/dev/null || useradd ...
。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
这可以轻松地适用于其他语言/用户/命令。只需交换node
用户和npm
命令即可。
我已经使用nodejs
和python
图像测试了此方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句