In the ever-evolving landscape of cloud services, the ability to customize and tailor configurations is more than just a luxury â itâs a necessity. For developers and businesses keen on leveraging the AWS ecosystem, the Cloud Development Kit (CDK) has emerged as an invaluable tool. Not only does it simplify infrastructure management, but it also provides a programmatic way to deploy resources on AWS. One such resource that often requires a touch of personalization is the HTTP gateway. Having a custom domain for this gateway not only enhances your brandâs visibility but also instills trust in your users.
In this article, weâll embark on a step-by-step journey, unraveling the mysteries of setting up a custom domain name for your HTTP gateway using the AWS CDK. Whether youâre a seasoned AWS veteran or a newcomer eager to dive deep, this guide promises to offer insights and actionable steps to elevate your cloud game.
So, grab your favorite cup of coffee, put on your developer hat, and letâs dive right in!
Typical AWS infrastructure
Letâs examine the basic infrastructure that is commonly used these days. While working on TARGPatrol, we adopted a similar approach as it allows for the creation of flexible and powerful solutions.
AWS Inftrastructure
- AWS VPC allows you to group all your infrastructure into an isolated virtual network. This virtual network mirrors a conventional network youâd manage in your own data center, while leveraging the scalable infrastructure of AWS.
- AWS API Gateway is a fully managed service, streamlines the process for developers to craft, release, sustain, oversee, and safeguard APIs regardless of their size. Serving as the âentry pointâ for apps to retrieve data or tap into business logic from backend services, this tool allows for the creation of both RESTful and WebSocket APIs, facilitating instantaneous bidirectional communication. Moreover, API Gateway is compatible with containerized, serverless, and traditional web-based workloads. Two types of gateways exist. Create RESTful APIs tailored for serverless tasks and HTTP backends using HTTP APIs. For APIs that solely need proxy functionality, HTTP APIs are the top pick. However, if you need both proxy functionality and comprehensive API management within one package, API Gateway provides REST APIs as an option.
- AWS Route 53 is a robust and scalable Domain Name System (DNS) web service. It directs user requests to web applications hosted either on AWS or on-premises setups. Additionally, AWS Route 53 enables the registration and linkage of custom domains to your AWS API Gateway.
- AWS Lambda is a serverless compute service, driven by events, which facilitates the execution of code for almost any application or backend process without the need to handle server management. Lambda can be activated by more than 200 AWS services and SaaS applications, ensuring you only pay for your actual usage.
Using AWS Lambda isnât obligatory. Alternatives include services like EC2, ECS, or EKS.
In the sprawling universe of cloud services, infrastructure as code (IAC) has carved out a significant niche. The AWS Cloud Development Kit (CDK), Amazonâs proprietary foray into this space, represents a paradigm shift in how we think about cloud resource provisioning.
What is AWS CDK?
The AWS CDK is an open-source software development framework to define cloud infrastructure in code and provision it through AWS CloudFormation. Unlike traditional CloudFormation where developers write cumbersome YAML or JSON templates, with CDK, they can leverage the power of modern programming languages such as TypeScript, Python, Java, or C#. This allows for more abstraction, reusability, and a more intuitive development experience.
Key Benefits of AWS CDK:
- Intuitive Infrastructure Design: Developers can use their preferred programming languages, making the process more fluid and reducing the learning curve.
- Reusable Components: CDK introduces the concept of constructs â pre-built pieces of cloud infrastructure. This means less repetitive code and more focus on the unique aspects of a given project.
- Stronger Validation: By leveraging the capabilities of mainstream programming languages, CDK provides early feedback through IDEs, making it easier to catch issues before they reach the deployment stage.
- Seamless Integration with AWS Services: Given its native nature, CDK smoothly integrates with the vast AWS ecosystem, making it a breeze to incorporate various AWS services into your infrastructure.
- Built-in Best Practices: AWS CDK has built-in defaults that adhere to AWS best practices, ensuring optimal configurations and security.
- Flexibility: While CDK offers high-level components for quick setup, developers also have the option to dive deep and customize low-level resources if needed.
The entire TARGParol infrastructure was constructed using AWS CDK/TypeScript, and our team has experienced no problems with it.
Preparation
Youâll need to begin by selecting and registering a custom domain. While this can be done through various providers such as GoDaddy, Cloudflare, etc., and subsequently transferring DNS control to AWS, Iâll demonstrate how to accomplish this directly within AWS.
Navigate to Route 53 Service and click to Domains -> Registered domains.
AWS Domain registration
Next, youâll need to choose an appropriate name for your custom domain and purchase it if itâs available. It will take a few minutes for the process to complete, after which you can view your domain in the Hosted Zones.
AWS Hosted zones
Order certificates
Once youâve completed the domain registration, the next step is to obtain a certificate to secure your traffic using the HTTPS protocol. While AWS CDK can facilitate the certificate ordering, itâs a relatively static process that can be handled separately. Head to the AWS Certificate Manager and select âRequest.â Opt for a public certificate. When prompted for a domain name, enter the one you purchased earlier. If youâre looking to secure a subdomain, you can specify additional names, such as sub.example.com. Alternatively, you can utilize wildcards like *.example.com to safeguard all subdomains under the primary domain. Opt for DNS Validation to confirm the link between your certificate and domain. You can rely on AWS during this process: when prompted to add validation DNS records, simply click âOk.â
It may take a few minutes to generate the certificate. Once completed, you can view your certificate in the AWS Certificate Manager dashboard.
AWS Certificate manager
To integrate it into your AWS CDK code, youâll need its Arn. Simply click on the certificate and copy the Arn value.
AWS Certificate Arn
Letâs put our hands on the code.
I hope youâre familiar with the AWS CDK. If not, thereâs a fantastic article you can follow to take your first steps (https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html). In short, you just need to install the AWS CDK CLI and create a new project.
The very first thing you need to define in an AWS CDK stack is your VPC. You can create it with just a few lines of code:
const vpc = new Vpc(this, "VPC", {
vpcName: "VpcName",
ipAddresses: IpAddresses.cidr("10.0.0.0/16"),
subnetConfiguration: [
{ name: "Public", cidrMask: 24, subnetType: SubnetType.PUBLIC },
{
name: "Private",
cidrMask: 24,
subnetType: SubnetType.PRIVATE_WITH_EGRESS,
},
{
name: "Isolated",
cidrMask: 24,
subnetType: SubnetType.PRIVATE_ISOLATED,
},
],
});
Here, weâre establishing a new VPC with three subnets. While this isnât directly related to the topic of custom domains, itâs prudent to prepare for any additional resources you might want to introduce in the future. Note that natGateways arenât crucial if weâre using Lambda as the backend. However, if you plan to deploy EC2 or ECS/EKS instances and need to provide them with Internet access, at least one natGateway is essential.
We require several constants from the resources that were manually created:
const domainName = "targpatrol.xyz";
const hostedZoneId = "Z01395012LPLFQI32IEEA";
const certArn =
"arn:aws:acm:us-east-1:988135634994:certificate/496295d2-317a-4622-85a2-4cc5b6ea6519";
const lambdaRepository = "111122223333.dkr.ecr.us-east-1.amazonaws.com";
If youâre uncertain about locating these values, refer to the screenshot provided earlier.
Now you can import the âHostedZoneâ and establish a new domain. Additionally, we need to set up a DNS record that will direct traffic to the API gateway, which weâll set up in a later step.
const hostedZoned = HostedZone.fromHostedZoneAttributes(this, "HostedZone", {
zoneName: props.domainName,
hostedZoneId: props.hostedZoneId,
});
const domainName = new DomainName(this, "DomainName", {
domainName: props.domainName,
certificate: Certificate.fromCertificateArn(
this,
"Certificate",
props.certArn
),
securityPolicy: SecurityPolicy.TLS_1_2,
});
new ARecord(this, "DnsRecord", {
zone: hostedZoned,
recordName: props.domainName,
target: RecordTarget.fromAlias(
new ApiGatewayv2DomainProperties(
domainName.regionalDomainName,
domainName.regionalHostedZoneId
)
),
});
With the domain and DNS set up, we can now proceed to the HTTP API Gateway. But first, letâs craft a simple Lambda function to manage our requests. While there are several methods to create a Lambda, Iâll utilize the AWS sample Lambda function for this demonstration.
const lambda = new DockerImageFunction(this, "LambdaFunction", {
functionName: "FunctionName",
code: DockerImageCode.fromEcr(
Repository.fromRepositoryName(
this,
"LambdaRepository",
props.lambdaRepository
),
{ tagOrDigest: "latest" }
),
});
The final action involves setting up the HTTP API Gateway and directing the domain towards it. As touched upon earlier, AWS offers various API Gateway types, including HTTP API and REST API. To put it briefly, while the REST API offers more features, it comes at a price tag three times higher. The HTTP API can be likened to a basic nginx proxy service, facilitating control over your HTTP(S) traffic. For this tutorial, Iâll be focusing on the HTTP API Gateway.
const gateway = new HttpApi(this, "HttpApiGateway", {
disableExecuteApiEndpoint: true,
defaultDomainMapping: {
domainName,
},
});
gateway.addRoutes({
path: "/api/v1/test",
methods: [HttpMethod.POST],
integration: new HttpLambdaIntegration("LambdaIntegration", lambda),
});
In Conclusion: The Power of AWS CDK
Navigating the AWS ecosystem can initially seem daunting, but tools like the AWS CDK are specifically designed to simplify and streamline the process. By allowing developers to use familiar programming languages and providing an intuitive framework to define and deploy cloud infrastructure, AWS CDK genuinely revolutionizes the cloud development experience.
The examples provided in this article merely scratch the surface of whatâs possible with AWS CDK. As you delve deeper and experiment more, youâll uncover a myriad of opportunities to optimize, automate, and innovate.
Embracing the AWS CDK means stepping into the future of cloud deployment, where flexibility meets efficiency. As always, continuous learning and adaptation are the keys to harnessing the full potential of any tool, AWS CDK being no exception.
Thank you for joining us on this exploratory journey into the world of AWS CDK. We encourage you to dive in, experiment, and share your experiences with the broader developer community. Happy coding!
P.S. All the code can be accessed in the repository linked here.