IBM Cloud 和 Terraform:如何创建和下载 API 密钥?

IBM Cloud and terraform: How to create and download API key?

随着 IBM Cloud provider plug-in for terraform it is possible to access the current authentication token.

data "ibm_iam_auth_token" "tokendata" {}

我也成功创建了一个服务ID。

resource "ibm_iam_service_id" "serviceID" {
  name        = "test"
  description = "New ServiceID"
}

如何创建一个 API 密钥,下载它并将其用于服务 ID 下的 运行 下一个 terraform apply

通过最近的更新,creating and referencing an API key for a service ID was added 的功能。

任务有点棘手,因为插件不 return iam_id for service IDs, only the unique ID

有两种选择。一种是使用 curljq

的 NULL 资源
  1. 首先获取服务ID详细信息,包括iam_id、
  2. 然后,通过 POST,创建 API 密钥。

1. 的片段可能如下所示:

resource "null_resource" "devops_iam_id" {
  // Get iam_id for service ID
  provisioner "local-exec" {
    command = "curl -X GET 'https://iam.cloud.ibm.com/v1/serviceids/${ibm_iam_service_id.myServiceID.id}' -H 'Authorization: ${data.ibm_iam_auth_token.iam_tokendata.iam_access_token}' -H 'Content-Type: application/json' | jq '.iam_id'"
  }
}

另一种选择是利用这一事实,即 iam_id 似乎只是前缀 iam- 后跟唯一 ID。因此,以下对我有用:

// Create a service ID for devops tasks
    resource "ibm_iam_service_id" "myServiceID" {
      name        = "myServiceID"
      description = "ServiceID for deploying the app and devops tasks"
    
      // create and download API key
      provisioner "local-exec" {
        command = "curl -X POST 'https://iam.cloud.ibm.com/v1/apikeys' -H 'Authorization: ${data.ibm_iam_auth_token.iam_tokendata.iam_access_token}' -H 'Content-Type: application/json' -d '{ \"name\":\"henrikTestKey\", \"iam_id\":\"iam-${ibm_iam_service_id.myServiceID.id}\", \"store_value\": true}' > apikeyOutput.json"
      }
    }

更新:有了这个 recent releaseiam_id 被 return 编辑并且可以直接解决:

// Create a service ID for devops tasks
    resource "ibm_iam_service_id" "myServiceID" {
      name        = "myServiceID"
      description = "ServiceID for deploying the app and devops tasks"
    
      // create and download API key
      provisioner "local-exec" {
        command = "curl -X POST 'https://iam.cloud.ibm.com/v1/apikeys' -H 'Authorization: ${data.ibm_iam_auth_token.iam_tokendata.iam_access_token}' -H 'Content-Type: application/json' -d '{ \"name\":\"henrikTestKey\", \"iam_id\":\"${ibm_iam_service_id.myServiceID.id}\", \"store_value\": true}' > apikeyOutput.json"
      }
    }

可以使用 IAM token data source:

获取必要的 Bearer 令牌
data "ibm_iam_auth_token" "tokendata" {}