フィールド マスクを使用してリソースを更新する

Google Cloudでリソースを更新する場合、リソース全体を置き換えることなく、特定のフィールドを変更することがよくあります。Rust 用の Cloud クライアント ライブラリはフィールド マスクをサポートしているため、更新オペレーションで変更するフィールドを指定し、他のすべてのフィールドを変更しないままにできます。

始める前に

このドキュメントでは Secret Manager API を使用しますが、他の Google Cloud サービスにも同じコンセプトが適用されます。

このドキュメントのコードを実行する前に、次の前提条件を満たしてください。

依存関係

google-cloud-wkt クレートは、FieldMask を含む Google CloudAPI のよく知られた型を提供します。google-cloud-secretmanager-v1、google-cloud-wkt、anyhow、tokio を Cargo.toml ファイルに追加します。

cargo add google-cloud-secretmanager-v1 google-cloud-wkt anyhow
cargo add tokio --features macros,rt-multi-thread

フィールド マスクの仕組み

FieldMask には、更新オペレーションで変更するフィールドや読み取りオペレーションで返すフィールドを識別する一連のシンボリック フィールドパスが含まれています。

更新オペレーションでは、サービスはマスクにリストされているフィールドのみを変更し、リクエスト メッセージ内のリストにないフィールドの値は無視します。更新リクエストでフィールド マスクを省略すると、オペレーションはすべての変更可能なフィールドに適用されます。

特定のフィールドをデフォルト値にリセットするには、マスクにフィールドパスを含め、リソース構造体でそのフィールドをデフォルト値のままにします。

リソースのフィールドを更新する

シークレットを作成し、FieldMask を使用して labels フィールドと annotations フィールドを選択的に更新するには、次の手順を完了します。

  1. SecretManagerService クライアントを初期化し、空の labels と annotations を含むシークレットを作成します。

    let client = SecretManagerService::builder().build().await?;
    
    let secret = client
        .create_secret()
        .set_parent(format!("projects/{project_id}"))
        .set_secret_id("your-secret")
        .set_secret(
            Secret::new().set_replication(Replication::new().set_automatic(Automatic::new())),
        )
        .send()
        .await?;
    println!("CREATE = {secret:?}");

  2. labels、annotations、現在の etag(同時更新の上書きを防ぐため)、"annotations" と "labels" をカバーする更新マスクを設定する update_secret リクエストを送信します。

    let tag = |mut labels: HashMap<_, _>, msg: &str| {
        labels.insert("updated".to_string(), msg.to_string());
        labels
    };
    
    let update = client
        .update_secret()
        .set_secret(
            Secret::new()
                .set_name(&secret.name)
                .set_etag(secret.etag)
                .set_labels(tag(secret.labels, "your-label"))
                .set_annotations(tag(secret.annotations, "your-annotations")),
        )
        .set_update_mask(FieldMask::default().set_paths(["annotations", "labels"]))
        .send()
        .await?;
    println!("UPDATE = {update:?}");

    set_update_mask 呼び出しでは、変更する正確なフィールドパスを指定します。

    .set_update_mask(FieldMask::default().set_paths(["annotations", "labels"]))

出力で、オペレーションによって両方のフィールドが更新されたことを確認できます。

labels: {"updated": "your-label"},
...
annotations: {"updated": "your-annotations"},

コードを補完する

次の関数は、シークレットの作成とフィールド マスクの更新を組み合わせたものです。

use google_cloud_secretmanager_v1::client::SecretManagerService;
use google_cloud_secretmanager_v1::model::replication::Automatic;
use google_cloud_secretmanager_v1::model::{Replication, Secret};
use google_cloud_wkt::FieldMask;
use std::collections::HashMap;

pub async fn sample(project_id: &str) -> anyhow::Result<()> {
    let client = SecretManagerService::builder().build().await?;

    let secret = client
        .create_secret()
        .set_parent(format!("projects/{project_id}"))
        .set_secret_id("your-secret")
        .set_secret(
            Secret::new().set_replication(Replication::new().set_automatic(Automatic::new())),
        )
        .send()
        .await?;
    println!("CREATE = {secret:?}");

    let tag = |mut labels: HashMap<_, _>, msg: &str| {
        labels.insert("updated".to_string(), msg.to_string());
        labels
    };

    let update = client
        .update_secret()
        .set_secret(
            Secret::new()
                .set_name(&secret.name)
                .set_etag(secret.etag)
                .set_labels(tag(secret.labels, "your-label"))
                .set_annotations(tag(secret.annotations, "your-annotations")),
        )
        .set_update_mask(FieldMask::default().set_paths(["annotations", "labels"]))
        .send()
        .await?;
    println!("UPDATE = {update:?}");

    Ok(())
}

クリーンアップ

Google Cloud アカウントに課金されないようにし、後続の実行で ALREADY_EXISTS エラーが発生しないようにするには、完了後に your-secret シークレットを削除します。