Skip to content

Instantly share code, notes, and snippets.

@SlootSantos
Last active May 22, 2022 18:58
Show Gist options
  • Save SlootSantos/2e081891eddeb1e8600604ad21a51110 to your computer and use it in GitHub Desktop.
Save SlootSantos/2e081891eddeb1e8600604ad21a51110 to your computer and use it in GitHub Desktop.
import { Construct } from "constructs";
import {
Role,
Effect,
PolicyDocument,
PolicyStatement,
AccountPrincipal,
CompositePrincipal,
} from "aws-cdk-lib/aws-iam";
import { IHostedZone } from "aws-cdk-lib/aws-route53";
import { accounts } from "../../constants/accounts";
import { NS_CREATION_ROLE_NAME } from "../../constants/roles";
export const buildnsRecordsCreationRole = (
scope: Construct,
hostedZone: IHostedZone
) => {
new Role(scope, "ns-record-creation-role", {
roleName: NS_CREATION_ROLE_NAME,
inlinePolicies: {
createNSRecord: buildRolePolicy(hostedZone),
},
// allowing access only from those accounts that we are expecting to write records to the root hosted zone
assumedBy: new CompositePrincipal(
new AccountPrincipal(accounts.dev),
new AccountPrincipal(accounts.prod)
),
});
};
const buildRolePolicy = (hostedZone: IHostedZone) => {
// required to list the hosted zones in the application stack via the custom resource
const allowHostedZones = new PolicyStatement({
resources: ["*"],
effect: Effect.ALLOW,
actions: ["route53:ListHostedZonesByName"],
});
// required to write the NS record via the custom resource in the application stacks
const allowChangingHostedZone = new PolicyStatement({
effect: Effect.ALLOW,
actions: ["route53:ChangeResourceRecordSets", "route53:GetHostedZone"],
resources: [`arn:aws:route53:::hostedzone/${hostedZone.hostedZoneId}`],
});
return new PolicyDocument({
statements: [allowHostedZones, allowChangingHostedZone],
});
};
import { Construct } from "constructs";
import { Stack, StackProps } from "aws-cdk-lib";
import { buildnsRecordsCreationRole } from "../services/IAM/nsRecordsCreationRole";
import { buildRootDomainHostedZone } from "../services/Route53/rootDomainHostedZone";
export class RootDomainStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const hostedZone = buildRootDomainHostedZone(this);
buildnsRecordsCreationRole(this, hostedZone);
}
}
import { Construct } from "constructs";
import { HostedZone } from "aws-cdk-lib/aws-route53";
import { domains } from "../../constants/domains";
export const buildRootDomainHostedZone = (scope: Construct) => {
// creating the hosted zone from lookup bc it does already exist in that account
// alternatively you could create it from scratch, but would need to make sure then that
// the domain is resolved properly
const zone = HostedZone.fromLookup(scope, "RootDomainHostedZone", {
domainName: domains.root,
});
return zone;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment