Click here to Skip to main content
15,887,683 members
Articles / DNS
Article

Getting started with Google Cloud DNS

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Dec 2014CC (Attr 3U)5 min read 56.9K   2  
This document demonstrates authenticating, creating a managed zone, and creating a resource record

This article is for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers

You can use the Google Cloud DNS API from either the gcloud command-line tool or directly using the REST API. This document demonstrates authenticating, creating a managed zone, and creating a resource record. The command-line tool requires that you install the Google Cloud SDK. The REST API examples demonstrate enabling the API, creating an HTML page, and calling the API with the Google JavaScript client library.

Prerequisites

To enable Google Cloud DNS, you must create a Google Developers Console project or use an existing project. In the project, you must enable the Cloud DNS API, accept the Terms of Service agreement when prompted, and enable billing for your project if you have not already done so. Note the project ID for use in the next section to authorize requests.

The user must be authorized in the team area of the project in the Google Developers Console. They require owner or editor rights to make changes or viewer rights to list or view the current DNS configuration.

The command-line tool requires the Google Cloud SDK. Run the gcloud components update dns command to ensure that you have the DNS commands in your environment.

Recommended: You should verify ownership of the domain that you want to manage.

Authorize the requests

Before you can read or modify DNS settings, you must authenticate with the REST API or the gcloud command-line tool.

Command line

Set up the command-line tool and authorize it to make API requests on your behalf:

  1. Install the Cloud SDK. If you already have the SDK installed, run the gcloud components update dns command to ensure that you have the DNS commands in your environment.

  2. Authenticate on the command-line:

    gcloud auth login
  3. Click Accept in the authorization dialog that displays in your browser. You can close the browser window after clicking accept.

  4. The command next prompts you to enter the project ID. Enter the value from the Developers Console that you created earlier.

Your gcloud command-line tool is now ready to use and will make all requests against the project ID that you entered. You can change this value later by re-running this command or by specifying the --project=NEW_PROJ_ID parameter for a command.

JavaScript

Enable the API

Before you can use the REST API, you must enable the Google Cloud DNS API in the Google Developers Console and create a client ID to allow your sample app to connect to the Google APIs. This document assumes you are testing the sample on http://localhost:8080.

 

  1. If you don't already have one, sign up for a Google account.
  2. Enable the Google Cloud DNS API in the Developers Console. You can choose an existing Compute Engine or App Engine project, or you can create a new project.
  3. If you need to make requests to the REST API, you will need to create an OAuth 2.0 ID:
    1. On the Credentials page in the APIs & Auth section, click Create new client ID.
    2. Choose Web application.
    3. In the Authorized JavaScript origins enter the host where you will serve this example, for example, http://localhost:8080 .
    4. Click Create Client ID.
  4. Note the following information in the project that you will need to input in later steps:
    • The client ID (xxxxxx.apps.googleusercontent.com).
    • The project ID that you wish to use. You can find the ID at the top of the Overview page in the Developers Console. You could also ask your user to provide the project name that they want to use in your app.

 

Now that the API is enabled for your project, you will configure your app to access the REST API on behalf of a user.

Set up the OAuth 2.0 flow

This example demonstrates a simple OAuth 2.0 flow using JavaScript that asks the user to authorize your app to make requests on their behalf. The user must have owner or editor access to the project in the team area of the {{ console_name }}. The OAuth 2.0 scope https://www.googleapis.com/auth/ndev.clouddns.readwrite grants your app access to read and write to the Cloud DNS API.

<button id="authButton">Authorize</button>
<script type="text/javascript">
// Array of scopes
var authParams = {
  'response_type' : 'token', // Retrieves an access token only
  'client_id' : 'xxxxxxx.apps.googleusercontent.com', // Client ID from Developers Console
  'immediate' : false, // For the demo, force the auth window every time
  'scope' : ['https://www.googleapis.com/auth/ndev.clouddns.readwrite']  // Array of scopes
};

function myCallback(authResult){
  if (authResult && authResult['access_token']) {
    // User granted authorization
    // Set the token for later API calls
    gapi.auth.setToken(authResult);
    ... // Next step, load API and query API
  } else {
    // Authorization failed or user declined
  }
}

// Attach a click even to an authorization button. Use clicks to trigger
// the flow so that the pop-up window succeeds.
document.getElementById('authButton').onclick = function(){
  gapi.auth.authorize(authParams, myCallback)
};
</script>

Now that you are authenticated, you can interact with the Cloud DNS API.

Creating a managed zone and a record

Now that your app has an access token, your app can manage zones and records. The following example demonstrates creating a managed zone and then creating an A record within that zone.

Command line

Create a managed zone and pass the required parameters. The zone name must be lower case, alphanumeric, and can contain a hyphen.

gcloud dns managed-zone create --dns_name="example.com." --description="A test zone" examplezonename

Next, create a DNS record within the examplezonename zone:

gcloud dns records --zone=examplezonename edit

In the editor that appears, an example of a change with both the additions and deletions sections are displayed. You can edit this JSON format and enter your additions, deletions or both.

{
  "additions": [
    {
      "kind": "dns#resourceRecordSet",
      "name": "example.com.",
      "rrdatas": [
        "ns-cloud1.googledomains.com. dns-admin.google.com. 1 21600 3600 1209600 300"
      ],
      "ttl": 21600,
      "type": "SOA"
    },
    ...
    {
      INSERT YOUR ADDITIONS HERE
    }
  ],
  "deletions": [
    {
      "kind": "dns#resourceRecordSet",
      "name": "example.com.",
      "rrdatas": [
        "ns-cloud1.googledomains.com. dns-admin.google.com. 0 21600 3600 1209600 300"
      ],
      "ttl": 21600,
      "type": "SOA"
    },
    ...
    {
      INSERT YOUR DELETIONS HERE
    }
  ]
}

Before you save your changes, verify your syntax to ensure you do not lose your changes if the command fails.

When you are finished editing, save your changes and exit the editor. The command sends your changes.

JavaScript

Load the Cloud DNS API methods and call the gapi.client.dns.managedzones.create() method to create a managed zone and then with the ID that is returned create a record within that zone:

<script type="text/javascript">
var projectName = 'YOUR_PROJECT_NAME';
var zoneName = 'YOUR_ZONE_NAME';

// Hard coded for the example:
var recordToCreate = {
  'additions' : [{
    'name' : 'example.com.',
    'type' : 'A',
    'ttl'  : 21600,
    'rrdatas' : ['1.2.3.4 2.3.4.5']
  }]
  // Can also specify a list of deletions
  // , 'deletions' : [{ // Same format as additions }]
}

gapi.client.load('dns', 'v1beta1', function() {
  createZone();
}

function createZone() {
  // Configure a request to the Managedzones.create API method and pass the
  // required and optional parameters
  var request = gapi.client.dns.managedzones.create({
    'project' : projectName,
    'resource' : {
      'name'        : zoneName,
      'dnsName'     : 'example.com.',
      'description' : 'A managed zone for example.com'
    }
  });

  // Execute the request and provide a callback function
  request.execute(function(resp) {
    // Insert the response into a div for viewing.
    document.getElementById('response-payload').innerText =
      'managedZones.create response:<pre>' +
      JSON.stringify(resp) + '</pre>';

      // Get managed zone ID:
      var zoneId = resp.id;
      createRecord(zoneId);
  });
}

/**
 * Create a basic record in the given zone
 *
 * @param zoneId The identifier for the zone that was returned during
 *               the previous step in this example.
 */
function createRecord(zoneId) {

  var request = gapi.client.dns.changes.create({
    'project' : projectName,
    'managedZone' : zoneName,
    'body' : recordToCreate
  });

  request.execute(function(resp){
    document.getElementById('response2-payload').innerText =
      'changes.create response:<pre>' +
      JSON.stringify(resp) + '</pre>';
  });
}

</script>
<div id="response-payload"></div>
<div id="response2-payload"></div>

Troubleshooting

verifyManagedZoneDnsNameOwnership

Please verify ownership of the 'your_domain' domain (or a parent) at http://www.google.com/webmasters/verification/ and try again.

When you receive this error, you must verify domain ownership.

accessNotConfigured

Access not configured

To resolve this error, you must enable the Cloud DNS API for your project.

inactiveBillingState

Project project_name cannot accept requests while in an inactive billing state. Billing state may take several minutes to update.

Enabling billing for your project in the Settings section of your project in the Developers Console.

Next steps

The simple examples in this document demonstrate how to get started quickly with the Cloud DNS API by using either the command-line tool or the REST API. Additional client libraries are available to help you create an app that uses the REST API directly.

To learn more about Cloud DNS, see the following topics:

Except as otherwise noted, the code samples of this page is licensed under the Apache 2.0 License.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution 3.0 Unported License


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --