This article is written for Windows, but the same principles apply to Linux and Mac.

A service account is a special Google account that is used with applications or services, such as Google Compute Engine. Service account credentials are stored in a file. There are two file formats, Json and P12.

The JSON format is the recommended format for service account credential files. This format consists of multiple JSON keys, with the private key being the critical value that is used to sign API requests. This file can be viewed in any text editor.

The P12 format, otherwise known as PKCS #12 or PFX, is a binary format for storing a certificate, intermediate certificates, and the private key in an encrypted file. Common file suffixes are .p12 or .pfx. The following openssl command will display a P12 file. Note the option -nodes. This means No DES, not NODES. Use this option so that you can see the unencrypted private key. In this example the password is notasecret.

Now let’s create a service account using the gcloud CLI. First, let’s set some environment variables to reduce mistakes. Modify with your Google Project ID.

Notice the MEMBER variable. The format for service account credentials is always USER@PROJECT suffixed with the domain iam.gserviceaccount.com.

This command will display the current Project ID:

To get fancy using jq:

Outputs:

Using jq makes it easy to set environment variables to chain commands together.

Create a service account using the previous environment variables:

Command output:

The next step is to authorize the service account with permissions. In this example, we authorize the role viewer:

To authorize a service account, you apply the role to the project and not to the service account itself. IAM policies applied to the service account manage who can use the service account and not the service account permissions. Remember to apply permissions for a service account to the project.

To quote Google:

In addition to being an identity, a service account is a resource that has IAM policies attached to it. These policies determine who can use the service account.

For instance, Alice can have the editor role on a service account and Bob can have the viewer role on a service account. This is just like granting roles for any other GCP resource.

Now that we have created and authorized this service account, create and download a service account credentials file to be used later in our software.

Command output:

To download a P12 format add the command line option:

gcloud iam service-accounts create

gcloud projects add-iam-policy-binding

gcloud iam service-accounts keys create