Vagrant 无法使用提供的 GCP 服务帐户进行身份验证

Vagrant fails to authenticate with GCP service account in provision

我尝试从预配的 GCS 中获取一些文件,但它没有按预期工作。

我创建了一个服务帐户并允许它访问目标资源。
当以下脚本以交互方式执行时,一切正常。但是,我在provision中执行的时候得到了如下警告和错误。

  1. 无法打开配置文件:[/root/.config/gcloud/configurations/config_default].
    我认为这是因为 .config 目录在根环境中不存在。
    我制作了.config目录作为测试,但并没有解决问题。

  2. 您目前没有选择活动帐户。
    我不想作为用户帐户进行身份验证,所以我认为我不必实施“gcloud auth login”。

Stacktrace和脚本如下

default: WARNING: Could not open the configuration file: [/root/.config/gcloud/configurations/config_default].
    default: ERROR: (gcloud.iam.service-accounts.keys.create) You do not currently have an active account selected.
    default: Please run:
    default: 
    default:   $ gcloud auth login
    default: 
    default: to obtain new credentials.
    default: 
    default: If you have already logged in with a different account:
    default: 
    default:     $ gcloud config set account ACCOUNT
    default: 
    default: to select an already authenticated account to use.
    default: ERROR: (gcloud.auth.activate-service-account) Could not read json file /root/key.json: Expecting value: line 1 column 1 (char 0)
    default: ServiceException: 401 Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
    default: /tmp/vagrant-shell: line 45: : command not found
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.
# Install Google Cloud SDK
## Add URI to package source list
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

## Install packages needed
sudo apt install -y apt-transport-https ca-certificates gnupg

## Import Google Cloud public key
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -

## Update and Install Google Cloud SDK
sudo apt update && sudo apt install -y google-cloud-sdk

## Create service account key
cd ~ && gcloud iam service-accounts keys create key.json --iam-account=example@example.iam.gserviceaccount.com

## Activate service account
gcloud auth activate-service-account \
         example@example.iam.gserviceaccount.com \
         --key-file ~/key.json \
         --project example-project

IIUC,错误不是 gcloud auth activate-service-account 的结果,而是 gcloud iam service-accounts keys create.

的结果

当您尝试 gcloud iam service-accounts keys create 时,您尚未通过身份验证 gcloud,因此您无权创建密钥。

您应该在流外创建密钥并(安全地)将密钥传输到 Vagrant 进程,以便它可以 gcloud auth activate-service-account