With the IBM Cloud provider plug-in for terraform it is possible to access the current authentication token.
data "ibm_iam_auth_token" "tokendata" {}
I have also successfully created a service ID.
resource "ibm_iam_service_id" "serviceID" {
name = "test"
description = "New ServiceID"
}
How can I create an API key, download it and use it to run the next terraform apply
under the service ID?
With a recent update, the feature of creating and referencing an API key for a service ID was added.
The task is a little bit tricky because the plugin does not return the iam_id for service IDs, only the unique ID.
There are two options. One is to use NULL resources with curl and jq to
A snippet for 1. could look like this:
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'"
}
}
Another option is to make use of the fact, that the iam_id seems to be simply the prefix iam-
followed by the unique ID. Thus, the following works for me:
// 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"
}
}
UPDATE: With this recent release, the iam_id is returned and can be directly addressed:
// 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"
}
}
The necessary Bearer token can be obtained using the IAM token data source:
data "ibm_iam_auth_token" "tokendata" {}