Skip to content

Commit b623771

Browse files
authored
docs(compute-samples): init add samples for custom hostname (GoogleCloudPlatform#6678)
1 parent 99a6cf1 commit b623771

4 files changed

Lines changed: 276 additions & 4 deletions

File tree

compute/cloud-client/pom.xml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<!--
3-
Copyright 2021 Google LLC
3+
Copyright 2022 Google LLC
44
55
Licensed under the Apache License, Version 2.0 (the "License");
66
you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@
2323
<dependency>
2424
<artifactId>google-cloud-compute</artifactId>
2525
<groupId>com.google.cloud</groupId>
26-
<version>1.6.0-beta</version>
26+
<version>1.7.0</version>
2727
</dependency>
2828
<dependency>
2929
<artifactId>google-cloud-storage</artifactId>
@@ -32,12 +32,12 @@
3232
<dependency>
3333
<groupId>com.google.api</groupId>
3434
<artifactId>gax</artifactId>
35-
<version>2.7.1</version>
35+
<version>2.8.1</version>
3636
</dependency>
3737
<dependency>
3838
<groupId>com.google.api</groupId>
3939
<artifactId>gax-httpjson</artifactId>
40-
<version>0.92.1</version>
40+
<version>0.93.1</version>
4141
</dependency>
4242

4343

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.customhostname;
18+
19+
// [START compute_instances_create_custom_hostname]
20+
21+
import com.google.cloud.compute.v1.AttachedDisk;
22+
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
23+
import com.google.cloud.compute.v1.InsertInstanceRequest;
24+
import com.google.cloud.compute.v1.Instance;
25+
import com.google.cloud.compute.v1.InstancesClient;
26+
import com.google.cloud.compute.v1.NetworkInterface;
27+
import com.google.cloud.compute.v1.Operation;
28+
import java.io.IOException;
29+
import java.util.concurrent.ExecutionException;
30+
31+
public class CreateInstanceWithCustomHostname {
32+
33+
public static void main(String[] args)
34+
throws IOException, ExecutionException, InterruptedException {
35+
// TODO(developer): Replace these variables before running the sample.
36+
// hostName: Custom hostname of the new VM instance.
37+
// * Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
38+
String project = "your-project-id";
39+
String zone = "zone-name"; // eg: "us-central1-a"
40+
String instanceName = "instance-name";
41+
String hostName = "host.example.com";
42+
createInstanceWithCustomHostname(project, zone, instanceName, hostName);
43+
}
44+
45+
// Creates an instance with custom hostname.
46+
public static void createInstanceWithCustomHostname(String projectId, String zone,
47+
String instanceName, String hostName)
48+
throws IOException, ExecutionException, InterruptedException {
49+
// machineType - Machine type for the VM instance specified in the following format:
50+
// * "zones/{zone}/machineTypes/{type_name}". For example:
51+
// * "zones/europe-west3-c/machineTypes/f1-micro"
52+
// * You can find the list of available machine types by using this gcloud command:
53+
// * $ gcloud compute machine-types list
54+
// sourceImage - Path of the disk image you want to use for your boot
55+
// * disk. This image can be one of the public images
56+
// * eg: "projects/...
57+
// * or a private image you have access to.
58+
// * You can check the list of available public images using:
59+
// * $ gcloud compute images list
60+
// networkName - Name of the network you want the new instance to use.
61+
// * For example: global/networks/default - if you want to use the default network.
62+
String machineType = "n1-standard-1";
63+
String sourceImage = String.format("projects/%s/global/images/family/%s", "debian-cloud",
64+
"debian-11");
65+
String networkName = "global/networks/default";
66+
67+
try (InstancesClient instancesClient = InstancesClient.create()) {
68+
System.out.printf("Creating the %s instance in %s with hostname %s...", instanceName, zone,
69+
hostName);
70+
71+
AttachedDisk disk =
72+
AttachedDisk.newBuilder()
73+
.setBoot(true)
74+
.setAutoDelete(true)
75+
.setType(AttachedDisk.Type.PERSISTENT.toString())
76+
.setInitializeParams(
77+
// Describe the size and source image of the boot disk to attach to the instance.
78+
AttachedDiskInitializeParams.newBuilder()
79+
.setSourceImage(sourceImage)
80+
.setDiskSizeGb(10).build())
81+
.build();
82+
83+
// Use the network interface provided in the networkName argument.
84+
NetworkInterface networkInterface = NetworkInterface.newBuilder()
85+
.setName(networkName)
86+
.build();
87+
88+
Instance instanceResource = Instance.newBuilder()
89+
// Custom hostnames are not resolved by the automatically created records
90+
// provided by Compute Engine internal DNS.
91+
// You must manually configure the DNS record for your custom hostname.
92+
.setName(instanceName)
93+
.setHostname(hostName)
94+
.addDisks(disk)
95+
.setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
96+
.addNetworkInterfaces(networkInterface).build();
97+
98+
InsertInstanceRequest request = InsertInstanceRequest.newBuilder()
99+
.setProject(projectId)
100+
.setZone(zone)
101+
.setInstanceResource(instanceResource).build();
102+
103+
// Wait for the create operation to complete.
104+
Operation response = instancesClient.insertAsync(request).get();
105+
106+
if (response.hasError()) {
107+
System.out.printf("Instance creation failed for instance: %s ; Response: %s ! ! ",
108+
instanceName, response);
109+
return;
110+
}
111+
System.out.printf("Instance created : %s", instanceName);
112+
System.out.printf("Operation Status for instance %s is %s: ", instanceName,
113+
response.getStatus());
114+
}
115+
116+
}
117+
118+
}
119+
// [END compute_instances_create_custom_hostname]
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.customhostname;
18+
19+
// [START compute_instances_get_hostname]
20+
21+
import com.google.cloud.compute.v1.Instance;
22+
import com.google.cloud.compute.v1.InstancesClient;
23+
import java.io.IOException;
24+
25+
public class GetInstanceHostname {
26+
27+
public static void main(String[] args) throws IOException {
28+
// TODO(developer): Replace these variables before running the sample.
29+
String project = "your-project-id";
30+
String zone = "zone-name"; // eg: "us-central1-a"
31+
String instanceName = "instance-name"; // Name of the VM instance to retrieve.
32+
33+
getInstanceHostname(project, zone, instanceName);
34+
}
35+
36+
// Retrieves the hostname of the Google Cloud VM instance.
37+
public static void getInstanceHostname(String projectId, String zone, String instanceName)
38+
throws IOException {
39+
try (InstancesClient instancesClient = InstancesClient.create()) {
40+
41+
Instance instance = instancesClient.get(projectId, zone, instanceName);
42+
43+
if (instance.hasHostname()) {
44+
// If a custom hostname is not set, the output for instance.getHostname() will be undefined.
45+
System.out.printf("Custom Hostname for the instance %s is: %s", instanceName,
46+
instance.getHostname());
47+
}
48+
}
49+
}
50+
51+
}
52+
// [END compute_instances_get_hostname]
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package compute.customhostname;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
import static com.google.common.truth.Truth.assertWithMessage;
21+
22+
import compute.DeleteInstance;
23+
import java.io.ByteArrayOutputStream;
24+
import java.io.IOException;
25+
import java.io.PrintStream;
26+
import java.util.UUID;
27+
import java.util.concurrent.ExecutionException;
28+
import org.junit.After;
29+
import org.junit.AfterClass;
30+
import org.junit.Before;
31+
import org.junit.BeforeClass;
32+
import org.junit.Test;
33+
import org.junit.runner.RunWith;
34+
import org.junit.runners.JUnit4;
35+
36+
@RunWith(JUnit4.class)
37+
public class CustomHostnameInstanceIT {
38+
39+
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
40+
private static String INSTANCE_NAME;
41+
private static String ZONE;
42+
private static String CUSTOM_HOSTNAME;
43+
44+
private ByteArrayOutputStream stdOut;
45+
46+
// Check if the required environment variables are set.
47+
public static void requireEnvVar(String envVarName) {
48+
assertWithMessage(String.format("Missing environment variable '%s' ", envVarName))
49+
.that(System.getenv(envVarName)).isNotEmpty();
50+
}
51+
52+
@BeforeClass
53+
public static void setup() throws IOException, ExecutionException, InterruptedException {
54+
final PrintStream out = System.out;
55+
ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
56+
System.setOut(new PrintStream(stdOut));
57+
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
58+
requireEnvVar("GOOGLE_CLOUD_PROJECT");
59+
60+
INSTANCE_NAME = "my-custom-hostname-test-instance" + UUID.randomUUID().toString().split("-")[0];
61+
ZONE = "us-central1-a";
62+
CUSTOM_HOSTNAME = "host.domain.com";
63+
64+
// Create Instance with a custom hostname.
65+
CreateInstanceWithCustomHostname.createInstanceWithCustomHostname(PROJECT_ID, ZONE,
66+
INSTANCE_NAME, CUSTOM_HOSTNAME);
67+
assertThat(stdOut.toString()).contains("Instance created : " + INSTANCE_NAME);
68+
69+
stdOut.close();
70+
System.setOut(out);
71+
}
72+
73+
@AfterClass
74+
public static void cleanUp() throws IOException, ExecutionException, InterruptedException {
75+
final PrintStream out = System.out;
76+
ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
77+
System.setOut(new PrintStream(stdOut));
78+
DeleteInstance.deleteInstance(PROJECT_ID, ZONE, INSTANCE_NAME);
79+
stdOut.close();
80+
System.setOut(out);
81+
}
82+
83+
@Before
84+
public void beforeEach() {
85+
stdOut = new ByteArrayOutputStream();
86+
System.setOut(new PrintStream(stdOut));
87+
}
88+
89+
@After
90+
public void afterEach() {
91+
stdOut = null;
92+
System.setOut(null);
93+
}
94+
95+
@Test
96+
public void testGetInstanceHostname() throws IOException {
97+
GetInstanceHostname.getInstanceHostname(PROJECT_ID, ZONE, INSTANCE_NAME);
98+
assertThat(stdOut.toString()).contains(CUSTOM_HOSTNAME);
99+
}
100+
101+
}

0 commit comments

Comments
 (0)