Skip to content

Commit 7c0e003

Browse files
authored
chore(samples): add custom hostname instances samples (#650)
1 parent 7196384 commit 7c0e003

File tree

3 files changed

+254
-0
lines changed

3 files changed

+254
-0
lines changed
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Copyright 2021 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+
* Creates an instance with custom hostname.
17+
*
18+
* @param {string} projectId - ID of the project in which you want to create the VM instance.
19+
* @param {string} zone - Name of the zone where you want to create the VM in, for example: us-west3-b.
20+
* @param {string} instanceName - Name of the new VM instance.
21+
* @param {string} hostname - Custom hostname of the new VM instance.
22+
* Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
23+
* @param {string} machineType - Machine type for the VM instance specified in the following format:
24+
* "zones/{zone}/machineTypes/{type_name}". For example:
25+
* "zones/europe-west3-c/machineTypes/f1-micro"
26+
* You can find the list of available machine types by using this gcloud command:
27+
* $ gcloud compute machine-types list
28+
* @param {string} sourceImage - Path of the disk image you want to use for your boot
29+
* disk. This image can be one of the public images
30+
* (for example, "projects/...)
31+
* or a private image you have access to.
32+
* You can check the list of available public images using:
33+
* $ gcloud compute images list
34+
* @param {string} networkName - Name of the network you want the new instance to use.
35+
* For example: global/networks/default - if you want to use the default network.
36+
*/
37+
function main(
38+
projectId,
39+
zone,
40+
instanceName,
41+
hostname,
42+
machineType = 'n1-standard-1',
43+
sourceImage = 'projects/debian-cloud/global/images/family/debian-10',
44+
networkName = 'global/networks/default'
45+
) {
46+
// [START compute_instances_create_custom_hostname]
47+
/**
48+
* TODO(developer): Uncomment and replace these variables before running the sample.
49+
*/
50+
// const projectId = 'YOUR_PROJECT_ID';
51+
// const zone = 'europe-central2-b'
52+
// const instanceName = 'YOUR_INSTANCE_NAME'
53+
// const hostname = 'host.example.com'
54+
// const machineType = 'n1-standard-1';
55+
// const sourceImage = 'projects/debian-cloud/global/images/family/debian-10';
56+
// const networkName = 'global/networks/default';
57+
58+
const compute = require('@google-cloud/compute');
59+
const computeProtos = compute.protos.google.cloud.compute.v1;
60+
61+
// Create a new instance with the values provided above in the specified project and zone.
62+
async function createInstanceWithCustomHostname() {
63+
const instancesClient = new compute.InstancesClient();
64+
65+
console.log(
66+
`Creating the ${instanceName} instance in ${zone} with hostname ${hostname}...`
67+
);
68+
69+
const [response] = await instancesClient.insert({
70+
instanceResource: {
71+
name: instanceName,
72+
// Custom hostnames are not resolved by the automatically created records
73+
// provided by Compute Engine internal DNS.
74+
// You must manually configure the DNS record for your custom hostname.
75+
hostname,
76+
disks: [
77+
{
78+
// Describe the size and source image of the boot disk to attach to the instance.
79+
initializeParams: {
80+
diskSizeGb: '10',
81+
sourceImage,
82+
},
83+
autoDelete: true,
84+
boot: true,
85+
type: computeProtos.AttachedDisk.Type.PERSISTENT,
86+
},
87+
],
88+
machineType: `zones/${zone}/machineTypes/${machineType}`,
89+
networkInterfaces: [
90+
{
91+
// Use the network interface provided in the networkName argument.
92+
name: networkName,
93+
},
94+
],
95+
},
96+
project: projectId,
97+
zone,
98+
});
99+
let operation = response.latestResponse;
100+
const operationsClient = new compute.ZoneOperationsClient();
101+
102+
// Wait for the create operation to complete.
103+
while (operation.status !== 'DONE') {
104+
[operation] = await operationsClient.wait({
105+
operation: operation.name,
106+
project: projectId,
107+
zone: operation.zone.split('/').pop(),
108+
});
109+
}
110+
111+
console.log('Instance created.');
112+
}
113+
114+
createInstanceWithCustomHostname();
115+
// [END compute_instances_create_custom_hostname]
116+
}
117+
118+
process.on('unhandledRejection', err => {
119+
console.error(err.message);
120+
process.exitCode = 1;
121+
});
122+
123+
main(...process.argv.slice(2));
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright 2021 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 hostname of the Google Cloud VM instance.
17+
*
18+
* @param {string} projectId - ID of the project in which you want to get the VM instance hostname.
19+
* @param {string} zone - Name of the zone your instance belongs to, for example: us-west3-b.
20+
* @param {string} instanceName - Name of the new VM instance.
21+
*/
22+
function main(projectId, zone, instanceName) {
23+
// [START compute_instances_get_hostname]
24+
/**
25+
* TODO(developer): Uncomment and replace these variables before running the sample.
26+
*/
27+
// const projectId = 'YOUR_PROJECT_ID';
28+
// const zone = 'europe-central2-b'
29+
// const instanceName = 'YOUR_INSTANCE_NAME'
30+
31+
const compute = require('@google-cloud/compute');
32+
33+
async function getInstanceHostname() {
34+
const instancesClient = new compute.InstancesClient();
35+
36+
const [instance] = await instancesClient.get({
37+
project: projectId,
38+
zone,
39+
instance: instanceName,
40+
});
41+
// If a custom hostname is not set, the output for instance.hostname will be undefined
42+
console.log(`Instance ${instanceName} has hostname: ${instance.hostname}`);
43+
}
44+
45+
getInstanceHostname();
46+
// [END compute_instances_get_hostname]
47+
}
48+
49+
process.on('unhandledRejection', err => {
50+
console.error(err.message);
51+
process.exitCode = 1;
52+
});
53+
54+
main(...process.argv.slice(2));
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Copyright 2021 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 uuid = require('uuid');
21+
const cp = require('child_process');
22+
const {assert} = require('chai');
23+
24+
const instancesClient = new compute.InstancesClient();
25+
26+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
27+
28+
const getInstance = async (projectId, zone, instanceName) => {
29+
const [instance] = await instancesClient.get({
30+
project: projectId,
31+
zone,
32+
instance: instanceName,
33+
});
34+
return instance;
35+
};
36+
37+
describe('Instance with a custom hostname samples', () => {
38+
const instanceName = `gcloud-test-instance-${uuid.v4().split('-')[0]}`;
39+
const zone = 'europe-central2-b';
40+
const custom_hostname = 'host.domain.com';
41+
42+
it('should create instance with a custom hostname and return correct hostname', async () => {
43+
const projectId = await instancesClient.getProjectId();
44+
let output = execSync(
45+
`node custom-hostname-instance/createInstanceWithCustomHostname ${projectId} ${zone} ${instanceName} ${custom_hostname}`
46+
);
47+
48+
const instance = await getInstance(projectId, zone, instanceName);
49+
50+
assert.equal(instance.hostname, custom_hostname);
51+
assert.match(output, /Instance created./);
52+
53+
output = execSync(
54+
`node custom-hostname-instance/getInstanceHostname ${projectId} ${zone} ${instanceName}`
55+
);
56+
57+
assert.include(
58+
output,
59+
`Instance ${instanceName} has hostname: ${custom_hostname}`
60+
);
61+
62+
execSync(`node deleteInstance ${projectId} ${zone} ${instanceName}`);
63+
});
64+
65+
it('should return undefined if hostname is not set', async () => {
66+
const projectId = await instancesClient.getProjectId();
67+
68+
execSync(`node createInstance ${projectId} ${zone} ${instanceName}`);
69+
const output = execSync(
70+
`node custom-hostname-instance/getInstanceHostname ${projectId} ${zone} ${instanceName}`
71+
);
72+
73+
assert.include(output, `Instance ${instanceName} has hostname: undefined`);
74+
75+
execSync(`node deleteInstance ${projectId} ${zone} ${instanceName}`);
76+
});
77+
});

0 commit comments

Comments
 (0)