I have downloaded the GCP service account key to my local system. In Terraform, I have set the GOOGLE_APPLICATION_CREDENTIALS as a path to this file in the startup-script part of my bastion instance. Below is a snippet:
variable "credentials"{
default="C:/GCP/service-account-key.json"
}
. . . . . .
metadata= {
startup-script=<<SCRIPT
export GOOGLE_APPLICATION_CREDENTIALS="${file("${var.credentials}")}"
SCRIPT
}
Later I have written a #!/bin/bash script to store this credentials to another file as below:
#!/bin/bash
printf "$GOOGLE_APPLICATION_CREDENTIALS" > /home/ubuntu/credentials
But when I open the above credentials file, the file is truncated as below and the entire key is missing:
{
type: service_account,
project_id: acn-devopsgcp,
private_key_id: xxxxx,
private_key: -----BEGIN
Can please someone let me know why the service account key is not getting exported properly to the file or if there is anything that needs to be corrected.
If this bastion instance is a Google Cloud Compute Engine (GCE) instance, you do not need to pass JSON keys to the VM.
You should use the service account which the GCE instance runs as - any tool which uses the GCP API/SDK (e.g.
gsutil
orgcloud
) will use this service account by default if no credentials are provided using environment variables.Each GCP project is provisioned with a "default compute" service account, or you can create one specifically for the instance in question with Terraform and grant permissions as necessary via IAM.
Specifically answering your question, however, your key is not being deployed due to nested double quotes. Your JSON key contains double quotes, which if not escaped will terminate the quote starting the string.
If you have to use the JSON key file, I would deploy it to the VM as a file, then read the file in the startup script:
You must configure the variable GOOGLE_APPLICATION_CREDENTIALS
https://cloud.google.com/docs/authentication/
You can download the JSON file from the Service Account.
In IAM & admin > Service Accounts section, click on the 3 dots of the Service Account you want to use and select "Create key" > JSON > Create
This will generate/download the JSON file.