问题
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:
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.
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:
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
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 filesee: https://cloud.google.com/sdk/gcloud/reference/auth/configure-docker
来源:https://stackoverflow.com/questions/59325936/how-to-authenticate-to-gcp-from-a-containerized-dockerfile