Skip to content
56 changes: 56 additions & 0 deletions secret-manager/createSecretWithCmek.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(parent, secretId, kmsKeyName) {
// [START secretmanager_create_secret_with_cmek]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'projects/my-project';
// const secretId = 'my-secret-with-cmek';
// const kmsKeyName = 'projects/my-project/locations/global/keyRings/my-keyring/cryptoKeys/my-key';

// Import the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Create the Secret Manager client
const client = new SecretManagerServiceClient();

async function createSecretWithCmek() {
// Create the secret with automatic replication and CMEK
const [secret] = await client.createSecret({
parent: parent,
secretId: secretId,
secret: {
replication: {
automatic: {
customerManagedEncryption: {
kmsKeyName: kmsKeyName,
},
},
},
},
});

console.log(`Created secret ${secret.name} with CMEK key ${kmsKeyName}`);
}

createSecretWithCmek();
Comment on lines +32 to +51
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function createSecretWithCmek which is defined and immediately called is redundant. You can simplify the code by moving the logic from createSecretWithCmek directly into main. This will make the code more concise and easier to read.

    // Create the secret with automatic replication and CMEK
    const [secret] = await client.createSecret({
      parent: parent,
      secretId: secretId,
      secret: {
        replication: {
          automatic: {
            customerManagedEncryption: {
              kmsKeyName: kmsKeyName,
            },
          },
        },
      },
    });

    console.log(`Created secret ${secret.name} with CMEK key ${kmsKeyName}`);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample. For consistency with other samples this is not required.

// [END secretmanager_create_secret_with_cmek]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
62 changes: 62 additions & 0 deletions secret-manager/createSecretWithUserManagedReplicationPolicy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(parent, secretId, locations, ttl) {
// [START secretmanager_create_ummr_secret]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const parent = 'projects/my-project';
// const secretId = 'my-new-secret';
// const locations = ['us-east1', 'europe-west1'];
// const ttl = 7776000; // Optional: 90 days in seconds

// Import the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Create the Secret Manager client
const client = new SecretManagerServiceClient();

async function createUmmrSecret() {
// Create the secret configuration
const secretConfig = {
replication: {
userManaged: {
replicas: locations.map(location => ({location})),
},
},
ttl: {
seconds: ttl,
},
};
Comment on lines +35 to +44
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

When ttl is null, the secretConfig object will have ttl: { seconds: null }. This might cause an API error if the backend expects the ttl field to be absent or to contain a valid duration. It's safer to conditionally add the ttl property to the secretConfig object only when a ttl value is provided.

    const secretConfig = {
      replication: {
        userManaged: {
          replicas: locations.map(location => ({location})),
        },
      },
    };

    if (ttl) {
      secretConfig.ttl = {
        seconds: ttl,
      };
    }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


// Create the secret
const [secret] = await client.createSecret({
parent: parent,
secretId: secretId,
secret: secretConfig,
});

console.log(`Created secret: ${secret.name}`);
}

createUmmrSecret();
Comment on lines +33 to +56
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function createUmmrSecret which is defined and immediately called is redundant. You can simplify the code by moving the logic from createUmmrSecret directly into main. This will make the code more concise and easier to read.

    // Create the secret configuration
    const secretConfig = {
      replication: {
        userManaged: {
          replicas: locations.map(location => ({location})),
        },
      },
      ttl: {
        seconds: ttl,
      },
    };

    // Create the secret
    const [secret] = await client.createSecret({
      parent: parent,
      secretId: secretId,
      secret: secretConfig,
    });

    console.log(`Created secret: ${secret.name}`);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample. For consistency with other samples this is not required.

// [END secretmanager_create_ummr_secret]
}

const args = process.argv.slice(2);
const locations = args[2] ? args[2].split(',') : [];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The command-line argument parsing is brittle. If an empty string is passed for locations (e.g., to specify a ttl without locations), args[2].split(',') results in [''], which will likely cause an API error. A more robust way to handle this is to filter out empty strings from the locations array.

const locations = args[2] ? args[2].split(',').filter(l => l) : [];

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is passed by user and empty string should not be given into replication locations

main(args[0], args[1], locations, args[3]).catch(console.error);
72 changes: 72 additions & 0 deletions secret-manager/detachTagBinding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(name, tagValue) {
// [START secretmanager_detach_tag_binding]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const name = 'projects/my-project/secrets/my-secret';
// const tagValue = 'tagValues/123456789012';

// Import the Resource Manager and Secret Manager libraries
const {TagBindingsClient} = require('@google-cloud/resource-manager').v3;

// Create the Resource Manager client
const rmClient = new TagBindingsClient();

// Build the resource name of the parent secret
const parent = `//secretmanager.googleapis.com/${name}`;

async function detachTag() {
// Find the binding name for the given tag value
let bindingName = null;
const iterable = rmClient.listTagBindingsAsync(
{
parent: parent,
pageSize: 50,
},
{autoPaginate: false}
);

for await (const binding of iterable) {
if (binding.tagValue === tagValue) {
bindingName = binding.name;
break;
}
}

if (bindingName === null) {
console.log(`Tag binding for value ${tagValue} not found on ${name}.`);
return;
}

// Delete the tag binding
const [operation] = await rmClient.deleteTagBinding({
name: bindingName,
});

// Wait for the operation to complete
await operation.promise();
console.log(`Detached tag value ${tagValue} from ${name}`);
}

detachTag();
Comment on lines +34 to +67
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function detachTag which is defined and immediately called is redundant. You can simplify the code by moving the logic from detachTag directly into main. This will make the code more concise and easier to read.

    // Find the binding name for the given tag value
    let bindingName = null;
    const iterable = rmClient.listTagBindingsAsync(
      {
        parent: parent,
        pageSize: 50,
      },
      {autoPaginate: false}
    );

    for await (const binding of iterable) {
      if (binding.tagValue === tagValue) {
        bindingName = binding.name;
        break;
      }
    }

    if (bindingName === null) {
      console.log(`Tag binding for value ${tagValue} not found on ${name}.`);
      return;
    }

    // Delete the tag binding
    const [operation] = await rmClient.deleteTagBinding({
      name: bindingName,
    });

    // Wait for the operation to complete
    await operation.promise();
    console.log(`Detached tag value ${tagValue} from ${name}`);

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample. For consistency with other samples this is not required.

// [END secretmanager_detach_tag_binding]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
47 changes: 47 additions & 0 deletions secret-manager/listSecretVersionsWithFilter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(parent = 'projects/my-project/secrets/my-secret') {
// [START secretmanager_list_secret_versions_with_filter]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const parent = 'projects/my-project/secrets/my-secret';
const filterStr = 'state=DISABLED';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function listSecretVersionsWithFilter() {
const [versions] = await client.listSecretVersions({
parent: parent,
filter: filterStr,
});

versions.forEach(version => {
console.log(`Found version: ${version.name}`);
});
}

listSecretVersionsWithFilter();
Comment on lines +31 to +42
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function listSecretVersionsWithFilter which is defined and immediately called is redundant. You can simplify the code by moving the logic from listSecretVersionsWithFilter directly into main. This will make the code more concise and easier to read.

    const [versions] = await client.listSecretVersions({
      parent: parent,
      filter: filterStr,
    });

    versions.forEach(version => {
      console.log(`Found version: ${version.name}`);
    });

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample. For consistency with other samples this is not required.

// [END secretmanager_list_secret_versions_with_filter]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
52 changes: 52 additions & 0 deletions secret-manager/listSecretsWithFilter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(projectId) {
// [START secretmanager_list_secrets_with_filter]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'my-project';
const filterStr = 'labels.secretmanager=rocks';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

// Build the resource name of the parent project
const parent = `projects/${projectId}`;

// List all secrets
async function listSecretsWithFilter() {
const [secrets] = await client.listSecrets({
parent: parent,
filter: filterStr,
});

// Print each secret
for (const secret of secrets) {
console.log(`Found secret: ${secret.name}`);
}
}

listSecretsWithFilter();
Comment on lines +35 to +47
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function listSecretsWithFilter which is defined and immediately called is redundant. You can simplify the code by moving the logic from listSecretsWithFilter directly into main. This will make the code more concise and easier to read.

    const [secrets] = await client.listSecrets({
      parent: parent,
      filter: filterStr,
    });

    // Print each secret
    for (const secret of secrets) {
      console.log(`Found secret: ${secret.name}`);
    }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample.

// [END secretmanager_list_secrets_with_filter]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
63 changes: 63 additions & 0 deletions secret-manager/listTagBindings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

async function main(name = 'projects/my-project/secrets/my-secret') {
// [START secretmanager_list_tag_bindings]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const name = 'projects/my-project/secrets/my-secret';

// Import the Resource Manager and Secret Manager libraries
const {TagBindingsClient} = require('@google-cloud/resource-manager').v3;

// Create the Resource Manager client
const client = new TagBindingsClient();

// Build the resource name of the parent secret
const parent = `//secretmanager.googleapis.com/${name}`;

async function listTagBindings() {
// List all tag bindings
let foundBindings = false;

// Use paginate to handle any pagination in the response
const iterable = client.listTagBindingsAsync(
{
parent: parent,
pageSize: 10,
},
{autoPaginate: false}
);

console.log(`Tag bindings for ${name}:`);

for await (const binding of iterable) {
console.log(`- Tag Value: ${binding.tagValue}`);
foundBindings = true;
}

if (!foundBindings) {
console.log(`No tag bindings found for ${name}.`);
}
}

listTagBindings();
Comment on lines +33 to +58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The main function is already async, so the nested async function listTagBindings which is defined and immediately called is redundant. You can simplify the code by moving the logic from listTagBindings directly into main. This will make the code more concise and easier to read.

    // List all tag bindings
    let foundBindings = false;

    // Use paginate to handle any pagination in the response
    const iterable = client.listTagBindingsAsync(
      {
        parent: parent,
        pageSize: 10,
      },
      {autoPaginate: false}
    );

    console.log(`Tag bindings for ${name}:`);

    for await (const binding of iterable) {
      console.log(`- Tag Value: ${binding.tagValue}`);
      foundBindings = true;
    }

    if (!foundBindings) {
      console.log(`No tag bindings found for ${name}.`);
    }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All samples contains inner function within main which is showing main functionality of the sample. For consistency with other samples this is not required.

// [END secretmanager_list_tag_bindings]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
Loading