10

I'd like to create Google Cloud API keys using Terraform.

Is this possible?

4
  • 2
    Does it need to be an API key or can it be a service account? AFAIK there is no API for creating API keys but you can create service accounts and their key pairs with Terraform. Commented Mar 24, 2020 at 10:05
  • Should be an API key as it's for usage with the Cloud Endpoints. You are right. it seems like it has no API Commented Mar 24, 2020 at 10:53
  • 1
    At this time, I do not believe that there is a Terraform module to create API keys. You can check the following link for all the Terraform modules that are available for GCP [1] registry.terraform.io/… Commented Mar 24, 2020 at 22:27
  • 1
    There is now! stackoverflow.com/a/71556294/2023941 Commented Mar 23, 2022 at 3:36

4 Answers 4

11

Google Cloud provider (version >= 4.14.0) for Terraform now supports creating API Keys.

Updating the answer with an example (as suggested by @noamt, thanks).

The key, in this case, restrict the possible APIs that can use to some GMaps ones:

resource "google_apikeys_key" "maps" {
  name         = "maps-api-key"
  display_name = "Nice name displayed in the UI"

  restrictions {
        # Example of whitelisting Maps Javascript API and Places API only
        api_targets {
            service = "maps-backend.googleapis.com"
        }
        api_targets {
            service = "places-backend.googleapis.com"
        }
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Great news. Please edit the answer to include an example, rather than a link to external docs. Links can be broken, pages can be removed
It'd be great also a data source to retrieve the key. My goal is putting that key into a Secret after it has been created.
I am using provider version 4.31.0 and I am unable to create a key and getting an error requiring to setup service account and billing. Tried with user_project_override and billing_project setup but still getting an error. Any extra configuration needed?
And how do we get the API Key value in Terraform? The docs say that it exports an encrypted key_string that can only be accessed through the GetKeyString method. But I have no idea how to use that method.
Seems the docs are inaccurate. I've been successfully able to get the key using the key_string attribute. E.g.: google_apikeys_key.maps.key_string. It's just marked as sensitive in Terraform so it will not be printed plaintext in the logs, but that's to be expected. One can though unmark it as sensitive using nonsensitive(google_apikeys_key.maps.key_string) when the key is not actually a secret.
9

Not yet, but Google seems to be working on exposing an API for API key management. Latest cloud sdk (tested with 287.0.0) has alpha support, like this:

$ gcloud alpha services api-keys
ERROR: (gcloud.alpha.services.api-keys) Command name argument expected.

Available commands for gcloud alpha services api-keys:

      clone                   *(ALPHA)*  Create a new API key with the same
                              metadata as input key.
      create                  *(ALPHA)*  Create an API key.
      delete                  *(ALPHA)*  Delete an API key.
      describe                *(ALPHA)*  Describe an API key's metadata.
      get-key-string          *(ALPHA)*  Get key string of an API key.
      list                    *(ALPHA)*  Lists API keys.
      lookup                  *(ALPHA)*  Look up resource name of a key string.
      undelete                *(ALPHA)*  Undelete an API key.
      update                  *(ALPHA)*  Update an API key's metadata.

When listing project API keys with the --log-http you can see the API endpoint used:

$ gcloud alpha services api-keys list --project $PROJECT --log-http
...
==== request start ====
uri: https://apikeys.googleapis.com/v2alpha1/projects/$PROJECT/keys?alt=json
...

Even though cloud sdk is using v2alpha1, there is a v2beta1 available. Verified like this:

$ curl -s -H"Authorization: Bearer $(gcloud auth print-access-token)" \
   https://apikeys.googleapis.com/v2beta1/projects/$PROJECT/keys
{
  "keys": [
    {
      "name": "projects/REDACTED/keys/REDACTED",
      "displayName": "REDACTED",
      "createTime": "2019-04-15T10:39:53.558Z",
      "updateTime": "2019-04-15T10:40:06.616639Z",
      "restrictions": {
        "androidKeyRestrictions": {},
        "apiTargets": [
          {
            "service": "geocoding_backend"
          }
        ]
      },
      "state": "ACTIVE"
    }
  ]
}

Since the terraform google provider is usually pretty quick to add new features I can only assume support is coming soon. You may want to create a Github Issue to show your interest. Or watch the beta provider's change log.

2 Comments

It seems they’ve declined the ask for Terraform support here: github.com/terraform-providers/terraform-provider-google/issues/…
Terraform support has arrived: stackoverflow.com/a/71556294/2023941
2

Many people use API Keys for securing access to API. However, Google considers unsecured this kind of authentication (the API key never rotate compare to an OAuth token that have 1H of life. If your authentication secret is stolen, with API key the effect is unlimited in the time).

That's why, for discouraging this bad usage, you can't easily generate (and also validate) the API keys, I mean, there isn't public API to call for creating or checking the API Keys. And thus, terraform can't perform this task.

2 Comments

So in a context where I require authentication, but don't care about the actual identity, what's the best way to go? Keeping secrets on the client side (which is a mobile app) is of course also not recommended.
Roughtly, I see 2 cases: Either your app is secured and each user have to be authenticated (user account with a password for example, Google Play account, or Google account,...) and you can select which users to authorize or not. At least, you can required an authenticated user to know who block in case of not appropriate use of your service. Or your app is public and adding security layer is useless.
1

It seems they’ve declined the ask for Terraform support here: https://github.com/hashicorp/terraform-provider-google/issues/6413

However there's now this issue for tracking the desire for this again: https://github.com/hashicorp/terraform-provider-google/issues/8959 👍🏻❔

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.