Creation of google service account key with terraform then save into output

Hi there, I wanted to create the json token key using terraform via data and output: 

 

 

 

resource "google_service_account" "myaccount" {
	account_id = "myaccount"
	display_name = "My Service Account"
}
resource "google_service_account_key" "mykey" {
	service_account_id = google_service_account.myaccount.name
	public_key_type = "TYPE_GOOGLE_CREDENTIALS_FILE"
}
data "google_service_account_key" "google_service_account_key" {
	service_account_id = google_service_account.myaccount.name
}

output "google_credentials_json" {
	value = google_service_account_key.google_service_account_key.private_key
	sensitive = true
}

 

 

 

 

There is a sample of creating the key but we are not allowed to create an output for the key, I want to know :

1. how to create a physical token creation with terraform
2. what is the standard practice of creating the key using terraform if not do we just create them in the console
(ps: I know there are safer way than this which is using role federation for the application but this case I have to stick with json credentials)

1 1 704
1 REPLY 1

Hello @lucheeseng,

Welcome to Google Cloud Community!

To create a JSON token key using Terraform without exposing it in the output, you can follow these steps:

  1. Create the Service Account and Key
    Use Terraform to create the Google Service Account and its associated key. You have already done this in your Terraform configuration.
  2. Store the Key Securely
    Instead of exposing the key in the output, you can store it securely in a file or a secret management service. One common practice is to save the key to a file on the local machine where Terraform is running.
  3. Manual Output
    If you need to access the key during provisioning, you can manually output a message guiding users on how to securely store and use the key without displaying it directly in the Terraform output.

Here is an updated version of your Terraform configuration with these considerations:

resource "google_service_account" "myaccount" {
	account_id = "myaccount"
	display_name = "My Service Account"
}

resource "google_service_account_key" "mykey" {
	service_account_id = google_service_account.myaccount.name
	public_key_type = "TYPE_GOOGLE_CREDENTIALS_FILE"
}

# Save the private key to a local file
resource "local_file" "private_key_file" {
  content  = google_service_account_key.mykey.private_key
  filename = "${path.module}/private-key.json"
}

# Output a message guiding users on handling the private key securely
output "private_key_instructions" {
  value = "The private key has been saved to private-key.json. Handle it securely."
}