How to authenticate to GCP from a containerized Dockerfile

自作多情 提交于 2021-01-29 09:50:43

问题


I am trying to build a new Docker image dynamically using a Cloud Build trigger job, however I fail to see how to safely retrieve my credentials to authenticate against GCP with a service account.

Here are the steps:

  1. Dockerfile created with steps to build a Docker image. One of the steps includes downloading a file from Google Storage (bucket) that I need to access as a GCP service account.

  2. Docker image is built by using a Cloud Build trigger that is triggered after each change in the linked repository and stored in GCR.

Step one fails because:

1.) By default, for some reason, the user running the Dockerfile in GCP is not authenticated against GCP. It is not a default Google Cloud Build account, it is an anonymous user.

2.) I can authenticate as a service account BUT

a.) I don't want to store the JSON private key unencrypted locally or in the repository. b.) If I stored it encrypted in the GCP repository, then I need to authenticate before decrypting it with KMS. But I don't have the key because it's still encrypted. So I am back to my problem. c.) If I stored it in a GCP Storage bucket, I need to authenticate, too. So I am back to my problem.

Is there any other approach how I can execute the Cloud build trigger job and stay/get a GCP service account context?


回答1:


The #1 solution of @ParthMehta is the right one.

Before calling the Docker Build, add this step in your Cloud Build for downloading the file from Cloud Storage by using the permission of Cloud Build environment (the service account is the following: <PROJECT_NUMBER>@cloudbuild.gserviceaccount.com)

- name: gcr.io/cloud-builders/gsutil
  args: ['cp', 'gs://mybucket/my_file', 'my_file']

The file are copied in the current directory of Cloud Build execution /workspace. Then add the files to your container by adding a simple COPY in your Dockerfile

....
COPY ./my_file ./my_file
....

In a general way, when you are working on GCP environment, you should never have to use JSON key file.




回答2:


  1. you can let cloud build to download the file from cloud storage for you and let docker to access the directory so it can use the file. You'll need to allow cloud build service account to access your bucket.

    see: https://cloud.google.com/cloud-build/docs/securing-builds/set-service-account-permissions

OR

  1. Use gcloud auth configure-docker and then you can impersonate as service account using --impersonate-service-account with access to the bucket, so docker user has sufficient access to download the file

    see: https://cloud.google.com/sdk/gcloud/reference/auth/configure-docker



来源:https://stackoverflow.com/questions/59325936/how-to-authenticate-to-gcp-from-a-containerized-dockerfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!