Skip to content

Commit

Permalink
feat(aws-fargate-ssmstringparameter): New Construct (#653)
Browse files Browse the repository at this point in the history
* created README

* created aws-fargate-ssmstringparameter construct

* revert package.json version number

* added task definition check tests

* fixed conflicting string name

Co-authored-by: biffgaut <[email protected]>
  • Loading branch information
mickychetta and biffgaut committed Apr 28, 2022
1 parent 824bb19 commit bcb7c63
Show file tree
Hide file tree
Showing 12 changed files with 3,800 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lib/*.js
test/*.js
*.d.ts
coverage
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
lib/*.js
test/*.js
*.js.map
*.d.ts
node_modules
*.generated.ts
dist
.jsii

.LAST_BUILD
.nyc_output
coverage
.nycrc
.LAST_PACKAGE
*.snk
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Exclude typescript source and config
*.ts
tsconfig.json
coverage
.nyc_output
*.tgz
*.snk
*.tsbuildinfo

# Include javascript files and typescript declarations
!*.js
!*.d.ts

# Exclude jsii outdir
dist

# Include .jsii
!.jsii

# Include .jsii
!.jsii
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# aws-fargate-ssmstringparameter module
<!--BEGIN STABILITY BANNER-->

---

![Stability: Experimental](https://img.shields.io/badge/stability-Experimental-important.svg?style=for-the-badge)

> All classes are under active development and subject to non-backward compatible changes or removal in any
> future version. These are not subject to the [Semantic Versioning](https://semver.org/) model.
> 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.
---
<!--END STABILITY BANNER-->

| **Reference Documentation**:| <span style="font-weight: normal">https://docs.aws.amazon.com/solutions/latest/constructs/</span>|
|:-------------|:-------------|
<div style="height:8px"></div>

| **Language** | **Package** |
|:-------------|-----------------|
|![Python Logo](https://docs.aws.amazon.com/cdk/api/latest/img/python32.png) Python|`aws_solutions_constructs.aws_fargate_ssmstringparameter`|
|![Typescript Logo](https://docs.aws.amazon.com/cdk/api/latest/img/typescript32.png) Typescript|`@aws-solutions-constructs/aws-fargate-ssmstringparameter`|
|![Java Logo](https://docs.aws.amazon.com/cdk/api/latest/img/java32.png) Java|`software.amazon.awsconstructs.services.fargatessmstringparameter`|

This AWS Solutions Construct implements an AWS Fargate service that can read/write to an AWS Systems Manager String Parameter

Here is a minimal deployable pattern definition:

Typescript
``` typescript
import { Construct } from 'constructs';
import { Stack, StackProps } from 'aws-cdk-lib';
import { FargateToSsmstringparameter, FargateToSsmstringparameterProps } from '@aws-solutions-constructs/aws-fargate-ssmstringparameter';

const constructProps: FargateToSsmstringparameterProps = {
publicApi: true,
ecrRepositoryArn: "arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo",
stringParameterProps: { stringValue: "test-string-value" }
};

new FargateToSsmstringparameter(stack, 'test-construct', constructProps);
```

Python
``` python
from aws_solutions_constructs.aws_fargate_ssmstringparameter import FargateToSsmstringparameter, FargateToSsmstringparameterProps
from aws_cdk import (
Stack,
aws_ssm as ssm
)
from constructs import Construct

FargateToSsmstringparameter(self, 'test_construct',
public_api=True,
ecr_repository_arn="arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo",
string_parameter_props=ssm.StringParameterProps(
string_value="test-string-value"))
```

Java
``` java
import software.constructs.Construct;

import software.amazon.awscdk.Stack;
import software.amazon.awscdk.StackProps;
import software.amazon.awscdk.services.ssm.*;
import software.amazon.awsconstructs.services.fargatessmstringparameter.*;

new FargateToSsmstringparameter(this, "test-construct", new FargateToSsmstringparameterProps.Builder()
.publicApi(true)
.ecrRepositoryArn("arn:aws:ecr:us-east-1:123456789012:repository/your-ecr-repo")
.stringParameterProps(new StringParameterProps.Builder()
.stringValue("test-string-value")
.build())
.build());
```

## Pattern Construct Props

| **Name** | **Type** | **Description** |
|:-------------|:----------------|-----------------|
| publicApi | `boolean` | Whether the construct is deploying a private or public API. This has implications for the VPC. |
| 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. |
| 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. |
| 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. |
| 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* |
| ecrImageVersion? | `string` | The version of the image to use from the repository. Defaults to 'Latest' |
| 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) |
| 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) |
| 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. |
| 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 |
| 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 |
|existingStringParameterObj?|[`ssm.StringParameter`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html)|Existing instance of SSM String parameter object, providing both this and `stringParameterProps` will cause an error|
|stringParameterProps?|[`ssm.StringParameterProps`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameterProps.html)|Optional user provided props to override the default props for SSM String parameter. If existingStringParameterObj is not set stringParameterProps is required. The only supported [`ssm.StringParameterProps.type`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameterProps.html#type) is [`STRING`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.ParameterType.html#string) if a different value is provided it will be overridden.|
|stringParameterPermissions?|`string`|Optional SSM String parameter permissions to grant to the Fargate service. One of the following may be specified: "Read", "ReadWrite".
|stringParameterEnvironmentVariableName?|`string`|Optional Name for the SSM parameter name environment variable set for the container.|

## Pattern Properties

| **Name** | **Type** | **Description** |
|:-------------|:----------------|-----------------|
| 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) |
| 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) |
| 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. |
|stringParameter|[`ssm.StringParameter`](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ssm.StringParameter.html)|Returns an instance of `ssm.StringParameter` created by the construct|

## Default settings

Out of the box implementation of the Construct without any override will set the following defaults:

### AWS Fargate Service
* Sets up an AWS Fargate service
* Uses the existing service if provided
* Creates a new service if none provided.
* Service will run in isolated subnets if available, then private subnets if available and finally public subnets
* Adds environment variables to the container with the ARN and Name of the SSM parameter
* Add permissions to the container IAM role allowing it to read/write to the SSM parameter

### AWS SSM String Parameter
* Sets up an AWS SSM String Parameter
* Uses an existing parameter if one is provided, otherwise creates a new one
* Adds an Interface Endpoint to the VPC for SSM parameter (the service by default runs in Isolated or Private subnets)

## Architecture
![Architecture Diagram](architecture.png)

***
&copy; Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/**
* Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/

import * as ec2 from "@aws-cdk/aws-ec2";
import * as ssm from "@aws-cdk/aws-ssm";
// Note: To ensure CDKv2 compatibility, keep the import statement for Construct separate
import { Construct } from "@aws-cdk/core";
import * as defaults from "@aws-solutions-constructs/core";
import * as ecs from "@aws-cdk/aws-ecs";

export interface FargateToSsmstringparameterProps {
/**
* Whether the construct is deploying a private or public API. This has implications for the VPC deployed
* by this construct.
*
* @default - none
*/
readonly publicApi: boolean;
/**
* Optional custom properties for a VPC the construct will create. This VPC will
* be used by the new Fargate service the construct creates (that's
* why targetGroupProps can't include a VPC). Providing
* both this and existingVpc is an error. An SSM Interface
* endpoint will be included in this VPC.
*
* @default - none
*/
readonly vpcProps?: ec2.VpcProps;
/**
* An existing VPC in which to deploy the construct. Providing both this and
* vpcProps is an error. If the client provides an existing Fargate service,
* this value must be the VPC where the service is running. An SSM Interface
* endpoint will be added to this VPC.
*
* @default - none
*/
readonly existingVpc?: ec2.IVpc;
/**
* Optional properties to create a new ECS cluster
*/
readonly clusterProps?: ecs.ClusterProps;
/**
* The arn of an ECR Repository containing the image to use
* to generate the containers
*
* format:
* arn:aws:ecr:[region]:[account number]:repository/[Repository Name]
*/
readonly ecrRepositoryArn?: string;
/**
* The version of the image to use from the repository
*
* @default - 'latest'
*/
readonly ecrImageVersion?: string;
/*
* Optional props to define the container created for the Fargate Service
*
* defaults - fargate-defaults.ts
*/
readonly containerDefinitionProps?: ecs.ContainerDefinitionProps | any;
/*
* Optional props to define the Fargate Task Definition for this construct
*
* defaults - fargate-defaults.ts
*/
readonly fargateTaskDefinitionProps?: ecs.FargateTaskDefinitionProps | any;
/**
* 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.
*
* defaults - fargate-defaults.ts
*/
readonly fargateServiceProps?: ecs.FargateServiceProps | any;
/**
* 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:
* existingImageObject, ecrImageVersion, containerDefintionProps, fargateTaskDefinitionProps,
* ecrRepositoryArn, fargateServiceProps, clusterProps, existingClusterInterface. If this value
* is provided, then existingContainerDefinitionObject must be provided as well.
*
* @default - none
*/
readonly existingFargateServiceObject?: ecs.FargateService;
/*
* A container definition already instantiated as part of a Fargate service. This must
* be the container in the existingFargateServiceObject.
*
* @default - None
*/
readonly existingContainerDefinitionObject?: ecs.ContainerDefinition;
/**
* Optional user provided props to override the default props for SSM String Parameter.
*
* @default - Default props are used
*/
readonly stringParameterProps?: ssm.StringParameterProps;
/**
* Optional user provided props to override the default props for SSM String Parameter.
*
* @default - None
*/
readonly existingStringParameterObj?: ssm.StringParameter;
/**
* Optional SSM String parameter permissions to grant to the Fargate service. One of the following may be specified: "Read", "ReadWrite".
*
* @default - 'Read'
*/
readonly stringParameterPermissions?: string
/**
* Optional Name for the SSM parameter name environment variable set for the container.
*
* @default - None
*/
readonly stringParameterEnvironmentVariableName?: string;
}

export class FargateToSsmstringparameter extends Construct {
public readonly vpc: ec2.IVpc;
public readonly service: ecs.FargateService;
public readonly container: ecs.ContainerDefinition;
public readonly stringParameter: ssm.StringParameter;

constructor(scope: Construct, id: string, props: FargateToSsmstringparameterProps) {
super(scope, id);
defaults.CheckProps(props);
defaults.CheckFargateProps(props);

// Other permissions for constructs are accepted as arrays, turning stringParameterPermissions into
// an array to use the same validation function.
if (props.stringParameterPermissions) {
const allowedPermissions = ['READ', 'READWRITE'];
defaults.CheckListValues(allowedPermissions, [props.stringParameterPermissions.toUpperCase()], 'stringParameterPermissions');
}

this.vpc = defaults.buildVpc(scope, {
existingVpc: props.existingVpc,
defaultVpcProps: props.publicApi ? defaults.DefaultPublicPrivateVpcProps() : defaults.DefaultIsolatedVpcProps(),
userVpcProps: props.vpcProps,
constructVpcProps: { enableDnsHostnames: true, enableDnsSupport: true }
});

defaults.AddAwsServiceEndpoint(scope, this.vpc, defaults.ServiceEndpointTypes.SSM);

if (props.existingFargateServiceObject) {
this.service = props.existingFargateServiceObject;
// CheckFargateProps confirms that the container is provided
this.container = props.existingContainerDefinitionObject!;
} else {
[this.service, this.container] = defaults.CreateFargateService(
scope,
id,
this.vpc,
props.clusterProps,
props.ecrRepositoryArn,
props.ecrImageVersion,
props.fargateTaskDefinitionProps,
props.containerDefinitionProps,
props.fargateServiceProps
);
}

// Setup the SSM String parameter
if (props.existingStringParameterObj) {
this.stringParameter = props.existingStringParameterObj;
} else {
if (!props.stringParameterProps) {
throw new Error("existingStringParameterObj or stringParameterProps needs to be provided.");
}
this.stringParameter = defaults.buildSsmStringParameter(this, 'stringParameter', props.stringParameterProps);
}

this.stringParameter.grantRead(this.service.taskDefinition.taskRole);

if (props.stringParameterPermissions) {
const _permissions = props.stringParameterPermissions.toUpperCase();

// Add the requested string parameter permission
if (_permissions === 'READWRITE') {
this.stringParameter.grantWrite(this.service.taskDefinition.taskRole);
}
}

// Add environment variables
const stringParameterEnvironmentVariableName = props.stringParameterEnvironmentVariableName || 'SSM_STRING_PARAMETER_NAME';
this.container.addEnvironment(stringParameterEnvironmentVariableName, this.stringParameter.parameterName);
}
}
Loading

0 comments on commit bcb7c63

Please sign in to comment.