Search code examples
google-cloud-platformgoogle-secret-manager

Automatically Grab Latest Google Cloud Platform Secret Version


I'm trying to grab the latest secret version. Is there a way to do that without specifying the version number? Such as using the keyword "latest". I'm trying to avoid having to iterate through all the secret versions with a for loop as GCP documentation shows:

try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
  // Build the parent name.
  SecretName projectName = SecretName.of(projectId, secretId);

  // Get all versions.
  ListSecretVersionsPagedResponse pagedResponse = client.listSecretVersions(projectName);

  // List all versions and their state.
  pagedResponse
      .iterateAll()
      .forEach(
          version -> {
            System.out.printf("Secret version %s, %s\n", version.getName(), version.getState());
          });
}

Solution

  • Yes, you can use "latest" as the version number. This is called an "alias". At present, the only alias is "latest", but we may support more aliases in the future.

    gcloud secrets versions access "latest" --secret "my-secret"
    
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, "latest"); // <-- here
    
      // Access the secret version.
      AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
    
      String payload = response.getPayload().getData().toStringUtf8();
      System.out.printf("Plaintext: %s\n", payload);
    }