Service accounts are special accounts that can be used by applications and servers to allow them access to your Google Cloud Platform resources. You can use them to manage access within your account, and for external applications.
For example, if you need to give an app permission to write to a Cloud Storage bucket, you can create a service account, give that account permission to write to the bucket, and then pass authenticate using the private key for that service account. If the app you’re authenticating is on Compute Engine, you can set a service account for the entire instance, which will apply be default for all gcloud API requests.
Creating a Service Account
Head over to the IAM & Admin Console, and click on “Service Users” in the sidebar. From here, you can create a new service account, or manage existing ones.
Give the service account a name. The service account will use the project-id.iam.gserviceaccount.com domain as the email, and act like a normal user when assigning permissions. Click “Create.”
If you want to assign project-wide permissions, which will apply to every affected resource, you can do so from the next screen. For example, you can give it project-wide read permissions with “Viewer,” or give it access to a specific service like Compute Engine.
On the next screen, you can give existing users access to either use or administrate the service account.
To give more fine-grained permissions, you can add the service account to the resources it needs to access, such as specific Compute Engine instances, by adding the account as a new member in the “Permissions” settings for the given resource. This way, you’re able to give access to specific resources, rather than project-wide permissions.
Using the Service Account
If you’re using the internally for other Google Cloud Platform services, you’ll often be given an option to select the service account. For example, for Compute Engine, under the instance settings you can set the service account that the engine uses, which will be used by default for all CLI requests coming from the instance.
If you want to authenticate a service that isn’t running on Compute Engine, or don’t want to set the service account for the whole instance, you’ll need to create an access key for the service account. You can do this from the Service Account settings in the IAM Console; click “Create Key,” and you’ll be given the option to download a JSON key for the service account.
Then, you can pass that key to the API, usually by setting the GOOGLE_APPLICATION_CREDENTIALS environment variable. This credential contains the service account email and ID, and is all that you need for setting up a connection between your application and GCP.