Skip to content

Commit 1857a33

Browse files
FrodoTheTruesofislSurferJeffAtGooglebcoe
authored
chore(samples): add delete protection samples (#696)
Co-authored-by: sofisl <[email protected]> Co-authored-by: Jeffrey Rennie <[email protected]> Co-authored-by: Benjamin E. Coe <[email protected]>
1 parent c11cc67 commit 1857a33

File tree

4 files changed

+303
-0
lines changed

4 files changed

+303
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Sends an instance creation request to the Compute Engine API and wait for it to complete.
17+
*
18+
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
19+
* @param {string} zone - Name of the zone you want to check, for example: us-west3-b
20+
* @param {string} instanceName - Name of the new virtual machine.
21+
* @param {string} deleteProtection - boolean value indicating if the new virtual machine should be
22+
* protected against deletion or not.
23+
*/
24+
25+
function main(projectId, zone, instanceName, deleteProtection) {
26+
// [START compute_delete_protection_create]
27+
/**
28+
* TODO(developer): Uncomment and replace these variables before running the sample.
29+
*/
30+
// const projectId = 'YOUR_PROJECT_ID';
31+
// const zone = 'europe-central2-b';
32+
// const instanceName = 'YOUR_INSTANCE_NAME';
33+
// const deleteProtection = true;
34+
35+
const compute = require('@google-cloud/compute');
36+
37+
// Send an instance creation request to the Compute Engine API and wait for it to complete.
38+
async function createInstance() {
39+
const instancesClient = new compute.InstancesClient();
40+
41+
const [response] = await instancesClient.insert({
42+
project: projectId,
43+
zone,
44+
instanceResource: {
45+
name: instanceName,
46+
// Set the delete protection bit.
47+
deletionProtection: deleteProtection,
48+
disks: [
49+
{
50+
// Describe the size and source image of the boot disk to attach to the instance.
51+
initializeParams: {
52+
diskSizeGb: '10',
53+
sourceImage:
54+
'projects/debian-cloud/global/images/family/debian-10',
55+
},
56+
autoDelete: true,
57+
boot: true,
58+
type: 'PERSISTENT',
59+
},
60+
],
61+
machineType: `zones/${zone}/machineTypes/e2-small`,
62+
networkInterfaces: [
63+
{
64+
// Use the default VPC network.
65+
name: 'default',
66+
},
67+
],
68+
},
69+
});
70+
let operation = response.latestResponse;
71+
const operationsClient = new compute.ZoneOperationsClient();
72+
73+
// Wait for the create operation to complete.
74+
while (operation.status !== 'DONE') {
75+
[operation] = await operationsClient.wait({
76+
operation: operation.name,
77+
project: projectId,
78+
zone: operation.zone.split('/').pop(),
79+
});
80+
}
81+
82+
console.log('Instance created.');
83+
}
84+
85+
createInstance();
86+
// [END compute_delete_protection_create]
87+
}
88+
89+
process.on('unhandledRejection', err => {
90+
console.error(err.message);
91+
process.exitCode = 1;
92+
});
93+
94+
const args = process.argv.slice(2);
95+
args[3] = args[3] === 'true';
96+
97+
main(...args);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Prints the state of delete protection flag of given instance.
17+
*
18+
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
19+
* @param {string} zone - Name of the zone you want to check, for example: us-west3-b
20+
* @param {string} instanceName - Name of the new virtual machine.
21+
*/
22+
23+
function main(projectId, zone, instanceName) {
24+
// [START compute_delete_protection_get]
25+
/**
26+
* TODO(developer): Uncomment and replace these variables before running the sample.
27+
*/
28+
// const projectId = 'YOUR_PROJECT_ID';
29+
// const zone = 'europe-central2-b';
30+
// const instanceName = 'YOUR_INSTANCE_NAME';
31+
32+
const compute = require('@google-cloud/compute');
33+
34+
// Print the state of delete protection flag of given instance.
35+
async function getDeleteProtection() {
36+
const instancesClient = new compute.InstancesClient();
37+
38+
const [instance] = await instancesClient.get({
39+
project: projectId,
40+
zone,
41+
instance: instanceName,
42+
});
43+
44+
console.log(
45+
`Instance ${instanceName} has deletionProtection value: ${instance.deletionProtection}`
46+
);
47+
}
48+
49+
getDeleteProtection();
50+
// [END compute_delete_protection_get]
51+
}
52+
53+
process.on('unhandledRejection', err => {
54+
console.error(err.message);
55+
process.exitCode = 1;
56+
});
57+
58+
main(...process.argv.slice(2));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* Updates the delete protection setting of given instance.
17+
*
18+
* @param {string} projectId - Project ID or project number of the Cloud project you want to use.
19+
* @param {string} zone - Name of the zone you want to check, for example: us-west3-b
20+
* @param {string} instanceName - Name of the new virtual machine.
21+
* @param {string} deleteProtection - boolean value indicating if the new virtual machine should be
22+
* protected against deletion or not.
23+
*/
24+
25+
function main(projectId, zone, instanceName, deleteProtection) {
26+
// [START compute_delete_protection_set]
27+
/**
28+
* TODO(developer): Uncomment and replace these variables before running the sample.
29+
*/
30+
// const projectId = 'YOUR_PROJECT_ID';
31+
// const zone = 'europe-central2-b';
32+
// const instanceName = 'YOUR_INSTANCE_NAME';
33+
// const deleteProtection = True;
34+
35+
const compute = require('@google-cloud/compute');
36+
37+
// Update the delete protection setting of given instance.
38+
async function setDeleteProtection() {
39+
const instancesClient = new compute.InstancesClient();
40+
41+
const [response] = await instancesClient.setDeletionProtection({
42+
project: projectId,
43+
zone,
44+
// Set the delete protection bit.
45+
deletionProtection: deleteProtection,
46+
resource: instanceName,
47+
});
48+
let operation = response.latestResponse;
49+
const operationsClient = new compute.ZoneOperationsClient();
50+
51+
// Wait for the create operation to complete.
52+
while (operation.status !== 'DONE') {
53+
[operation] = await operationsClient.wait({
54+
operation: operation.name,
55+
project: projectId,
56+
zone: operation.zone.split('/').pop(),
57+
});
58+
}
59+
60+
console.log('Instance updated.');
61+
}
62+
63+
setDeleteProtection();
64+
// [END compute_delete_protection_set]
65+
}
66+
67+
process.on('unhandledRejection', err => {
68+
console.error(err.message);
69+
process.exitCode = 1;
70+
});
71+
72+
const args = process.argv.slice(2);
73+
args[3] = args[3] === 'true';
74+
75+
main(...args);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2022 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
const compute = require('@google-cloud/compute');
18+
19+
const {describe, it} = require('mocha');
20+
const cp = require('child_process');
21+
const {assert} = require('chai');
22+
23+
const {generateTestId, getStaleVMInstances, deleteInstance} = require('./util');
24+
25+
const instancesClient = new compute.InstancesClient();
26+
27+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
28+
29+
describe('prevent accidental vm deletion tests', () => {
30+
const instanceName = generateTestId();
31+
const zone = 'europe-central2-b';
32+
33+
after(async () => {
34+
const instances = await getStaleVMInstances();
35+
await Promise.all(
36+
instances.map(instance =>
37+
deleteInstance(instance.zone, instance.instanceName)
38+
)
39+
);
40+
});
41+
42+
it('should create instance and set delete protection', async () => {
43+
const projectId = await instancesClient.getProjectId();
44+
45+
const outputCreate = execSync(
46+
`node instances/preventing-accidental-vm-deletion/createInstance ${projectId} ${zone} ${instanceName} true`
47+
);
48+
assert.match(outputCreate, /Instance created./);
49+
50+
const outputGet = execSync(
51+
`node instances/preventing-accidental-vm-deletion/getDeleteProtection ${projectId} ${zone} ${instanceName}`
52+
);
53+
assert.include(
54+
outputGet,
55+
`Instance ${instanceName} has deletionProtection value: true`
56+
);
57+
58+
const outputSet = execSync(
59+
`node instances/preventing-accidental-vm-deletion/setDeleteProtection ${projectId} ${zone} ${instanceName} false`
60+
);
61+
assert.include(outputSet, 'Instance updated.');
62+
63+
const outputGet2 = execSync(
64+
`node instances/preventing-accidental-vm-deletion/getDeleteProtection ${projectId} ${zone} ${instanceName}`
65+
);
66+
assert.include(
67+
outputGet2,
68+
`Instance ${instanceName} has deletionProtection value: false`
69+
);
70+
71+
execSync(`node deleteInstance ${projectId} ${zone} ${instanceName}`);
72+
});
73+
});

0 commit comments

Comments
 (0)