terraform, gcp,

Terraform output GCP Service Account private key as plain JSON

Feb 02, 2023 · 2 mins read · Post a comment

Right of the bat, using GCP Service Accounts (SA) is greatly not recommended. This comes from GCP though. Service account keys are not managed properly, and present a security risk. Initially, the key management itself is an annoying pain point, often left as a low priority JIRA task for later, which will be forgotten in a few days. How many times have you shared a GCP SA key with a co-worker of yours on Slack, or MS Teams?! However, if you haven’t done so, good for you, but a large chunk of the engineers I consider, don’t quote me, are taking security as granted. So, instead of using Service Accounts, Google recommends a different authentication strategies, which unfortunately won’t be topic for now. Today, I want to show you how to use the lazy, “irresponsible” approach to get the Terraform SA key, and share it some developers of yours lol. It’s a dirty solution, keep in mind.


  • GCP Service Account
  • Terraform
  • base64 CLI


Given the following Terraform code:

resource "google_service_account" "this" {
  account_id   = "devcoops-some-id"
  display_name = "DevCoops SA"

resource "google_service_account_key" "this" {
  service_account_id = google_service_account.this.name
  public_key_type    = "TYPE_X509_PEM_FILE"

Add the following code to output.tf:

output "devcoops_sa_private_key" {
  value     = google_service_account_key.this.private_key
  sensitive = true

sensitive = true is the important part of it.

Next, apply TF changes, by running terraform apply.

Now, the value itself is a base64 encoded string. To get the real, plain JSON output you need to decode it, so make sure you have the base64 CLI tool installed. brew install base64 for macOS tho. Similar thing for Linux I believe.

Decode the TF output:

terraform output devcoops_sa_private_key | base64 -d -


Obviously, not a professional approach, but gets the job done fast. To be honest, I wouldn’t suggest it, yet if you are limited by time and decide to overlook the security risk aspect, that’s fine too.

If you have any other great solutions on this topic, or even issues, feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.