Skip to content

chore(secretmanager): add global samples for delayed destroy #4073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions secret-manager/createSecretWithDelayedDestroy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2025 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, timeToLive) {
// [START secretmanager_create_secret_with_delayed_destroy]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const parent = 'projects/my-project';
// const secretId = 'my-secret';
// const timeToLive = 86400;

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

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

async function createSecretWithDelayedDestroy() {
const [secret] = await client.createSecret({
parent: parent,
secretId: secretId,
secret: {
replication: {
automatic: {},
},
version_destroy_ttl: {
seconds: timeToLive,
},
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider adding error handling here to catch any potential exceptions during secret creation. This will provide more informative error messages and prevent the program from crashing unexpectedly.

    }).catch(err => {
      console.error(`Failed to create secret: ${err}`);
      throw err; // Re-throw the error to prevent further execution
    });


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

createSecretWithDelayedDestroy();
// [END secretmanager_create_secret_with_delayed_destroy]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
48 changes: 48 additions & 0 deletions secret-manager/disableSecretDelayedDestroy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2025 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_disable_secret_delayed_destroy]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const name = 'projects/my-project/secrets/my-secret';

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

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

async function disableSecretDelayedDestroy() {
const [secret] = await client.updateSecret({
secret: {
name: name,
},
updateMask: {
paths: ['version_destroy_ttl'],
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider adding error handling here to catch any potential exceptions during secret updating. This will provide more informative error messages and prevent the program from crashing unexpectedly.

    }).catch(err => {
      console.error(`Failed to disable delayed destroy: ${err}`);
      throw err; // Re-throw the error to prevent further execution
    });


console.info(`Disabled delayed destroy ${secret.name}`);
}

disableSecretDelayedDestroy();
// [END secretmanager_disable_secret_delayed_destroy]
}

const args = process.argv.slice(2);
main(...args).catch(console.error);
56 changes: 56 additions & 0 deletions secret-manager/test/secretmanager.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -543,4 +543,60 @@ describe('Secret Manager samples', () => {
);
assert.match(output, new RegExp(`Destroyed ${regionalVersion.name}`));
});

it('creates a secret with delayed destroy enabled', async () => {
const timeToLive = 24 * 60 * 60;
const output = execSync(
`node createSecretWithDelayedDestroy.js projects/${projectId} ${secretId}-2 ${timeToLive}`
);
assert.match(output, new RegExp('Created secret'));
});

it('disables a secret delayed destroy', async () => {
await client.createSecret({
parent: `projects/${projectId}`,
secretId: `${secretId}-delayedDestroy`,
secret: {
replication: {
automatic: {},
},
version_destroy_ttl: {
seconds: 24 * 60 * 60,
},
},
});

const output = execSync(
`node disableSecretDelayedDestroy.js ${secret.name}-delayedDestroy`
);
Comment on lines +570 to +571
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 secret name ${secret.name}-delayedDestroy is hardcoded here. It would be better to generate a unique secret ID for this test to avoid potential conflicts with other tests or existing secrets. Also, consider adding a try-catch block around the deleteSecret call to handle cases where the secret might not exist.

    const delayedDestroySecretId = `${secretId}-delayedDestroy-${v4()}`;
    await client.createSecret({
      parent: `projects/${projectId}`,
      secretId: delayedDestroySecretId,
      secret: {
        replication: {
          automatic: {},
        },
        version_destroy_ttl: {
          seconds: 24 * 60 * 60,
        },
      },
    });

    const output = execSync(
      `node disableSecretDelayedDestroy.js projects/${projectId}/secrets/${delayedDestroySecretId}`
    );
    assert.match(output, new RegExp('Disabled delayed destroy'));

    try {
      await client.deleteSecret({
        name: `projects/${projectId}/secrets/${delayedDestroySecretId}`,
      });
    } catch (err) {
      console.warn(`Failed to delete secret ${delayedDestroySecretId}: ${err}`);
    }

assert.match(output, new RegExp('Disabled delayed destroy'));

await client.deleteSecret({
name: `${secret.name}-delayedDestroy`,
});
});

it('updates a secret delayed destroy', async () => {
const updatedTimeToLive = 24 * 60 * 60 * 2;
await client.createSecret({
parent: `projects/${projectId}`,
secretId: `${secretId}-delayedDestroy`,
secret: {
replication: {
automatic: {},
},
version_destroy_ttl: {
seconds: 24 * 60 * 60,
},
},
});

const output = execSync(
`node updateSecretWithDelayedDestroy.js ${secret.name}-delayedDestroy ${updatedTimeToLive}`
Comment on lines +594 to +595
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 secret name ${secret.name}-delayedDestroy is hardcoded here. It would be better to generate a unique secret ID for this test to avoid potential conflicts with other tests or existing secrets. Also, consider adding a try-catch block around the deleteSecret call to handle cases where the secret might not exist.

    const delayedDestroySecretId = `${secretId}-delayedDestroy-${v4()}`;
    const updatedTimeToLive = 24 * 60 * 60 * 2;
    await client.createSecret({
      parent: `projects/${projectId}`,
      secretId: delayedDestroySecretId,
      secret: {
        replication: {
          automatic: {},
        },
        version_destroy_ttl: {
          seconds: 24 * 60 * 60,
        },
      },
    });

    const output = execSync(
      `node updateSecretWithDelayedDestroy.js projects/${projectId}/secrets/${delayedDestroySecretId} ${updatedTimeToLive}`
    );
    assert.match(output, new RegExp('Updated secret'));
    try {
      await client.deleteSecret({
        name: `projects/${projectId}/secrets/${delayedDestroySecretId}`,
      });
    } catch (err) {
      console.warn(`Failed to delete secret ${delayedDestroySecretId}: ${err}`);
    }

);
assert.match(output, new RegExp('Updated secret'));
await client.deleteSecret({
name: `${secret.name}-delayedDestroy`,
});
});
});
55 changes: 55 additions & 0 deletions secret-manager/updateSecretWithDelayedDestroy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2025 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',
updatedTimeToLive
) {
// [START secretmanager_update_secret_with_delayed_destroy]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const name = 'projects/my-project/secrets/my-secret';
// const updatedTimeToLive = 86400;

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

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

async function updateSecret() {
const [secret] = await client.updateSecret({
secret: {
name: name,
version_destroy_ttl: {
seconds: updatedTimeToLive,
},
},
updateMask: {
paths: ['version_destroy_ttl'],
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Consider adding error handling here to catch any potential exceptions during secret updating. This will provide more informative error messages and prevent the program from crashing unexpectedly.

    }).catch(err => {
      console.error(`Failed to update secret: ${err}`);
      throw err; // Re-throw the error to prevent further execution
    });


console.info(`Updated secret ${secret.name}`);
}

updateSecret();
// [END secretmanager_update_secret_with_delayed_destroy]
}

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