Skip to content

feat(awstf): add custom domains for terraform APIs #785

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions cloud/aws/deploytf/.nitric/modules/api/domain.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
locals {
domain_list = tolist(var.domain_names)
base_names = { for domain in local.domain_list : domain => split(".", domain)[0] }
}

resource "aws_acm_certificate" "website-cert" {
for_each = var.domain_names

domain_name = each.value
validation_method = "DNS"
}

locals {
domain_validation_options = {
for domain in var.domain_names :
domain => one(aws_acm_certificate.website-cert[domain].domain_validation_options)
}
}

resource "aws_route53_record" "cert-validation-dns" {
for_each = var.domain_names

zone_id = var.zone_ids[each.value]
ttl = "600"
name = local.domain_validation_options[each.value].resource_record_name
type = local.domain_validation_options[each.value].resource_record_type
records = [local.domain_validation_options[each.value].resource_record_value]

depends_on = [aws_acm_certificate.website-cert]
}

resource "aws_acm_certificate_validation" "cert-validation" {
for_each = var.domain_names

certificate_arn = aws_acm_certificate.website-cert[each.value].arn
validation_record_fqdns = [aws_route53_record.cert-validation-dns[each.value].fqdn]
}

resource "aws_apigatewayv2_domain_name" "api_domain_name" {
for_each = var.domain_names

domain_name = each.value

domain_name_configuration {
certificate_arn = aws_acm_certificate_validation.cert-validation[each.value].certificate_arn
endpoint_type = "REGIONAL"
security_policy = "TLS_1_2"
}
}

resource "aws_apigatewayv2_api_mapping" "api_mapping" {
for_each = var.domain_names

api_id = aws_apigatewayv2_api.api_gateway.id
stage = aws_apigatewayv2_stage.stage.id
domain_name = aws_apigatewayv2_domain_name.api_domain_name[each.value].domain_name
}

resource "aws_route53_record" "api-dnsrecord" {
for_each = var.domain_names

zone_id = var.zone_ids[each.value]
// The name is prepended onto the target domain name alias. If theres a subdomain will use it, otherwise just use the target domain name
name = length(split(".", each.value)) > 2 ? local.base_names[each.value] : ""
type = "A"

alias {
name = aws_apigatewayv2_domain_name.api_domain_name[each.value].domain_name_configuration[0].target_domain_name
zone_id = aws_apigatewayv2_domain_name.api_domain_name[each.value].domain_name_configuration[0].hosted_zone_id
evaluate_target_health = false
}
}
17 changes: 0 additions & 17 deletions cloud/aws/deploytf/.nitric/modules/api/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,4 @@ resource "aws_lambda_permission" "apigw_lambda" {
function_name = each.value
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.api_gateway.execution_arn}/*/*/*"
}

# look up existing certificate for domains
data "aws_acm_certificate" "cert" {
for_each = var.domains
domain = each.value
}

# deploy custom domain names
resource "aws_apigatewayv2_domain_name" "domain" {
for_each = var.domains
domain_name = each.value
domain_name_configuration {
certificate_arn = data.aws_acm_certificate.cert[each.key].arn
endpoint_type = "REGIONAL"
security_policy = "TLS_1_2"
}
}
11 changes: 8 additions & 3 deletions cloud/aws/deploytf/.nitric/modules/api/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ variable "target_lambda_functions" {
type = map(string)
}

variable "domains" {
description = "The domains to associate with the API Gateway"
type = set(string)
variable "domain_names" {
description = "A set of each domain name."
type = set(string)
}

variable "zone_ids" {
description = "The id of the hosted zone mapped to the domain name."
type = map(string)
}
12 changes: 9 additions & 3 deletions cloud/aws/deploytf/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ func (n *NitricAwsTerraformProvider) Api(stack cdktf.TerraformStack, name string
return fmt.Errorf("aws provider can only deploy OpenAPI specs")
}

additionalApiConfig := n.AwsConfig.Apis[name]

openapiDoc := &openapi3.T{}
err := openapiDoc.UnmarshalJSON([]byte(config.GetOpenapi()))
if err != nil {
Expand Down Expand Up @@ -172,16 +174,20 @@ func (n *NitricAwsTerraformProvider) Api(stack cdktf.TerraformStack, name string
templateFile := cdktf.Fn_Templatefile(asset.Path(), nameArnPairs)

domains := []string{}
if n.AwsConfig != nil && n.AwsConfig.Apis != nil && n.AwsConfig.Apis[name] != nil {
domains = n.AwsConfig.Apis[name].Domains
zoneIds := make(map[string]*string)

if additionalApiConfig != nil {
domains = additionalApiConfig.Domains
zoneIds = getZoneIds(additionalApiConfig.Domains)
}

n.Apis[name] = api.NewApi(stack, jsii.Sprintf("api_%s", name), &api.ApiConfig{
Name: jsii.String(name),
Spec: cdktf.Token_AsString(templateFile, &cdktf.EncodingOptions{}),
TargetLambdaFunctions: &targetNames,
Domains: jsii.Strings(domains...),
StackId: n.Stack.StackIdOutput(),
DomainNames: jsii.Strings(domains...),
ZoneIds: &zoneIds,
})

return nil
Expand Down
82 changes: 82 additions & 0 deletions cloud/aws/deploytf/domain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2021 Nitric Technologies Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package deploytf

import (
"context"
"strings"

"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/route53"
"github.com/aws/aws-sdk-go/aws"
)

func getZoneIds(domainNames []string) map[string]*string {
ctx := context.TODO()

cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-west-2"))
if err != nil {
return nil
}

client := route53.NewFromConfig(cfg)

zoneMap := make(map[string]*string)

normalizedDomains := make(map[string]string)
for _, d := range domainNames {
d = strings.ToLower(strings.TrimSuffix(d, "."))
normalizedDomains[d] = d + "."
}

paginator := route53.NewListHostedZonesPaginator(client, &route53.ListHostedZonesInput{})
hostedZones := make(map[string]string) // map of zone name -> zone ID

for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil
}

for _, hz := range page.HostedZones {
name := strings.ToLower(strings.TrimSuffix(*hz.Name, "."))
hostedZones[name] = strings.TrimPrefix(*hz.Id, "/hostedzone/")
}
}

// Resolve each domain name
for domain, normalized := range normalizedDomains {
// Check full domain
if id, ok := hostedZones[strings.TrimSuffix(normalized, ".")]; ok {
zoneMap[domain] = aws.String(id)
continue
}

// Try parent/root domain
parts := strings.Split(domain, ".")
if len(parts) > 2 {
root := strings.Join(parts[len(parts)-2:], ".")
if id, ok := hostedZones[root]; ok {
zoneMap[domain] = aws.String(id)
continue
}
}

// No match
zoneMap[domain] = nil
}

return zoneMap
}
37 changes: 30 additions & 7 deletions cloud/aws/deploytf/generated/api/Api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ type Api interface {
DependsOn() *[]*string
// Experimental.
SetDependsOn(val *[]*string)
Domains() *[]*string
SetDomains(val *[]*string)
DomainNames() *[]*string
SetDomainNames(val *[]*string)
EndpointOutput() *string
// Experimental.
ForEach() cdktf.ITerraformIterator
Expand Down Expand Up @@ -56,6 +56,8 @@ type Api interface {
SetTargetLambdaFunctions(val *map[string]*string)
// Experimental.
Version() *string
ZoneIds() *map[string]*string
SetZoneIds(val *map[string]*string)
// Experimental.
AddOverride(path *string, value interface{})
// Experimental.
Expand Down Expand Up @@ -127,11 +129,11 @@ func (j *jsiiProxy_Api) DependsOn() *[]*string {
return returns
}

func (j *jsiiProxy_Api) Domains() *[]*string {
func (j *jsiiProxy_Api) DomainNames() *[]*string {
var returns *[]*string
_jsii_.Get(
j,
"domains",
"domainNames",
&returns,
)
return returns
Expand Down Expand Up @@ -297,6 +299,16 @@ func (j *jsiiProxy_Api) Version() *string {
return returns
}

func (j *jsiiProxy_Api) ZoneIds() *map[string]*string {
var returns *map[string]*string
_jsii_.Get(
j,
"zoneIds",
&returns,
)
return returns
}


func NewApi(scope constructs.Construct, id *string, config *ApiConfig) Api {
_init_.Initialize()
Expand Down Expand Up @@ -333,13 +345,13 @@ func (j *jsiiProxy_Api)SetDependsOn(val *[]*string) {
)
}

func (j *jsiiProxy_Api)SetDomains(val *[]*string) {
if err := j.validateSetDomainsParameters(val); err != nil {
func (j *jsiiProxy_Api)SetDomainNames(val *[]*string) {
if err := j.validateSetDomainNamesParameters(val); err != nil {
panic(err)
}
_jsii_.Set(
j,
"domains",
"domainNames",
val,
)
}
Expand Down Expand Up @@ -396,6 +408,17 @@ func (j *jsiiProxy_Api)SetTargetLambdaFunctions(val *map[string]*string) {
)
}

func (j *jsiiProxy_Api)SetZoneIds(val *map[string]*string) {
if err := j.validateSetZoneIdsParameters(val); err != nil {
panic(err)
}
_jsii_.Set(
j,
"zoneIds",
val,
)
}

// Checks if `x` is a construct.
//
// Use this method instead of `instanceof` to properly detect `Construct`
Expand Down
8 changes: 6 additions & 2 deletions cloud/aws/deploytf/generated/api/ApiConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ type ApiConfig struct {
Providers *[]interface{} `field:"optional" json:"providers" yaml:"providers"`
// Experimental.
SkipAssetCreationFromLocalModules *bool `field:"optional" json:"skipAssetCreationFromLocalModules" yaml:"skipAssetCreationFromLocalModules"`
// The domains to associate with the API Gateway.
Domains *[]*string `field:"required" json:"domains" yaml:"domains"`
// A set of each domain name.
DomainNames *[]*string `field:"required" json:"domainNames" yaml:"domainNames"`
// The name of the API Gateway.
Name *string `field:"required" json:"name" yaml:"name"`
// Open API spec.
Expand All @@ -23,5 +23,9 @@ type ApiConfig struct {
StackId *string `field:"required" json:"stackId" yaml:"stackId"`
// The names of the target lambda functions The property type contains a map, they have special handling, please see {@link cdk.tf /module-map-inputs the docs}.
TargetLambdaFunctions *map[string]*string `field:"required" json:"targetLambdaFunctions" yaml:"targetLambdaFunctions"`
// The id of the hosted zone mapped to the domain name.
//
// The property type contains a map, they have special handling, please see {@link cdk.tf /module-map-inputs the docs}
ZoneIds *map[string]*string `field:"required" json:"zoneIds" yaml:"zoneIds"`
}

10 changes: 9 additions & 1 deletion cloud/aws/deploytf/generated/api/Api__checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func validateApi_IsTerraformElementParameters(x interface{}) error {
return nil
}

func (j *jsiiProxy_Api) validateSetDomainsParameters(val *[]*string) error {
func (j *jsiiProxy_Api) validateSetDomainNamesParameters(val *[]*string) error {
if val == nil {
return fmt.Errorf("parameter val is required, but nil was provided")
}
Expand Down Expand Up @@ -130,6 +130,14 @@ func (j *jsiiProxy_Api) validateSetTargetLambdaFunctionsParameters(val *map[stri
return nil
}

func (j *jsiiProxy_Api) validateSetZoneIdsParameters(val *map[string]*string) error {
if val == nil {
return fmt.Errorf("parameter val is required, but nil was provided")
}

return nil
}

func validateNewApiParameters(scope constructs.Construct, id *string, config *ApiConfig) error {
if scope == nil {
return fmt.Errorf("parameter scope is required, but nil was provided")
Expand Down
6 changes: 5 additions & 1 deletion cloud/aws/deploytf/generated/api/Api__no_checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func validateApi_IsTerraformElementParameters(x interface{}) error {
return nil
}

func (j *jsiiProxy_Api) validateSetDomainsParameters(val *[]*string) error {
func (j *jsiiProxy_Api) validateSetDomainNamesParameters(val *[]*string) error {
return nil
}

Expand All @@ -52,6 +52,10 @@ func (j *jsiiProxy_Api) validateSetTargetLambdaFunctionsParameters(val *map[stri
return nil
}

func (j *jsiiProxy_Api) validateSetZoneIdsParameters(val *map[string]*string) error {
return nil
}

func validateNewApiParameters(scope constructs.Construct, id *string, config *ApiConfig) error {
return nil
}
Expand Down
Binary file modified cloud/aws/deploytf/generated/api/jsii/api-0.0.0.tgz
Binary file not shown.
3 changes: 2 additions & 1 deletion cloud/aws/deploytf/generated/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func init() {
_jsii_.MemberProperty{JsiiProperty: "cdktfStack", GoGetter: "CdktfStack"},
_jsii_.MemberProperty{JsiiProperty: "constructNodeMetadata", GoGetter: "ConstructNodeMetadata"},
_jsii_.MemberProperty{JsiiProperty: "dependsOn", GoGetter: "DependsOn"},
_jsii_.MemberProperty{JsiiProperty: "domains", GoGetter: "Domains"},
_jsii_.MemberProperty{JsiiProperty: "domainNames", GoGetter: "DomainNames"},
_jsii_.MemberProperty{JsiiProperty: "endpointOutput", GoGetter: "EndpointOutput"},
_jsii_.MemberProperty{JsiiProperty: "forEach", GoGetter: "ForEach"},
_jsii_.MemberProperty{JsiiProperty: "fqn", GoGetter: "Fqn"},
Expand All @@ -45,6 +45,7 @@ func init() {
_jsii_.MemberMethod{JsiiMethod: "toString", GoMethod: "ToString"},
_jsii_.MemberMethod{JsiiMethod: "toTerraform", GoMethod: "ToTerraform"},
_jsii_.MemberProperty{JsiiProperty: "version", GoGetter: "Version"},
_jsii_.MemberProperty{JsiiProperty: "zoneIds", GoGetter: "ZoneIds"},
},
func() interface{} {
j := jsiiProxy_Api{}
Expand Down
Binary file modified cloud/aws/deploytf/generated/bucket/jsii/bucket-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/cdn/jsii/cdn-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/http_proxy/jsii/http_proxy-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/keyvalue/jsii/keyvalue-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/parameter/jsii/parameter-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/policy/jsii/policy-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/queue/jsii/queue-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/rds/jsii/rds-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/schedule/jsii/schedule-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/secret/jsii/secret-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/service/jsii/service-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/sql/jsii/sql-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/stack/jsii/stack-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/topic/jsii/topic-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/vpc/jsii/vpc-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/website/jsii/website-0.0.0.tgz
Binary file not shown.
Binary file modified cloud/aws/deploytf/generated/websocket/jsii/websocket-0.0.0.tgz
Binary file not shown.
Loading
Loading