Terraform for GCP How to create API Keys
Hi, this is Paul, and welcome to the #31 part of my Terraform guide. Today we will discuss, how to create an API Key using the Terraform script.
Add Role for Service Account
First, to create an API Key you need to add a Role API Keys Admin
to you're Service Account. How to add permissions we already discussed in this article:
Overview of the Terraform google_apikeys_key
Here is the resource block example we will analyze:
resource "google_apikeys_key" "demo_key" {
name = "key"
display_name = "demo-key"
restrictions {
api_targets {
service = "translate.googleapis.com"
methods = ["GET"]
}
browser_key_restrictions {
allowed_referrers = [".*"]
}
}
}
Parameters of the Resource Block
resource "google_apikeys_key" "demo_key"
: Defines a new resource of typegoogle_apikeys_key
nameddemo_key
in Terraform. This name is used in Terraform to reference this resource.name
: The logical name of the key in GCP. This name uniquely identifies the key in your GCP project.display_name
: A human-readable name for the key that can be used for convenient display.
Parameters of the restrictions
Block
api_targets
: A block describing which APIs and methods this key can be applied to.service
: Specifies the particular API service that the key applies to (in this case,translate.googleapis.com
).methods
: A list of HTTP methods that are allowed to be used with this key (in this case, onlyGET
).browser_key_restrictions
: A block that restricts the use of the API key in browser applications.allowed_referrers
: A list of URL patterns that are allowed to use this key. The pattern".*"
indicates that access is allowed for any referrers.
Conclusion
Using Terraform to manage GCP API keys, you can greatly simplify the process of managing API access and enhance the security of your application by controlling which services and methods are available for each key. Terraform provides a convenient way to declaratively describe and control these settings as part of your cloud infrastructure, making the process of managing keys more transparent and versionable.
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn