When updating a resource in Google Cloud, you often want to modify specific fields without replacing the entire resource. The Cloud Client Libraries for Rust support field masks so that you can specify which fields an update operation modifies and leave all other fields unchanged.
Before you begin
This document uses the Secret Manager API, though the same concepts apply to other Google Cloud services.
Before running the code in this document, complete the following prerequisites:
- Follow Get started with Rust to set up your development environment.
- Follow Create and access a secret using Secret Manager to enable the Secret Manager API and configure authentication.
Dependencies
The google-cloud-wkt crate provides well-known types for Google Cloud
APIs, including FieldMask. Add google-cloud-secretmanager-v1,
google-cloud-wkt, anyhow, and tokio to your Cargo.toml file:
cargo add google-cloud-secretmanager-v1 google-cloud-wkt anyhow
cargo add tokio --features macros,rt-multi-thread
How field masks work
A FieldMask contains a set of symbolic field paths that identify which fields
an update operation modifies or a read operation returns.
In an update operation, the service changes only the fields listed in the mask and ignores values on any unlisted fields in the request message. If you omit the field mask on an update request, the operation applies to all mutable fields.
To reset a specific field to its default value, include the field path in the mask and leave that field at its default value on the resource struct.
Update fields on a resource
To create a secret and selectively update its labels and annotations fields
using a FieldMask, complete the following steps:
Initialize a
SecretManagerServiceclient and create a secret with emptylabelsandannotations:Send an
update_secretrequest that setslabels,annotations, the currentetagto prevent overwriting concurrent updates, and an update mask covering"annotations"and"labels":The
set_update_maskcall specifies the exact field paths to modify:
The output confirms that the operation updated both fields:
labels: {"updated": "your-label"},
...
annotations: {"updated": "your-annotations"},
Complete code
The following function combines secret creation and the field-mask update:
Clean up
To avoid incurring charges to your Google Cloud account and to prevent
ALREADY_EXISTS errors on subsequent runs, delete the your-secret
secret when you're finished.