1---
2layout: "docs"
3page_title: "Google Cloud - Secrets Engines"
4sidebar_title: "Google Cloud"
5sidebar_current: "docs-secrets-gcp"
6description: |-
7  The Google Cloud secrets engine for Vault dynamically generates Google Cloud
8  service account keys and OAuth tokens based on IAM policies.
9---
10
11# Google Cloud Secrets Engine
12
13The Google Cloud Vault secrets engine dynamically generates Google Cloud service
14account keys and OAuth tokens based on IAM policies. This enables users to gain
15access to Google Cloud resources without needing to create or manage a dedicated
16service account.
17
18The benefits of using this secrets engine to manage Google Cloud IAM service accounts are:
19
20- **Automatic cleanup of GCP IAM service account keys** - each Service Account
21  key is associated with a Vault lease. When the lease expires (either during
22  normal revocation or through early revocation), the service account key is
23  automatically revoked.
24
25- **Quick, short-term access** - users do not need to create new GCP Service
26  Accounts for short-term or one-off access (such as batch jobs or quick
27  introspection).
28
29- **Multi-cloud and hybrid cloud applications** - users authenticate to Vault
30  using a central identity service (such as LDAP) and generate GCP credentials
31  without the need to create or manage a new Service Account for that user.
32
33~> **NOTE: Deprecation of `access_token` Leases**: In previous versions of this secrets engine
34    (released with Vault <= 0.11.1), a lease was generated with access tokens. If you're using
35    an old version of the plugin, please upgrade. Read more in the
36    [upgrade guide](#deprecation-of-access-token-leases)
37
38
39## Setup
40
41Most secrets engines must be configured in advance before they can perform their
42functions. These steps are usually completed by an operator or configuration
43management tool.
44
451. Enable the Google Cloud secrets engine:
46
47    ```text
48    $ vault secrets enable gcp
49    Success! Enabled the gcp secrets engine at: gcp/
50    ```
51
52    By default, the secrets engine will mount at the name of the engine. To
53    enable the secrets engine at a different path, use the `-path` argument.
54
551. Configure the secrets engine with account credentials, or leave blank or unwritten
56   to use Application Default Credentials.
57
58    ```text
59    $ vault write gcp/config credentials=@my-credentials.json
60    Success! Data written to: gcp/config
61    ```
62
63    If you are running Vault from inside [Google Compute Engine][gce] or [Google
64    Kubernetes Engine][gke], the instance or pod service account can be used in
65    place or specifying the credentials JSON file.
66    For more information on authentication, see the [authentication section](#authentication) below.
67
681. Configure a roleset. Rolesets determine the permissions that Service Account
69credentials generated by Vault will have on GCP resources.
70
71    To configure a roleset that generates OAuth2 access tokens (preferred):
72
73    ```text
74    $ vault write gcp/roleset/my-token-roleset \
75        project="my-project" \
76        secret_type="access_token"  \
77        token_scopes="https://www.googleapis.com/auth/cloud-platform" \
78        bindings=-<<EOF
79          resource "//cloudresourcemanager.googleapis.com/projects/my-project" {
80            roles = ["roles/viewer"]
81          }
82        EOF
83    ```
84
85    To configure a roleset that generates GCP Service Account keys:
86
87    ```text
88    $ vault write gcp/roleset/my-key-roleset \
89        project="my-project" \
90        secret_type="service_account_key"  \
91        bindings=-<<EOF
92          resource "//cloudresourcemanager.googleapis.com/projects/my-project" {
93            roles = ["roles/viewer"]
94          }
95        EOF
96    ```
97
98    Alternatively, provide a file for the `bindings` argument like so:
99
100    ```text
101    $ vault write gcp/roleset/my-roleset
102        bindings=@mybindings.hcl
103        ...
104    ```
105
106    For more information on role bindings and sample role bindings, please see
107    the [roleset bindings](#roleset-bindings) section below.
108
109    For more information on the differences between OAuth2 access tokens and
110    Service Account keys, see the [things to note](#things-to-note) section
111    below.
112
113## Usage
114
115After the secrets engine is configured and a user/machine has a Vault token with
116the proper permission, it can generate credentials. Depending on how the roleset
117was configured, you can generate OAuth2 tokens or service account keys.
118
119### Access Tokens
120
121To generate OAuth2 tokens, read from `gcp/token/...`. The roleset must have been
122created as type `access_token`:
123
124```text
125$ vault read gcp/token/my-token-roleset
126
127Key                Value
128---                -----
129expires_at_seconds    1537402548
130token                 ya29.c.ElodBmNPwHUNY5gcBpnXcE4ywG4w1k...
131token_ttl             3599
132```
133
134This endpoint generates a non-renewable, non-revocable static OAuth2 access token
135with a lifetime of one hour, where `token_ttl` is given in seconds and the
136`expires_at_seconds` is the expiry time for the token, given as a Unix timestamp.
137The `token` value then can be used as a HTTP Authorization Bearer token in requests
138to GCP APIs:
139
140```sh
141$ curl -H "Authorization: Bearer ya29.c.ElodBmNPwHUNY5gcBpnXcE4ywG4w1k..."
142```
143
144### Service Account Keys
145
146To generate service account keys, read from `gcp/key/...`. The roleset must have
147been created as type `service_account_key`:
148
149```text
150$ vault read gcp/key/my-key-roleset
151
152Key                 Value
153---                 -----
154lease_id            gcp/key/my-key-roleset/ce563a99-5e55-389b...
155lease_duration      30m
156lease_renewable     true
157key_algorithm       KEY_ALG_RSA_2048
158key_type            TYPE_GOOGLE_CREDENTIALS_FILE
159private_key_data    ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsC...
160```
161
162This endpoint generates a new [GCP IAM service account key][iam-keys] associated
163with the roleset's Service Account. When the lease expires (or is revoked
164early), the Service Account key will be deleted.
165
166**There is a default limit of 10 keys per Service Account.** For more
167information on this limit and recommended mitigation, please see the [things to
168note](#things-to-note) section below.
169
170## Roleset Bindings
171
172Roleset bindings define a list of resources and the associated IAM roles on that
173resource. Roleset bindings are used as the `binding` argument when creating or
174updating a roleset and are specified in the following format using HCL:
175
176```hcl
177resource NAME {
178  roles = [ROLE, [ROLE...]]
179}
180```
181
182For example:
183
184```hcl
185resource "buckets/my-bucket" {
186  roles = [
187    "roles/storage.objectAdmin",
188    "roles/storage.legacyBucketReader",
189  ]
190}
191```
192
193The top-level `resource` block defines the resource or resource path for which
194IAM policy information will be bound. The resource path may be specified in a
195few different formats:
196
197- **Project-level self-link** - a URI with scheme and host, generally
198  corresponding to the `self_link` attribute of a resource in GCP. This must
199  include the resource nested in the parent project.
200
201    ```text
202    # compute alpha zone
203    https://www.googleapis.com/compute/alpha/projects/my-project/zones/us-central1-c
204    ```
205
206- **Full resource name** - a schema-less URI consisting of a DNS-compatible API
207  service name and resource path. See the [full resource name API
208  documentation][resource-name-full] for more information.
209
210    ```text
211    # Compute snapshot
212    //compute.googleapis.com/project/my-project/snapshots/my-compute-snapshot
213
214    # Pubsub snapshot
215    //pubsub.googleapis.com/project/my-project/snapshots/my-pubsub-snapshot
216    ```
217
218- **Relative resource name** - A path-noscheme URI path, usually as accepted by
219  the API. Use this if the version or service are apparent from the resource
220  type. Please see the [relative resource name API
221  documentation][resource-name-relative] for more information.
222
223    ```text
224    # Storage bucket objects
225    buckets/my-bucket
226    buckets/my-bucket/objects/my-object
227
228    # PubSub topics
229    projects/my-project/topics/my-pubsub-topic
230    ```
231
232The nested `roles` attribute is an array of strings names of [GCP IAM
233roles][iam-roles]. The roles may be specified in the following formats:
234
235- **Global role name** - these are global roles built into Google Cloud. For the
236  full list of available roles, please see the [list of predefined GCP
237  roles][predefined-roles].
238
239    ```text
240    roles/viewer
241    roles/bigquery.user
242    roles/billing.admin
243    ```
244
245- **Organization-level custom role** - these are roles that are created at the
246  organization level by organization owners.
247
248    ```text
249    organizations/my-organization/roles/my-custom-role
250    ```
251
252    For more information, please see the documentation on [GCP custom
253    roles][custom-roles].
254
255- **Project-level custom role** - these are roles that are created at a
256  per-project level by project owners.
257
258    ```text
259    projects/my-project/roles/my-custom-role
260    ```
261
262    For more information, please see the documentation on [GCP custom
263    roles][custom-roles].
264
265
266## Authentication
267
268The Google Cloud Vault secrets backend uses the official Google Cloud Golang
269SDK. This means it supports the common ways of [providing credentials to Google
270Cloud][cloud-creds]. In addition to specifying `credentials` directly via Vault
271configuration, you can also get configuration from the following values **on the
272Vault server**:
273
2741. The environment variables `GOOGLE_APPLICATION_CREDENTIALS`. This is specified
275as the **path** to a Google Cloud credentials file, typically for a service
276account. If this environment variable is present, the resulting credentials are
277used. If the credentials are invalid, an error is returned.
278
2791. Default instance credentials. When no environment variable is present, the
280default service account credentials are used. This is useful when running Vault
281on [Google Compute Engine][gce] or [Google Kubernetes Engine][gke]
282
283For more information on service accounts, please see the [Google Cloud Service
284Accounts documentation][service-accounts].
285
286To use this storage backend, the service account must have the following
287minimum scope(s):
288
289```text
290https://www.googleapis.com/auth/cloud-platform
291```
292
293### Required Permissions
294
295The credentials given to Vault must have the following permissions:
296
297```text
298# Service Account + Key Admin
299iam.serviceAccounts.create
300iam.serviceAccounts.delete
301iam.serviceAccounts.get
302iam.serviceAccounts.list
303iam.serviceAccounts.update
304iam.serviceAccountKeys.create
305iam.serviceAccountKeys.delete
306iam.serviceAccountKeys.get
307iam.serviceAccountKeys.list
308
309# IAM Policy Changes
310<service>.<resource>.getIamPolicy
311<service>.<resource>.setIamPolicy
312```
313
314where `<service>` and `<resource>` correspond to permissions which will be
315granted, for example:
316
317```text
318# Projects
319resourcemanager.projects.getIamPolicy
320resourcemanager.projects.setIamPolicy
321
322# All compute
323compute.*.getIamPolicy
324compute.*.setIamPolicy
325```
326
327You can either:
328
329- Create a [custom role][custom-roles] using these permissions, and assign this
330  role at a project-level
331
332- Assign the set of roles required to get resource-specific
333  `getIamPolicy/setIamPolicy` permissions. At a minimum you will need to assign
334  `roles/iam.serviceAccountAdmin` and `roles/iam.serviceAccountKeyAdmin` so
335  Vault can manage service accounts and keys.
336
337
338## Things to Note
339
340### Access Tokens vs. Service Account Keys
341
342Advantages of `access_tokens`:
343* Can generate infinite number of tokens per roleset
344
345Disadvantages of `access_tokens`:
346* Cannot be used with some client libraries or tools
347* Have a static life-time of 1 hr that cannot be modified, revoked, or extended.
348
349Advantages of `service_account_keys`:
350* Controllable life-time through Vault, allowing for longer access
351* Can be used by all normal GCP tooling
352
353Disadvantages of `service_account_keys`:
354* Infinite lifetime in GCP (i.e. if they are not managed properly, leaked keys can live forever)
355* Limited to 10 per roleset/service account.
356
357When generating OAuth access tokens, Vault will still
358generate a dedicated service account and key. This private key is stored in Vault
359and is never accessible to other users, and the underlying key can
360be rotated. See the [GCP API documentation][api] for more information on
361rotation.
362
363### Service Accounts are Tied to Rolesets
364
365Service Accounts are created when the roleset is created (or updated) rather
366than each time a secret is generated. This may be different from how other
367secrets engines behave, but it is for good reasons:
368
369- IAM Service Account creation and permission propagation can take up to 60
370  seconds to complete. By creating the Service Account in advance, we speed up
371  the timeliness of future operations and reduce the flakiness of automated
372  workflows.
373
374- Each GCP project has a limit on the number of IAM Service Accounts. You can
375  [request additional quota][quotas]. The quota increase is processed by humans,
376  so it is best to request this additional quota in advance. This limit is
377  currently 100, **including system-managed Service Accounts**. If Service
378  Accounts were created per secret, this quota limit would reduce the number of
379  secrets that can be generated.
380
381### Service Account Keys Quota Limits
382
383GCP IAM has a hard limit (currently 10) on the number of Service Account keys.
384Attempts to generate more keys will result in an error. If you find yourself
385running into this limit, consider the following:
386
387- Have shorter TTLs or revoke access earlier. If you are not using past Service
388  Account keys, consider rotating and freeing quota earlier.
389
390- Create additional rolesets which share the same set of permissions. Additional
391  rolesets can be created with the same set of permissions. This will create a
392  new service account and increases the number of keys you can create.
393
394- Where possible, use OAuth2 access tokens instead of Service Account keys.
395
396### Resources Must Exist at Roleset Creation
397
398Because we the bindings for the Service Account are set during roleset creation,
399resources that do not exist will fail the `getIamPolicy` API call.
400
401### Roleset Creation May Partially Fail
402
403Every Service Account creation, key creation, and IAM policy change is a GCP API
404call per resource. If an API call to one of these resources fails, the roleset
405creation fails and Vault will attempt to rollback.
406
407These rollbacks are API calls, so they may also fail. The secrets engine uses a
408WAL to ensure that unused bindings are cleaned up. In the case of quota limits,
409you may need to clean these up manually.
410
411### Do Not Modify Vault-owned IAM Accounts
412
413While Vault will initially create and assign permissions to IAM service
414accounts, it is possible that an external user deletes or modifies this service
415account. These changes are difficult to detect, and it is best to prevent this
416type of modification through IAM permissions.
417
418Vault roleset Service Accounts will have emails in the format:
419
420```
421vault<roleset-prefix>-<creation-unix-timestamp>@...
422```
423
424Communicate with your teams (or use IAM permissions) to not modify these
425resources.
426
427
428## Help &amp; Support
429
430The Google Cloud Vault secrets engine is written as an external Vault plugin and
431thus exists outside the main Vault repository. It is automatically bundled with
432Vault releases, but the code is managed separately.
433
434Please report issues, add feature requests, and submit contributions to the
435[vault-plugin-secrets-gcp repo on GitHub][repo].
436
437
438## API
439The GCP secrets engine has a full HTTP API. Please see the [GCP secrets engine API docs][api]
440for more details.
441
442[api]: https://vaultproject.io/api/secret/gcp/index.html
443[cloud-creds]: https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application
444[custom-roles]: https://cloud.google.com/iam/docs/creating-custom-roles
445[gce]: https://cloud.google.com/compute/
446[gke]: https://cloud.google.com/kubernetes-engine/
447[iam-keys]: https://cloud.google.com/iam/docs/service-accounts#service_account_keys
448[iam-roles]: https://cloud.google.com/iam/docs/understanding-roles
449[predefined-roles]: https://cloud.google.com/iam/docs/understanding-roles#predefined_roles
450[repo]: https://github.com/hashicorp/vault-plugin-secrets-gcp
451[resource-name-full]: https://cloud.google.com/apis/design/resource_names#full_resource_name
452[resource-name-relative]: https://cloud.google.com/apis/design/resource_names#relative_resource_name
453[quotas]: https://cloud.google.com/compute/quotas
454[service-accounts]: https://cloud.google.com/compute/docs/access/service-accounts
455
456
457## Upgrade Guides
458
459### Deprecation of Access Token Leases
460
461~> **NOTE**: This only affects access tokens. There is no change to the `service_account_key` secret type
462
463Previous versions of this secrets engine (Vault <= 0.11.1) created a lease for
464each access token secret. We have removed them after discovering that these
465tokens, specifically Google OAuth2 tokens for IAM service accounts, are
466non-revocable and have a static 60 minute lifetime. To match the current
467limitations of the GCP APIs, the secrets engine will no longer allow for
468revocation or manage the token TTL - more specifically, **the access_token
469response will no longer include `lease_id` or other lease information**. This
470change does not reflect any change to the actual underlying OAuth tokens or GCP
471service accounts.
472
473To upgrade:
474
475- Remove references from `lease_id`, `lease_duration` or other `lease_*`
476  attributes when reading responses for the access tokens secrets endpoint (i.e.
477  from `gcp/token/$roleset`). See the [documentation for access
478  tokens](#access-tokens) to see the new format for the response.
479
480- Be aware of leftover leases from previous versions. While these old leases
481  will still be revocable, they will not actually invalidate their associated
482  access token, and that token will still be useable for up to one hour.
483