Creating a CNAME record for a sub-domain.
TypeScriptCreating a CNAME record using Pulumi involves defining a resource for a DNS record with a specific provider based on the DNS service you are using. In this example, I'll show you how to create a CNAME record for a sub-domain using AWS Route 53, since AWS is one of the most popular cloud providers and commonly used for DNS management.
Here's an overview of the steps we'll take in our Pulumi program:
- Create a Route 53 hosted zone if you don't already have one. The hosted zone should correspond to the domain for which you are creating the sub-domain CNAME record.
- Within this hosted zone, create the CNAME record by specifying the sub-domain as the record name and the target domain to which it should point.
Let's take a look at the Pulumi program:
import * as aws from "@pulumi/aws"; // Replace these variables with your own domain details. const domainName = "example.com"; // Your domain. const subDomain = "www"; // The subdomain prefix you want to map. const targetDomain = "anotherdomain.com"; // The target domain you want to point to. // Create a Route 53 hosted zone for the domain, if one doesn't already exist. const zone = new aws.route53.Zone("my-zone", { name: domainName, }); // Create a CNAME record in Route 53 for the sub-domain. const cnameRecord = new aws.route53.Record(`${subDomain}-record`, { zoneId: zone.id, name: `${subDomain}.${domainName}`, // The FQDN of your sub-domain. type: "CNAME", ttl: 300, records: [targetDomain], // This is where the CNAME record will point. }); // Export the nameservers for the hosted zone. export const nameServers = zone.nameServers;
In the code above:
- We import the
aws
module from@pulumi/aws
, which includes the classes and functions we need to interact with AWS services. - We define two variables,
domainName
andsubDomain
, which you should replace with your own domain and desired subdomain, respectively. - We create an instance of
aws.route53.Zone
to either fetch or create a hosted zone for your domain within AWS Route 53. - We create an instance of
aws.route53.Record
to create the actual CNAME record within the hosted zone. We specify the record's name, type (which is "CNAME"), TTL (time-to-live), and the target domain.
Finally, we export the value
nameServers
using Pulumi's export syntax. This will print the nameservers for your hosted zone to the console after your Pulumi program has been successfully applied.You'll run this Pulumi program in a TypeScript environment where Pulumi CLI is installed and configured for your AWS account. Once run, Pulumi will provision the resources as coded and give you a live URL that reflects the changes.