@aws-cdk/core#Fn TypeScript Examples
The following examples show how to use
@aws-cdk/core#Fn.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fargateServiceResources.ts From aws-boilerplate with MIT License | 6 votes |
private retrieveMainVpc() {
const stack = Stack.of(this);
return Vpc.fromVpcAttributes(this, "EC2MainVpc", {
vpcId: Fn.importValue(MainVpc.getVpcArnOutputExportName(this.envSettings)),
publicSubnetIds: [
Fn.importValue(MainVpc.getPublicSubnetOneIdOutputExportName(this.envSettings)),
Fn.importValue(MainVpc.getPublicSubnetTwoIdOutputExportName(this.envSettings)),
],
availabilityZones: [
stack.availabilityZones[0],
stack.availabilityZones[1],
],
});
}
Example #2
Source File: fargateServiceResources.ts From aws-boilerplate with MIT License | 6 votes |
private retrievePublicLoadBalancer(vpc: IVpc) {
const securityGroupId = Fn.importValue(
MainECSCluster.getPublicLoadBalancerSecurityGroupIdOutputExportName(this.envSettings));
const loadBalancerArn = Fn.importValue(MainECSCluster.getLoadBalancerArnOutputExportName(this.envSettings));
const loadBalancerDnsName = Fn.importValue(MainECSCluster.getLoadBalancerDnsNameOutput(this.envSettings));
const loadBalancerCanonicalHostedZoneId = Fn.importValue(
MainECSCluster.getLoadBalancerCanonicalHostedZoneIdOutputExportName(this.envSettings));
return ApplicationLoadBalancer.fromApplicationLoadBalancerAttributes(this,
"MainPublicLoadBalancer", {
vpc,
loadBalancerArn,
securityGroupId,
loadBalancerDnsName,
loadBalancerCanonicalHostedZoneId
});
}
Example #3
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
constructor(scope: core.App, id: string, props: WebAppStackProps) {
super(scope, id, props);
const {envSettings} = props;
const domainZone = PublicHostedZone.fromHostedZoneAttributes(this, "DomainZone", {
hostedZoneId: envSettings.hostedZone.id,
zoneName: envSettings.hostedZone.name,
});
const filesPath = `${props.envSettings.projectRootDir}/services/webapp/build`;
if (fs.existsSync(filesPath)) {
this.webAppCloudFrontDistribution = new WebAppCloudFrontDistribution(this, "WebApp", {
sources: [Source.asset(filesPath)],
domainZone,
domainName: props.envSettings.domains.webApp,
apiDomainName: props.envSettings.domains.api,
certificateArn: Fn.importValue(
MainCertificates.geCloudFrontCertificateArnOutputExportName(props.envSettings)),
authLambdaSSMParameterName: UsEastResourcesStack.getAuthLambdaVersionArnSSMParameterName(props.envSettings),
basicAuth: props.envSettings.appBasicAuth,
});
}
}
Example #4
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
private retrieveMainVpc(props: EnvDbStackProps) {
const stack = Stack.of(this);
return Vpc.fromVpcAttributes(this, "EC2MainVpc", {
vpcId: Fn.importValue(MainVpc.getVpcArnOutputExportName(props.envSettings)),
publicSubnetIds: [
Fn.importValue(MainVpc.getPublicSubnetOneIdOutputExportName(props.envSettings)),
Fn.importValue(MainVpc.getPublicSubnetTwoIdOutputExportName(props.envSettings)),
],
availabilityZones: [
stack.availabilityZones[0],
stack.availabilityZones[1],
],
});
}
Example #5
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
protected createTaskRole(props: SshBastionStackProps): Role {
const stack = Stack.of(this);
const chamberServiceName = this.getChamberServiceName(props.envSettings);
const taskRole = new Role(this, "MigrationsTaskRole", {
assumedBy: new ServicePrincipal('ecs-tasks'),
});
taskRole.addToPolicy(new PolicyStatement({
actions: ["sqs:*", "cloudformation:DescribeStacks", "events:*"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: [
"kms:Get*",
"kms:Describe*",
"kms:List*",
"kms:Decrypt",
],
resources: [
Fn.importValue(MainKmsKey.getMainKmsOutputExportName(props.envSettings)),
],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:DescribeParameters"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:GetParameters*"],
resources: [
`arn:aws:ssm:${stack.region}:${stack.account}:parameter/${chamberServiceName}/*`,
],
}));
return taskRole;
}
Example #6
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
protected createTaskRole(props: MigrationsStackProps): Role {
const stack = Stack.of(this);
const chamberServiceName = this.getChamberServiceName(props.envSettings);
const taskRole = new Role(this, "AdminPanelTaskRole", {
assumedBy: new ServicePrincipal('ecs-tasks'),
});
taskRole.addToPolicy(new PolicyStatement({
actions: ["sqs:*", "cloudformation:DescribeStacks", "events:*"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: [
"kms:Get*",
"kms:Describe*",
"kms:List*",
"kms:Decrypt",
],
resources: [
Fn.importValue(MainKmsKey.getMainKmsOutputExportName(props.envSettings)),
],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:DescribeParameters"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:GetParameters*"],
resources: [
`arn:aws:ssm:${stack.region}:${stack.account}:parameter/${chamberServiceName}/*`,
],
}));
return taskRole;
}
Example #7
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
protected createTaskRole(props: MigrationsStackProps): Role {
const stack = Stack.of(this);
const chamberServiceName = this.getChamberServiceName(props.envSettings);
const taskRole = new Role(this, "MigrationsTaskRole", {
assumedBy: new ServicePrincipal('ecs-tasks'),
});
taskRole.addToPolicy(new PolicyStatement({
actions: [
"kms:Get*",
"kms:Describe*",
"kms:List*",
"kms:Decrypt",
],
resources: [
Fn.importValue(MainKmsKey.getMainKmsOutputExportName(props.envSettings)),
],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:DescribeParameters"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:GetParameters*"],
resources: [
`arn:aws:ssm:${stack.region}:${stack.account}:parameter/${chamberServiceName}/*`,
],
}));
return taskRole;
}
Example #8
Source File: stack.ts From aws-boilerplate with MIT License | 6 votes |
protected createTaskRole(props: MigrationsStackProps): Role {
const stack = Stack.of(this);
const chamberServiceName = this.getChamberServiceName(props.envSettings);
const taskRole = new Role(this, "ApiTaskRole", {
assumedBy: new ServicePrincipal('ecs-tasks'),
});
taskRole.addToPolicy(new PolicyStatement({
actions: ["sqs:*", "cloudformation:DescribeStacks", "events:*"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: [
"kms:Get*",
"kms:Describe*",
"kms:List*",
"kms:Decrypt",
],
resources: [
Fn.importValue(MainKmsKey.getMainKmsOutputExportName(props.envSettings)),
],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:DescribeParameters"],
resources: ["*"],
}));
taskRole.addToPolicy(new PolicyStatement({
actions: ["ssm:GetParameters*"],
resources: [
`arn:aws:ssm:${stack.region}:${stack.account}:parameter/${chamberServiceName}/*`,
],
}));
return taskRole;
}
Example #9
Source File: fargateServiceResources.ts From aws-boilerplate with MIT License | 5 votes |
private retrieveFargateContainerSecurityGroup() {
return SecurityGroup.fromSecurityGroupId(this, "FargateContainerSecurityGroup",
Fn.importValue(MainECSCluster.getFargateContainerSecurityGroupIdOutputExportName(this.envSettings)));
}
Example #10
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
constructor(scope: core.App, id: string, props: SshBastionStackProps) {
super(scope, id, props);
const {envSettings} = props;
if (!props.envSettings.sshBastion.sshPublicKey) {
return;
}
const resources = new FargateServiceResources(this, "Resources", props);
const securityGroup = new SecurityGroup(this, "SecurityGroup", {
vpc: resources.mainVpc,
allowAllOutbound: true,
});
securityGroup.addIngressRule(Peer.anyIpv4(), Port.tcp(22));
securityGroup.addIngressRule(securityGroup, Port.allTcp());
const containerName = 'sshBastion';
const dbSecretArn = Fn.importValue(MainDatabase.getDatabaseSecretArnOutputExportName(envSettings));
const taskRole = this.createTaskRole(props);
const taskDefinition = new FargateTaskDefinition(this, "TaskDefinition", {
taskRole,
cpu: 256,
memoryLimitMiB: 512,
});
const container = taskDefinition.addContainer(containerName, {
image: ContainerImage.fromEcrRepository(resources.backendRepository, 'ssh-bastion'),
logging: this.createAWSLogDriver(this.node.id),
environment: {
"CHAMBER_SERVICE_NAME": this.getChamberServiceName(envSettings),
"CHAMBER_KMS_KEY_ALIAS": MainKmsKey.getKeyAlias(envSettings),
"SSH_PUBLIC_KEY": props.envSettings.sshBastion.sshPublicKey,
"WORKERS_EVENT_BUS_NAME": EnvComponentsStack.getWorkersEventBusName(props.envSettings),
},
secrets: {
"DB_CONNECTION": EcsSecret.fromSecretsManager(
Secret.fromSecretArn(this, "DbSecret", dbSecretArn)),
},
command: ["sh", "-c", "/bin/chamber exec $CHAMBER_SERVICE_NAME -- ./scripts/run-ssh-bastion.sh"]
});
container.addPortMappings({
protocol: Protocol.TCP,
hostPort: 22,
containerPort: 22,
});
new CfnOutput(this, "TaskDefinitionArnOutput", {
exportName: SshBastionStack.getTaskDefinitionArn(props.envSettings),
value: taskDefinition.taskDefinitionArn,
});
new CfnOutput(this, "SecurityGroupIdOutput", {
exportName: SshBastionStack.getSecurityGroupId(props.envSettings),
value: securityGroup.securityGroupId,
});
}
Example #11
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
constructor(scope: core.App, id: string, props: MigrationsStackProps) {
super(scope, id, props);
const {envSettings} = props;
const resources = new FargateServiceResources(this, "MigrationsResources", props);
const containerName = 'migrations';
const dbSecretArn = Fn.importValue(MainDatabase.getDatabaseSecretArnOutputExportName(envSettings));
const taskRole = this.createTaskRole(props);
const migrationsTaskDefinition = new FargateTaskDefinition(this, "MigrationsTaskDefinition", {
taskRole,
cpu: 256,
memoryLimitMiB: 512,
});
const containerDef = migrationsTaskDefinition.addContainer(containerName, {
image: ContainerImage.fromEcrRepository(resources.backendRepository, envSettings.version),
logging: this.createAWSLogDriver(this.node.id),
environment: {
"CHAMBER_SERVICE_NAME": this.getChamberServiceName(envSettings),
"CHAMBER_KMS_KEY_ALIAS": MainKmsKey.getKeyAlias(envSettings),
},
secrets: {
"DB_CONNECTION": EcsSecret.fromSecretsManager(
Secret.fromSecretArn(this, "DbSecret", dbSecretArn))
},
});
new StateMachine(this, "MigrationsStateMachine", {
stateMachineName: `${envSettings.projectEnvName}-migrations`,
definition: new Task(this, "MigrationsFargateTask", {
task: new RunEcsFargateTask({
cluster: resources.mainCluster,
taskDefinition: migrationsTaskDefinition,
assignPublicIp: true,
securityGroup: resources.fargateContainerSecurityGroup,
containerOverrides: [
{
containerDefinition: containerDef,
command: ['./scripts/run_migrations.sh'],
}
],
integrationPattern: ServiceIntegrationPattern.SYNC,
}),
}),
timeout: Duration.minutes(5),
});
}
Example #12
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
private createFargateService(resources: FargateServiceResources, props: ApiStackProps) {
const {envSettings} = props;
const taskRole = this.createTaskRole(props);
const dbSecretArn = Fn.importValue(MainDatabase.getDatabaseSecretArnOutputExportName(envSettings));
const domainZone = PublicHostedZone.fromHostedZoneAttributes(this, "DomainZone", {
hostedZoneId: envSettings.hostedZone.id,
zoneName: envSettings.hostedZone.name,
});
const allowedHosts = [
envSettings.domains.api,
envSettings.domains.webApp,
envSettings.domains.www,
].join(',');
const httpsListener = ApplicationListener.fromApplicationListenerAttributes(this, "HttpsListener", {
listenerArn: Fn.importValue(
MainECSCluster.getLoadBalancerHttpsListenerArnOutputExportName(props.envSettings)),
securityGroup: resources.publicLoadBalancerSecurityGroup,
});
return new ApplicationMultipleTargetGroupsFargateService(this, "ApiService", {
securityGroup: resources.fargateContainerSecurityGroup,
serviceName: `${props.envSettings.projectEnvName}-api`,
cluster: resources.mainCluster,
cpu: 512,
memoryLimitMiB: 1024,
desiredCount: 1,
taskRole,
assignPublicIp: true,
taskImageOptions: [
{
containerName: 'backend',
image: ContainerImage.fromEcrRepository(resources.backendRepository, envSettings.version),
environment: {
"CHAMBER_SERVICE_NAME": this.getChamberServiceName(envSettings),
"CHAMBER_KMS_KEY_ALIAS": MainKmsKey.getKeyAlias(envSettings),
"DJANGO_ALLOWED_HOSTS": allowedHosts,
"DJANGO_ALLOWED_CIDR_NETS": "10.0.1.0/16",
"WORKERS_EVENT_BUS_NAME": EnvComponentsStack.getWorkersEventBusName(props.envSettings),
},
secrets: {
"DB_CONNECTION": EcsSecret.fromSecretsManager(
Secret.fromSecretArn(this, "DbSecret", dbSecretArn))
},
}
],
loadBalancers: [
{
domainZone,
domainName: envSettings.domains.api,
loadBalancer: resources.publicLoadBalancer,
listeners: [httpsListener],
},
],
targetGroups: [
{protocol: Protocol.TCP, containerPort: 80, priority: 2, hostHeader: envSettings.domains.api},
{protocol: Protocol.TCP, containerPort: 80, priority: 3, hostHeader: envSettings.domains.webApp},
{protocol: Protocol.TCP, containerPort: 80, priority: 4, hostHeader: envSettings.domains.www},
],
});
}
Example #13
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
constructor(scope: core.App, id: string, props: AdminPanelStackProps) {
super(scope, id, props);
const {envSettings} = props;
const resources = new FargateServiceResources(this, "AdminPanelResources", props);
const taskRole = this.createTaskRole(props);
const dbSecretArn = Fn.importValue(MainDatabase.getDatabaseSecretArnOutputExportName(envSettings));
const domainZone = PublicHostedZone.fromHostedZoneAttributes(this, "DomainZone", {
hostedZoneId: envSettings.hostedZone.id,
zoneName: envSettings.hostedZone.name,
});
const httpsListener = ApplicationListener.fromApplicationListenerAttributes(this, "HttpsListener", {
listenerArn: Fn.importValue(
MainECSCluster.getLoadBalancerHttpsListenerArnOutputExportName(props.envSettings)),
securityGroup: resources.publicLoadBalancerSecurityGroup,
});
this.fargateService = new ApplicationMultipleTargetGroupsFargateService(this, "AdminPanelService", {
securityGroup: resources.fargateContainerSecurityGroup,
serviceName: `${props.envSettings.projectEnvName}-admin-panel`,
cluster: resources.mainCluster,
cpu: 256,
memoryLimitMiB: 512,
desiredCount: 1,
taskRole,
assignPublicIp: true,
taskImageOptions: [
{
containerName: 'backend',
image: ContainerImage.fromEcrRepository(resources.backendRepository, envSettings.version),
environment: {
"CHAMBER_SERVICE_NAME": this.getChamberServiceName(envSettings),
"CHAMBER_KMS_KEY_ALIAS": MainKmsKey.getKeyAlias(envSettings),
"DJANGO_ALLOWED_HOSTS": `${envSettings.domains.adminPanel}`,
"DJANGO_ALLOWED_CIDR_NETS": "10.0.1.0/16",
"WORKERS_EVENT_BUS_NAME": EnvComponentsStack.getWorkersEventBusName(props.envSettings),
},
secrets: {
"DB_CONNECTION": EcsSecret.fromSecretsManager(
Secret.fromSecretArn(this, "DbSecret", dbSecretArn)),
},
}
],
loadBalancers: [
{
domainZone,
domainName: envSettings.domains.adminPanel,
loadBalancer: resources.publicLoadBalancer,
listeners: [httpsListener],
},
],
targetGroups: [
{protocol: Protocol.TCP, containerPort: 80, priority: 1, hostHeader: envSettings.domains.adminPanel}
],
});
}
Example #14
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
private retrieveLambdaSecurityGroup(props: EnvDbStackProps) {
return SecurityGroup.fromSecurityGroupId(this, "LambdaSecurityGroup",
Fn.importValue(MainLambdaConfig.getLambdaSecurityGroupIdOutputExportName(props.envSettings)));
}
Example #15
Source File: stack.ts From aws-boilerplate with MIT License | 5 votes |
private retrieveFargateContainerSecurityGroup(props: EnvDbStackProps) {
return SecurityGroup.fromSecurityGroupId(this, "FargateContainerSecurityGroup",
Fn.importValue(MainECSCluster.getFargateContainerSecurityGroupIdOutputExportName(props.envSettings)));
}
Example #16
Source File: fargateServiceResources.ts From aws-boilerplate with MIT License | 5 votes |
private retrievePublicLoadBalancerSecurityGroup(props: EnvConstructProps): ISecurityGroup {
return SecurityGroup.fromSecurityGroupId(this, "LbSecurityGroup",
Fn.importValue(MainECSCluster.getPublicLoadBalancerSecurityGroupIdOutputExportName(props.envSettings)));
}
Example #17
Source File: stack.ts From keycloak-on-aws with Apache License 2.0 | 4 votes |
constructor(scope: Construct, id: string, props: KeycloakStackProps = {}) {
super(scope, id, props);
const dbMsg = props.auroraServerless ? 'using aurora serverless' : 'rds mysql';
const vpcMsg = props.fromExistingVPC ? 'existing vpc' : 'new vpc';
this.setDescription(`(SO8021) - Deploy keycloak ${dbMsg} with ${vpcMsg}. template version: ${process.env.VERSION}`);
const certificateArnParam = this.makeParam('CertificateArn', {
type: 'String',
description: 'Certificate Arn for Application Load Balancer',
minLength: 5,
});
this.addGroupParam({ 'Application Load Balancer Settings': [certificateArnParam] });
this._keycloakSettings.certificateArn = certificateArnParam.valueAsString;
if (!props.auroraServerless) {
const databaseInstanceType = this.makeParam('DatabaseInstanceType', {
type: 'String',
description: 'Instance type to be used for the core instances',
allowedValues: INSTANCE_TYPES,
default: 'r5.large',
});
this.addGroupParam({ 'Database Instance Settings': [databaseInstanceType] });
this._keycloakSettings.databaseInstanceType = new ec2.InstanceType(databaseInstanceType.valueAsString);
}
if (props.fromExistingVPC) {
const vpcIdParam = this.makeParam('VpcId', {
type: 'AWS::EC2::VPC::Id',
description: 'Your VPC Id',
});
const pubSubnetsParam = this.makeParam('PubSubnets', {
type: 'List<AWS::EC2::Subnet::Id>',
description: 'Public subnets (Choose two)',
});
const privSubnetsParam = this.makeParam('PrivSubnets', {
type: 'List<AWS::EC2::Subnet::Id>',
description: 'Private subnets (Choose two)',
});
const dbSubnetsParam = this.makeParam('DBSubnets', {
type: 'List<AWS::EC2::Subnet::Id>',
description: 'Database subnets (Choose two)',
});
this.addGroupParam({ 'VPC Settings': [vpcIdParam, pubSubnetsParam, privSubnetsParam, dbSubnetsParam] });
const azs = ['a', 'b'];
const vpc = ec2.Vpc.fromVpcAttributes(this, 'VpcAttr', {
vpcId: vpcIdParam.valueAsString,
vpcCidrBlock: Aws.NO_VALUE,
availabilityZones: azs,
publicSubnetIds: azs.map((_, index) => Fn.select(index, pubSubnetsParam.valueAsList)),
privateSubnetIds: azs.map((_, index) => Fn.select(index, privSubnetsParam.valueAsList)),
isolatedSubnetIds: azs.map((_, index) => Fn.select(index, dbSubnetsParam.valueAsList)),
});
Object.assign(this._keycloakSettings, {
vpc,
publicSubnets: { subnets: vpc.publicSubnets },
privateSubnets: { subnets: vpc.privateSubnets },
databaseSubnets: { subnets: vpc.isolatedSubnets },
});
}
const minContainersParam = this.makeParam('MinContainers', {
type: 'Number',
description: 'minimum containers count',
default: 2,
minValue: 2,
});
const maxContainersParam = this.makeParam('MaxContainers', {
type: 'Number',
description: 'maximum containers count',
default: 10,
minValue: 2,
});
const targetCpuUtilizationParam = this.makeParam('AutoScalingTargetCpuUtilization', {
type: 'Number',
description: 'Auto scaling target cpu utilization',
default: 75,
minValue: 0,
});
this.addGroupParam({ 'AutoScaling Settings': [minContainersParam, maxContainersParam, targetCpuUtilizationParam] });
const javaOptsParam = this.makeParam('JavaOpts', {
type: 'String',
description: 'JAVA_OPTS environment variable',
});
this.addGroupParam({ 'Environment variable': [javaOptsParam] });
new KeyCloak(this, 'KeyCloak', {
vpc: this._keycloakSettings.vpc,
publicSubnets: this._keycloakSettings.publicSubnets,
privateSubnets: this._keycloakSettings.privateSubnets,
databaseSubnets: this._keycloakSettings.databaseSubnets,
certificateArn: this._keycloakSettings.certificateArn,
auroraServerless: props.auroraServerless,
databaseInstanceType: this._keycloakSettings.databaseInstanceType,
stickinessCookieDuration: Duration.days(7),
nodeCount: minContainersParam.valueAsNumber,
autoScaleTask: {
min: minContainersParam.valueAsNumber,
max: maxContainersParam.valueAsNumber,
targetCpuUtilization: targetCpuUtilizationParam.valueAsNumber,
},
env: {
JAVA_OPTS: javaOptsParam.valueAsString,
},
});
}