As mentioned in the previous section, a resource such as a Compute Engine VM can use a service account to interact with a Google Cloud API. Note that it is also possible to attach a service account to a resource that is deployed in a different project.
When a VM is created, it uses a default service account that you can replace with a new one assuming you have at least a Service Account User role on this new account:
Figure 12.34 – Adding a service account to a Compute Engine VM
Once a VM is created, you can access it via ssh and check what credentials it uses to authenticate to Google Cloud services with the following command: gcloud auth list.
In the following figure, a vm-a Compute Engine VM uses the bucket-access service account. This service account has a Storage Admin role in this project. This means a VM using this service account can access and interact with Google Cloud Storage. For example, it can create and list buckets as shown in the following screenshot:
Figure 12.35 – Using a service account to interact with Google Cloud Storage from a Compute Engine VM directly
To confirm what type of account was actually used for a my-new-bucket-to-test-service-account creation (shown in Figure 12.35), we can look into the Cloud Logging log entry for the GCS Bucket type and confirm that the bucket-access user account was used:
Figure 12.36 – Cloud Logging log entry showing the account used for a bucket creation
Check the following link to see what other Google Cloud services besides Compute Engine VMs use service accounts: https://cloud.google.com/iam/docs/attach-service-accounts.
Impersonating a service account
Because a service account can also act as a resource, you can grant access to it to users or groups. The ability to temporarily act as another identity in a controlled way helps administrators to limit the scope of permissions assigned to users. For example, users can have permissions necessary for day-to-day activities, and occasionally, for a limited time, can impersonate a service account for some extra activities.
Let’s look at the example in the following figure. The app-owner user has the following roles: Viewer, to browse the resources in this project, Compute Instance Admin, to manage compute instances, and the Service Account Token Creator role (on the bucket-access service account), which allows impersonating a service account.
Figure 12.37 – Impersonating a service account by a user
In the CLOUD SHELL section of the screenshot, you can see the app_owner user trying to create a storage bucket. This task fails, as the user doesn’t have the required permissions. However, once the same command is issued with –impersonate-service-account=bucket-access@, the command succeeds and the bucket is created because bucket-access is a service account with a Storage Admin role.