Nested Credentials with Cloud Build
How to access protected resources inside docker builds on Cloud Build in less than 2 minutes.
Cloud Build is Google Cloud’s serverless CI tool for running ephemeral builds of code, tests and deployments. When using it to build Docker images, sometimes you’ll need to access private or protected resources which require authentication. But you don’t want to have to expose any keys in source code or as arguments to the container which could then be available to the build process, so how do you access these resources safely and securely?
In this post, I want to discuss how we’ll use Cloud Build to retrieve code from a private NPM registry on Artifact Registry during the building of a docker image. When we build a docker image in a Cloud Build job we don’t automatically get access to everything the Cloud Build service account can access.
Consider this snippet of code which is a build step in a Cloud Build job:
name: "gcr.io/cloud-builders/docker"
args:
[
"build",
"-t",
"us-docker.pkg.dev/$PROJECT_ID/${_IMAGE_NAME}",
".",
]
You might use something like this in your build process, but the problem is that once you’re in the Docker build process, then it doesn’t have any awareness of what it is, or where it’s building, and nor should it as we expect Docker images to be built in isolation by default.
If, in your Dockerfile, you have a step that’s something like npm install
which builds all your dependencies inside your app, then if one of those dependencies is in the Artifact Registry, it won’t work, because inside the build process, it doesn’t have any credentials automatically assigned by default.
Assuming the Cloud Build job is run by a service account that has permissions to use Artifact Registry, then all you need to do is include a parameter --network=cloudbuild
in your args, and it will have access to the host’s credentials.
name: "gcr.io/cloud-builders/docker"
args:
[
"build",
"--network=cloudbuild",
"-t",
"us-docker.pkg.dev/$PROJECT_ID/${_IMAGE_NAME}",
".",
]
Easy, simple and secure.