Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Last active September 8, 2022 16:56
Show Gist options
  • Save nitrocode/c5be3e043623c26c4048d39a9c4dd9b7 to your computer and use it in GitHub Desktop.
Save nitrocode/c5be3e043623c26c4048d39a9c4dd9b7 to your computer and use it in GitHub Desktop.
Using the http and mastercard restapi terraform provider

Using the http and mastercard restapi terraform provider

I had an issue when trying to get the cloudflare account_id which is available using the REST API but unavailable using the cloudflare terraform provider (original thread).

✗ curl -X GET "https://api.cloudflare.com/client/v4/accounts" \
     -H "Content-Type:application/json" \
     -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" |
  jq -r '.result[] | select(.name == "<your-account-name>").id'

<your-account-id>

I worked around the lack of a data source by using Mastercard's restapi terraform provider and providing the API token using the env var TF_VAR_cloudflare_api_token.

This is a powerful escape hatch with many use-cases!

terraform {
  required_version = ">= 0.13.0"

  required_providers {
    restapi = {
      source  = "Mastercard/restapi"
      version = "> 1"
    }
    http = {
      source  = "hashicorp/http"
      version = "> 3"
    }
  }
}

variable "cloudflare_api_token" {}

provider "restapi" {
  uri                  = "https://api.cloudflare.com"
  debug                = true
  write_returns_object = true
  headers = {
    "Content-Type"  = "application/json"
    "Authorization" = "Bearer ${var.cloudflare_api_token}"
  }
}

data "restapi_object" "account" {
  path         = "/client/v4/accounts"
  results_key  = "result"
  search_key   = "name"
  search_value = "<your-account-name>"
}

output "account_restapi" {
  value = jsondecode(data.restapi_object.account.api_response).result.id
}

data "http" "account" {
  url = "https://api.cloudflare.com/client/v4/accounts"

  request_headers = {
    Accept        = "application/json"
    Authorization = "Bearer ${var.cloudflare_api_token}"
  }
}

output "account_http" {
  value = jsondecode(data.http.account.response_body).result[index(jsondecode(data.http.account.response_body).result.*.name, "<your-account-name>")].id
}

This resulted in the following plan output

data.http.account: Reading...
data.restapi_object.account: Reading...
data.restapi_object.account: Read complete after 1s [id=<your-account-id>]
data.http.account: Read complete after 2s [id=https://api.cloudflare.com/client/v4/accounts]

Changes to Outputs:
  + account_http    = "<your-account-id>"
  + account_restapi = "<your-account-id>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment