• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 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 /*
18  * EDITING INSTRUCTIONS
19  * This file is referenced in README's and javadoc. Any change to this file should be reflected in
20  * the project's README's and package-info.java.
21  */
22 
23 package com.google.cloud.examples.dns.snippets;
24 
25 import com.google.cloud.dns.ChangeRequestInfo;
26 import com.google.cloud.dns.Dns;
27 import com.google.cloud.dns.DnsOptions;
28 import com.google.cloud.dns.RecordSet;
29 import com.google.cloud.dns.Zone;
30 import java.util.concurrent.TimeUnit;
31 
32 /** A snippet for Google Cloud DNS showing how to create and update a resource record set. */
33 public class CreateOrUpdateRecordSets {
34 
main(String... args)35   public static void main(String... args) {
36     // Create a service object.
37     // The project ID and credentials will be inferred from the environment.
38     Dns dns = DnsOptions.getDefaultInstance().getService();
39 
40     // Change this to a zone name that exists within your project
41     String zoneName = "my-unique-zone";
42 
43     // Get zone from the service
44     Zone zone = dns.getZone(zoneName);
45 
46     // Prepare a <i>www.<zone-domain>.</i> type A record set with ttl of 24 hours
47     String ip = "12.13.14.15";
48     RecordSet toCreate =
49         RecordSet.newBuilder("www." + zone.getDnsName(), RecordSet.Type.A)
50             .setTtl(24, TimeUnit.HOURS)
51             .addRecord(ip)
52             .build();
53 
54     // Make a change
55     ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder().add(toCreate);
56 
57     // Verify a www.<zone-domain>. type A record does not exist yet.
58     // If it does exist, we will overwrite it with our prepared record.
59     for (RecordSet current : zone.listRecordSets().iterateAll()) {
60       if (toCreate.getName().equals(current.getName())
61           && toCreate.getType().equals(current.getType())) {
62         changeBuilder.delete(current);
63       }
64     }
65 
66     // Build and apply the change request to our zone
67     ChangeRequestInfo changeRequest = changeBuilder.build();
68     zone.applyChangeRequest(changeRequest);
69   }
70 }
71