필드 마스크를 사용하여 리소스 업데이트

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 보안 비밀을 삭제하세요.