根据 terraform 文档(https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_service_account_key):
public_key_data (Optional) Public key data to create a service account key for given service account. The expected format for this field is a base64 encoded X509_PEM and it conflicts with public_key_type and private_key_type.
显然可以将公钥上传到 GCP 服务帐户。我正在努力做到这一点。
我使用 openssl 生成了私钥/公钥对:
openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
-keyout /path/to/private_key.pem \
-out /path/to/public_key.pem \
-subj "/CN=unused"
然后我获取了该公钥,删除了页眉、页脚和换行符,然后将其粘贴到文件中并将该文件提供给 Terraform:
resource "google_service_account_key" "service-account-key" {
service_account_id = google_service_account.api-service-account.name
public_key_data = file("../public_keys/certificate.pem")
}
这证明没问题。但是当 Terraform 尝试创建资源时,我收到此错误:
╷
│ Error: Error creating service account key: googleapi: Error 400: The given public key data is invalid., badRequest
│
│ with google_service_account_key.service-account-key,
│ on main.tf line XX, in resource "google_service_account_key" "service-account-key":
│ XX: resource "google_service_account_key" "service-account-key" {
│
╵
我已经尝试了我能想到的一切:
对密钥进行硬编码
不删除页脚和页眉
不删除换行符
以编程方式删除它们
使用 terraform 以编程方式对其进行编码
使用 terraform 以编程方式对其进行解码
使用以下方式生成证书:
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
openssl req -new -x509 -key private_key.pem -out certificate.pem -days 365 -subj "/CN=unused"
然后我用证书再次尝试了一切。
我验证了密钥及其有效的 base64,所以这不是问题。格式也应该是 x509,所以我认为这也不是问题。但此时我已经没有想法了。
我在互联网上找不到一个合适的、完整的例子,我没有主意了。
虽然您创建的 PEM 文件包含 Base64 公钥,但 Terraform 期望整个文件采用 Base64 编码(因此包括 -----BEGIN CERTIFICATE-----
/
-----END CERTIFICATE-----
改变:
resource "google_service_account_key" "service-account-key" {
service_account_id = google_service_account.api-service-account.name
public_key_data = file("../public_keys/certificate.pem")
}
至:
resource "google_service_account_key" "service-account-key" {
service_account_id = google_service_account.api-service-account.name
public_key_data = filebase64("../public_keys/certificate.pem")
}
它会起作用的。