Skip to content

Commit cd218b6

Browse files
authored
feat(aws-fargate-secretsmanager): Create new construct (#670)
* created README.md * created new construct * fixed doc typo and created cidr constant
1 parent 1b843bf commit cd218b6

13 files changed

+3564
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
lib/*.js
2+
test/*.js
3+
*.d.ts
4+
coverage
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
lib/*.js
2+
test/*.js
3+
*.js.map
4+
*.d.ts
5+
node_modules
6+
*.generated.ts
7+
dist
8+
.jsii
9+
10+
.LAST_BUILD
11+
.nyc_output
12+
coverage
13+
.nycrc
14+
.LAST_PACKAGE
15+
*.snk
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Exclude typescript source and config
2+
*.ts
3+
tsconfig.json
4+
coverage
5+
.nyc_output
6+
*.tgz
7+
*.snk
8+
*.tsbuildinfo
9+
10+
# Include javascript files and typescript declarations
11+
!*.js
12+
!*.d.ts
13+
14+
# Exclude jsii outdir
15+
dist
16+
17+
# Include .jsii
18+
!.jsii
19+
20+
# Include .jsii
21+
!.jsii
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# aws-fargate-secretsmanager module
2+
<!--BEGIN STABILITY BANNER-->
3+
4+
---
5+
6+
![Stability: Experimental](https://img.shields.io/badge/stability-Experimental-important.svg?style=for-the-badge)
7+
8+
> All classes are under active development and subject to non-backward compatible changes or removal in any
9+
> future version. These are not subject to the [Semantic Versioning](https://semver.org/) model.
10+
> This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.
11+
12+
---
13+
<!--END STABILITY BANNER-->
14+
15+
| **Reference Documentation**:| <span style="font-weight: normal">https://docs.aws.amazon.com/solutions/latest/constructs/</span>|
16+
|:-------------|:-------------|
17+
<div style="height:8px"></div>
18+
19+
| **Language** | **Package** |
20+
|:-------------|-----------------|
21+
|![Python Logo](https://docs.aws.amazon.com/cdk/api/latest/img/python32.png) Python|`aws_solutions_constructs.aws_fargate_secretsmanager`|
22+
|![Typescript Logo](https://docs.aws.amazon.com/cdk/api/latest/img/typescript32.png) Typescript|`@aws-solutions-constructs/aws-fargate-secretsmanager`|
23+
|![Java Logo](https://docs.aws.amazon.com/cdk/api/latest/img/java32.png) Java|`software.amazon.awsconstructs.services.fargatesecretsmanager`|
24+
25+
This AWS Solutions Construct implements an AWS Fargate service that can write/read to an AWS Secrets Manager
26+
27+
Here is a minimal deployable pattern definition:
28+
29+
Typescript
30+
``` typescript
31+
import { Construct } from 'constructs';
32+
import { Stack, StackProps } from 'aws-cdk-lib';
33+
import { FargateToSecretsmanager, FargateToSecretsmanagerProps } from '@aws-solutions-constructs/aws-fargate-secretsmanager';
34+
35+
const constructProps: FargateToSecretsmanagerProps = {
36+
publicApi: true,
37+
ecrRepositoryArn: "arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo",
38+
};
39+
40+
new FargateToSecretsmanager(stack, 'test-construct', constructProps);
41+
```
42+
43+
Python
44+
``` python
45+
from aws_solutions_constructs.aws_fargate_secretsmanager import FargateToSecretsmanager, FargateToSecretsmanagerProps
46+
from aws_cdk import (
47+
Stack
48+
)
49+
from constructs import Construct
50+
51+
FargateToSecretsmanager(self, 'test_construct',
52+
public_api=True,
53+
ecr_repository_arn="arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo")
54+
```
55+
56+
Java
57+
``` java
58+
import software.constructs.Construct;
59+
60+
import software.amazon.awscdk.Stack;
61+
import software.amazon.awscdk.StackProps;
62+
import software.amazon.awsconstructs.services.fargatesecretsmanager.*;
63+
64+
new FargateToSecretsmanager(this, "test-construct", new FargateToSecretsmanagerProps.Builder()
65+
.publicApi(true)
66+
.ecrRepositoryArn("arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo")
67+
.build());
68+
```
69+
70+
## Pattern Construct Props
71+
72+
| **Name** | **Type** | **Description** |
73+
|:-------------|:----------------|-----------------|
74+
| publicApi | `boolean` | Whether the construct is deploying a private or public API. This has implications for the VPC. |
75+
| vpcProps? | [`ec2.VpcProps`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.VpcProps.html) | Optional custom properties for a VPC the construct will create. This VPC will be used by any Private Hosted Zone the construct creates (that's why loadBalancerProps and privateHostedZoneProps can't include a VPC). Providing both this and existingVpc is an error. |
76+
| existingVpc? | [`ec2.IVpc`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IVpc.html) | An existing VPC in which to deploy the construct. Providing both this and vpcProps is an error. If the client provides an existing load balancer and/or existing Private Hosted Zone, those constructs must exist in this VPC. |
77+
| clusterProps? | [`ecs.ClusterProps`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ClusterProps.html) | Optional properties to create a new ECS cluster. To provide an existing cluster, use the cluster attribute of fargateServiceProps. |
78+
| ecrRepositoryArn? | `string` | The arn of an ECR Repository containing the image to use to generate the containers. Either this or the image property of containerDefinitionProps must be provided. format: arn:aws:ecr:*region*:*account number*:repository/*Repository Name* |
79+
| ecrImageVersion? | `string` | The version of the image to use from the repository. Defaults to 'Latest' |
80+
| containerDefinitionProps? | [`ecs.ContainerDefinitionProps \| any`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ContainerDefinitionProps.html) | Optional props to define the container created for the Fargate Service (defaults found in fargate-defaults.ts) |
81+
| fargateTaskDefinitionProps? | [`ecs.FargateTaskDefinitionProps \| any`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateTaskDefinitionProps.html) | Optional props to define the Fargate Task Definition for this construct (defaults found in fargate-defaults.ts) |
82+
| fargateServiceProps? | [`ecs.FargateServiceProps \| any`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateServiceProps.html) | Optional values to override default Fargate Task definition properties (fargate-defaults.ts). The construct will default to launching the service is the most isolated subnets available (precedence: Isolated, Private and Public). Override those and other defaults here. |
83+
| existingFargateServiceObject? | [`ecs.FargateService`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateService.html) | A Fargate Service already instantiated (probably by another Solutions Construct). If this is specified, then no props defining a new service can be provided, including: ecrImageVersion, containerDefinitionProps, fargateTaskDefinitionProps, ecrRepositoryArn, fargateServiceProps, clusterProps |
84+
| existingContainerDefinitionObject? | [`ecs.ContainerDefinition`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ContainerDefinition.html) | A container definition already instantiated as part of a Fargate service. This must be the container in the existingFargateServiceObject |
85+
|secretProps?|[`secretsmanager.SecretProps`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-secretsmanager.SecretProps.html)|Optional user provided props to override the default props for Secrets Manager|
86+
|existingSecretObj?|[`secretsmanager.Secret`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-secretsmanager.Secret.html)|Existing instance of Secrets Manager Secret object, If this is set then the secretProps is ignored|
87+
|grantWriteAccess?|`boolean`|Optional write access to the Secret for the Fargate service (Read-Only by default)
88+
|secretEnvironmentVariableName?|`string`|Optional Name for the Secrets Manager secret environment variable set for the Fargate service.|
89+
90+
## Pattern Properties
91+
92+
| **Name** | **Type** | **Description** |
93+
|:-------------|:----------------|-----------------|
94+
| vpc | [`ec2.IVpc`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.IVpc.html) | The VPC used by the construct (whether created by the construct or provided by the client) |
95+
| service | [`ecs.FargateService`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateService.html) | The AWS Fargate service used by this construct (whether created by this construct or passed to this construct at initialization) |
96+
| container | [`ecs.ContainerDefinition`](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.ContainerDefinition.html) | The container associated with the AWS Fargate service in the service property. |
97+
|secret|[`secretsmanager.Secret`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-secretsmanager.Secret.html)|Returns an instance of `secretsmanager.Secret` created by the construct|
98+
99+
## Default settings
100+
101+
Out of the box implementation of the Construct without any override will set the following defaults:
102+
103+
### AWS Fargate Service
104+
* Sets up an AWS Fargate service
105+
* Uses the existing service if provided
106+
* Creates a new service if none provided.
107+
* Service will run in isolated subnets if available, then private subnets if available and finally public subnets
108+
* Adds environment variables to the container with the ARN and Name of the Secrets Manager secret
109+
* Add permissions to the container IAM role allowing it to publish to the Secrets Manager secret
110+
111+
### Amazon Secrets Manager Secret
112+
* Sets up an Amazon Secrets Manager secret
113+
* Uses an existing secret if one is provided, otherwise creates a new one
114+
* (default) random name
115+
* (default) random value
116+
* Adds an Interface Endpoint to the VPC for Secrets Manager (the service by default runs in Isolated or Private subnets)
117+
* Retain the Secret when deleting the CloudFormation stack
118+
119+
## Architecture
120+
![Architecture Diagram](architecture.png)
121+
122+
***
123+
&copy; Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
/**
2+
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
5+
* with the License. A copy of the License is located at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
10+
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
11+
* and limitations under the License.
12+
*/
13+
14+
import * as ec2 from "@aws-cdk/aws-ec2";
15+
import * as secretsmanager from "@aws-cdk/aws-secretsmanager";
16+
// Note: To ensure CDKv2 compatibility, keep the import statement for Construct separate
17+
import { Construct } from "@aws-cdk/core";
18+
import * as defaults from "@aws-solutions-constructs/core";
19+
import * as ecs from "@aws-cdk/aws-ecs";
20+
21+
export interface FargateToSecretsmanagerProps {
22+
/**
23+
* Whether the construct is deploying a private or public API. This has implications for the VPC deployed
24+
* by this construct.
25+
*
26+
* @default - none
27+
*/
28+
readonly publicApi: boolean;
29+
/**
30+
* Optional custom properties for a VPC the construct will create. This VPC will
31+
* be used by the new Fargate service the construct creates (that's
32+
* why targetGroupProps can't include a VPC). Providing
33+
* both this and existingVpc is an error. A Secrets Manager Interface
34+
* endpoint will be included in this VPC.
35+
*
36+
* @default - none
37+
*/
38+
readonly vpcProps?: ec2.VpcProps;
39+
/**
40+
* An existing VPC in which to deploy the construct. Providing both this and
41+
* vpcProps is an error. If the client provides an existing Fargate service,
42+
* this value must be the VPC where the service is running. A Secrets Manager Interface
43+
* endpoint will be added to this VPC.
44+
*
45+
* @default - none
46+
*/
47+
readonly existingVpc?: ec2.IVpc;
48+
/**
49+
* Optional properties to create a new ECS cluster
50+
*/
51+
readonly clusterProps?: ecs.ClusterProps;
52+
/**
53+
* The arn of an ECR Repository containing the image to use
54+
* to generate the containers
55+
*
56+
* format:
57+
* arn:aws:ecr:[region]:[account number]:repository/[Repository Name]
58+
*/
59+
readonly ecrRepositoryArn?: string;
60+
/**
61+
* The version of the image to use from the repository
62+
*
63+
* @default - 'latest'
64+
*/
65+
readonly ecrImageVersion?: string;
66+
/*
67+
* Optional props to define the container created for the Fargate Service
68+
*
69+
* defaults - fargate-defaults.ts
70+
*/
71+
readonly containerDefinitionProps?: ecs.ContainerDefinitionProps | any;
72+
/*
73+
* Optional props to define the Fargate Task Definition for this construct
74+
*
75+
* defaults - fargate-defaults.ts
76+
*/
77+
readonly fargateTaskDefinitionProps?: ecs.FargateTaskDefinitionProps | any;
78+
/**
79+
* Optional values to override default Fargate Task definition properties
80+
* (fargate-defaults.ts). The construct will default to launching the service
81+
* is the most isolated subnets available (precedence: Isolated, Private and
82+
* Public). Override those and other defaults here.
83+
*
84+
* defaults - fargate-defaults.ts
85+
*/
86+
readonly fargateServiceProps?: ecs.FargateServiceProps | any;
87+
/**
88+
* A Fargate Service already instantiated (probably by another Solutions Construct). If
89+
* this is specified, then no props defining a new service can be provided, including:
90+
* existingImageObject, ecrImageVersion, containerDefintionProps, fargateTaskDefinitionProps,
91+
* ecrRepositoryArn, fargateServiceProps, clusterProps, existingClusterInterface. If this value
92+
* is provided, then existingContainerDefinitionObject must be provided as well.
93+
*
94+
* @default - none
95+
*/
96+
readonly existingFargateServiceObject?: ecs.FargateService;
97+
/*
98+
* A container definition already instantiated as part of a Fargate service. This must
99+
* be the container in the existingFargateServiceObject.
100+
*
101+
* @default - None
102+
*/
103+
readonly existingContainerDefinitionObject?: ecs.ContainerDefinition;
104+
/**
105+
* Existing instance of Secret object, providing both this and secretProps will cause an error.
106+
*
107+
* @default - Default props are used
108+
*/
109+
readonly existingSecretObj?: secretsmanager.Secret;
110+
/**
111+
* Optional user-provided props to override the default props for the Secret.
112+
*
113+
* @default - Default props are used
114+
*/
115+
readonly secretProps?: secretsmanager.SecretProps;
116+
117+
/**
118+
* Optional Access granted to the Fargate service for the secret. 'Read' or 'ReadWrite
119+
*
120+
* @default - 'Read'
121+
*/
122+
readonly grantWriteAccess?: string
123+
/**
124+
* Optional Name for container environment variable containing the ARN of the secret.
125+
*
126+
* @default - SECRET_ARN
127+
*/
128+
readonly secretEnvironmentVariableName?: string;
129+
}
130+
131+
export class FargateToSecretsmanager extends Construct {
132+
public readonly vpc: ec2.IVpc;
133+
public readonly service: ecs.FargateService;
134+
public readonly container: ecs.ContainerDefinition;
135+
public readonly secret: secretsmanager.Secret;
136+
137+
constructor(scope: Construct, id: string, props: FargateToSecretsmanagerProps) {
138+
super(scope, id);
139+
defaults.CheckProps(props);
140+
defaults.CheckFargateProps(props);
141+
142+
// Other permissions for constructs are accepted as arrays, turning grantWriteAccess into
143+
// an array to use the same validation function.
144+
if (props.grantWriteAccess) {
145+
const allowedPermissions = ['READ', 'READWRITE'];
146+
defaults.CheckListValues(allowedPermissions, [props.grantWriteAccess.toUpperCase()], 'grantWriteAccess');
147+
}
148+
149+
this.vpc = defaults.buildVpc(scope, {
150+
existingVpc: props.existingVpc,
151+
defaultVpcProps: props.publicApi ? defaults.DefaultPublicPrivateVpcProps() : defaults.DefaultIsolatedVpcProps(),
152+
userVpcProps: props.vpcProps,
153+
constructVpcProps: { enableDnsHostnames: true, enableDnsSupport: true }
154+
});
155+
156+
defaults.AddAwsServiceEndpoint(scope, this.vpc, defaults.ServiceEndpointTypes.SECRETS_MANAGER);
157+
158+
if (props.existingFargateServiceObject) {
159+
this.service = props.existingFargateServiceObject;
160+
// CheckFargateProps confirms that the container is provided
161+
this.container = props.existingContainerDefinitionObject!;
162+
} else {
163+
[this.service, this.container] = defaults.CreateFargateService(
164+
scope,
165+
id,
166+
this.vpc,
167+
props.clusterProps,
168+
props.ecrRepositoryArn,
169+
props.ecrImageVersion,
170+
props.fargateTaskDefinitionProps,
171+
props.containerDefinitionProps,
172+
props.fargateServiceProps
173+
);
174+
}
175+
176+
if (props.existingSecretObj) {
177+
this.secret = props.existingSecretObj;
178+
} else {
179+
this.secret = defaults.buildSecretsManagerSecret(this, 'secret', props.secretProps);
180+
}
181+
182+
// Enable read permissions for the Fargate service role by default
183+
this.secret.grantRead(this.service.taskDefinition.taskRole);
184+
185+
if (props.grantWriteAccess) {
186+
const permission = props.grantWriteAccess.toUpperCase();
187+
188+
if (permission === 'READWRITE') {
189+
this.secret.grantWrite(this.service.taskDefinition.taskRole);
190+
}
191+
}
192+
193+
// Configure environment variables
194+
const secretEnvironmentVariableName = props.secretEnvironmentVariableName || 'SECRET_ARN';
195+
this.container.addEnvironment(secretEnvironmentVariableName, this.secret.secretArn);
196+
}
197+
}

0 commit comments

Comments
 (0)