Giter Site home page Giter Site logo

cloudcomponents / cdk-constructs Goto Github PK

View Code? Open in Web Editor NEW
612.0 20.0 102.0 10.45 MB

A collection of higher-level reusable cdk constructs

License: MIT License

JavaScript 0.01% TypeScript 99.08% HTML 0.53% Shell 0.20% Dockerfile 0.18%
aws cdk slack github aws-cdk contentful webhooks stripe codepipeline devops

cdk-constructs's Introduction

cloudcomponents Logo

@cloudcomponents/cdk-constructs

Build Status cdkdx typescript python

A collection of higher-level reusable cdk constructs

Constructs

This repository is a monorepo managed with Lerna. Several constructs are published to pypi and npm from the same codebase.

Constructs Description Npm-Downloads
cdk-codepipeline-slack #slack approval workflow and notification messages on codepipeline state changes npm
cdk-contentful-webhook Create, update and delete contentful webhooks with your app deployment npm
cdk-github-webhook Create, update and delete github webhooks with your app deployment npm
cdk-stripe-webhook Create, update and delete stripe webhooks with your app deployment npm
cdk-static-website Static website using S3, configures CloudFront (CDN) and maps a custom domain via Route53 (DNS) npm
cdk-pull-request-check CodeCommit pull request check npm
cdk-pull-request-approval-rule CodeCommit pull request approval rules to enforcing your pull request workflow npm
cdk-codepipeline-merge-action CodePipeline action to merge branches npm
cdk-codepipeline-check-parameter-action Cdk component that checks if system parameters are set correctly npm
cdk-codecommit-backup Backup CodeCommit repositories to S3 npm
cdk-dependency-check OWASP dependency-check for codecommit repositories npm
cdk-container-registry Registry for container images npm
cdk-blue-green-container-deployment Blue green container deployment with CodeDeploy npm
cdk-chatops Constructs for chattool integration: #slack / msteams npm
cdk-developer-tools-notifications #slack / msteams / email notifications for developer tools: CodeCommit, CodeBuild, CodeDeploy, CodePipeline npm
cdk-deletable-bucket Bucket with content cleanup to allow bucket deletion when the stack will be destroyed npm
cdk-codepipeline-dockerfile-linter-action CodePipeline action to lint dockerfiles with hadolint npm
cdk-codepipeline-anchore-inline-scan-action CodePipeline action to integrate Anchore Engine into your pipeline npm
cdk-dynamodb-seeder A seeder for dynamodb tables npm
cdk-temp-stack A stack that destroys itself after a given time (ttl) npm
cdk-lambda-at-edge-pattern CDK Constructs for Lambda@Edge pattern: HttpHeaders npm
cdk-cloudfront-authorization CloudFront with Cognito authentication using Lambda@Edge npm
cdk-secret-key Provide secret keys to lambdas npm
cdk-responsive-email-template Responsive email template for aws ses npm
cdk-s3-antivirus Antivirus for Amazon S3 npm
cdk-wordpress CDK Construct to deploy wordpress npm

Contributing

We welcome community contributions and pull requests.

License

MIT

cdk-constructs's People

Contributors

bdq avatar brentryan avatar calvinwyoung avatar cardosi avatar cathiele avatar cuperman avatar dependabot[bot] avatar hupe1980 avatar idvb avatar joeflateau avatar kadishmal avatar kieranjen avatar kimisme9386 avatar livefreeorcode avatar mbp avatar neilkuan avatar pcariel avatar rogperez avatar rpivo avatar vondeetzen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cdk-constructs's Issues

[PullRequestCheck] Error using package, no found resource lambda

Hi, @hupe1980.

I like your work,
I have a problem when I try to use the package.

import { PullRequestCheck } from "@cloudcomponents/cdk-pull-request-check";
new PullRequestCheck(this, "PullRequestCheck", {
      repository,
      buildSpec: BuildSpec.fromObject({
        version: "0.2",
        phases: {
          build: {
            commands: ['echo "Hello, CodeBuild!"']
          }
        }
      })
    });

at new PullRequestCheck (/node_modules/@cloudcomponents/cdk-pull-request-check/src/pull_request_check.ts:48:37)
ENOENT: no such file or directory, stat PATH_MY_APP/resources'

can you help me with this?
Thank you

Support for www->apex redirect or apex->www

Generally I end up manually creating the empty bucket and CloudFront distribution to do a redirect from www -> apex. It'd be great if this was either a separate construct (RedirectWebsite perhaps?) or configuration you could apply to StaticWebsite to get it to set this up for you.

Stripe Webhook does not work with secrets vended by SecretsManager

What I'm trying to do:

...
const secretKey = SecretValue.secretsManager(stripeKeySecretName)
...

new StripeWebhook(this, 'StripeWebhook', {
            secretKey: secretKey.toString(),
            url: api.url,
            events,
            logLevel: 'debug',
        })

That is to read stripe secret key value from SecretsManager vs providing it in code which is problematic.
I get the following error when trying to deploy this:

6:44:59 PM | CREATE_FAILED        | Custom::StripeWebhook       | StripeWebhookCustomResource8D1A2FEA
Failed to create resource. Invalid API Key provided: {{resolv********************************************************
*************************************************::}}

Expected outcome:

The key can be resolved from secrets manager.


Ideally I think this interface would actually accept the SecretValue instead of a string (and you can build that either directly from text or from SecretsManager/SSM/etc

ContainerPort not working

Hi, I'm trying to specify a container port but it seems like props is not working properly and keep default back to 80

Received response status [FAILED] from custom resource. Message returned: InvalidPar
ameterException: The container sample-website did not have a container port 80 defined.
const taskDefinition = new DummyTaskDefinition(this, 'DummyTaskDefinition', {
      image: 'nginx',
      family: this.props.family,
      containerPort: 8080,
    });

Slack notifier Lambda ignores channel ID passed to SlackNotifier construct

The Slack notifier Lambda ignores the channel ID passed to the SlackNotifier construct:

const {
SLACK_BOT_TOKEN,
SLACK_CHANNEL,
SLACK_BOT_NAME,
SLACK_BOT_ICON,
} = process.env;

The Slack manual approval Lambda rightly picks up the channel ID:

const {
SLACK_BOT_TOKEN,
SLACK_CHANNEL,
SLACK_CHANNEL_ID,
SLACK_BOT_NAME,
SLACK_BOT_ICON,
} = process.env;

Only one DynamoDB seeder possible per CDK stack

We encountered an issue in which multiple DynamoDBSeeder instances cause the stack deployment to fail. The problem seems to be missing permission to access the staged seed files on S3.

I created a minimal stack to reproduce the issue: https://github.com/robdasilva/cdk-dynamo-db-seeder-s3-role-issue

After looking into the synthesized stack output, it seems, that there is a policy attached to the CustomServiceProvider for each seed. However, they all reference the same resource—i.e. the seed file of the first seeder. The same behavior is seen for the BatchWriteItem policy of the respective DynamoDB tables: There is only one statement for the first table.

That causes the stack deployment to fail once it reaches any subsequent seeder, due to the CustomResource being unable to access the respective file on S3.

Feature Request: More configurability for CloudFront with StaticWebsite

We use React Router on pages that we're deploying with StaticWebsite.

This means we're deploying a single index.html but all paths need to map to it so the client side routing can work. We normally do this like so:
https://hackernoon.com/hosting-static-react-websites-on-aws-s3-cloudfront-with-ssl-924e5c134455

e.g. set up a custom error page with a 200 response and index.html.

I'm proposing to expose errorConfigurations as an optional field in StaticWebsiteProps which we pass directly to the CloudFrontWebDistribution constructor.

Another alternative would be to expose something like cloudFrontSettings which allows users to override all CloudFront configuration as exposed by CDK directly with a spread, but that feels a bit heavy handed when we're only allowing a couple of options at the moment, hence the proposal above.

[cdk-static-website] Allow skipping Route 53 records

Hi there,

Thanks so much for creating this project, really glad to see something like this exist 👍

I was just wondering if the maintainers would be open to a new option in the cdk-static-website package that prevents Route 53 records from being created. This would be for scenarios where DNS is being handled externally (e.g. GoDaddy).

Happy to create a PR if there's interest

bug(dynamodb-seeder): CustomResource cannot access KMS key

When a DynamoDB table has a customer-managed CMK, the following error occurs:

Received response status [FAILED] from custom resource. Message returned: KMS key access denied error: com.amazonaws.services.kms.model.AWSKMSException: The ciphertext refers to a customer master key that does
not exist, does not exist in this region, or you are not allowed to access. (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: d7d7828b-5a92-40d3-b306-e3cfae47f761; Proxy: null)
(RequestId: fb5a9bb1-a81c-4504-a541-b172aa2797a9)

#99 gives the appropriate actions to the IAM role policy for the lambda, but it seems that the CustomResource does not have access to the KMS key...

@hupe1980 🙃

[cdk-cloudfront-authorization] Support alternate domain name

This resource is amazing and exactly what I've been looking for! The Cloudfront Lambda@Edge authorization stacks work almost exactly for what I need. One thing I would like to do that doesn't currently seem to be supported is to create an alternate CNAME record for my Cloudfront URL and use that instead of the default Cloudfront URL. I configure the Distribution as desired with the certificate and alternate domain names properties specified, but when I try to go to my site using the alternate domain name, I get an auth error page with error=redirect_mismatch in the URL.

So my request is for an alternateDomainName property to be added to the Distribution classes and, if specified, use that domain name as the canonical base URL. I think that would then just need to be updated here:

    props.authorization.updateUserPoolClientCallbacks({
      callbackUrls: [`https://${distribution.distributionDomainName}${props.authorization.redirectPaths.signIn}`],
      logoutUrls: [`https://${distribution.distributionDomainName}${props.authorization.redirectPaths.signOut}`],
    });

Thank you!

[PullRequestCheck] Organize lambda by folders

Hello, @hupe1980 . Maybe this requirement is not relevant, you can close if you wish.

Is there a possibility to forget the lambda in folders? to be able to view only the source file of it?

Sorry for my bad English.
Thank you
image

DummyTaskDefinition container_port is ignored

Hi!

I am currently trying to set up an ECS blue/green deployment using your module (python).

I have noticed a potential issue when creating the dummy task definition. When running cdk deploy I get the following error:

CREATE_FAILED | Custom::BlueGreenService | Service/CustomResource/Default (ServiceCustomResourceE0E93D09) Failed to create resource. InvalidParameterException: The container sample-website did not have a container port 8080 defined.

It seems that the container_port attribute of DummyTaskDefinition is ignored.

Having reviewed the code it looks like it isn't outputted to the custom resource template that is created in CloudFormation and also isn't used in the lambda function that creates the dummy task definition.

If it helps you I can look into creating a pull request to fix this?

StaticSite support to root object in Cloudfront distribution to deploy Hugo, Gatsby and statically generated websites

We are trying to deploy a static website using the StaticSite construct.
When you host a Hugo website on S3 it functions perfectly but when you move it to CloudFront you likely get the nasty “AccessDenied” error. This is because the behavior of CloudFront’s default root object is quite different from the behavior of Amazon S3 index documents and how it deals with root objects. When you configure an Amazon S3 bucket as a website and specify the index document, Amazon S3 returns the index document even if a user requests a different subdirectory. This is absolutely not how CloudFront works thus you get the “AccessDenied” error.

We found out the following link is suggesting a possible solution link including an additional lambda at edge that includes the default root object to a subdirectory in case it is missing.

Would it be possible to include this feature in this library to enable the deployment of statically generated website (including Hugo, Gatsby, etc)?

Thank you very much in advance!

Feature Request: Allow VPC declaration in PullRequestCheck

First off - Thank you for all the work that has been done here, cdk-constructs is really cool and I think I'll get a lot of use out of it!

Feature Request

I'd like to be able to pass an iVPC to PullRequestCheck so that the CodeBuild Project can run in a VPC. Here's AWS's documentation on CodeBuild + VPCs that has some use cases that may demonstrate why this would be useful (beyond my own).

I'm not very well versed in JS/TS (I've been using the Python implementation of CDK), but I went ahead and created a PR anyway because it seemed like a pretty straight forward change. Hopefully it's helpful. #94

FullRegionS3CodeCommitBackup failes when repositories_names are specified

When explicity specifying the names of the repositories you want to backup, all the entries in the array are merged into one string.

This string is then used as codecommit repo name:

repository_names = ["repo_name_one", "repo_name_two"]

Running command ./backup_codecommit.sh
--
declare -a repos '[' -z repo_name_one repo_name_two ']'
./backup_codecommit.sh: line 7: [: repo_name_one: binary operator expected repos='repo_name_one repo_name_two' for codecommitrepo in "${repos[@]}"] 
echo '[===== Backup repository: repo_name_one repo_name_two =====]'
[===== Backup repository: repo_name_one repo_name_two =====]
git clone 'https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/repo_name_one repo_name_two'
Cloning into 'repo_name_one repo_name_two'...
fatal: unable to access 'https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/repo_name_one repo_name_two/': The requested URL returned error: 505

npm package @cloudcomponents/[email protected] fails to run

After installing and configuring @cloudcomponents/[email protected] (the latest stable version), lambda SNS listener fails to run with the error:

{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module '@slack/web-api'",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module '@slack/web-api'",
        "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
        "    at Module.load (internal/modules/cjs/loader.js:653:32)",
        "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
        "    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
        "    at startup (internal/bootstrap/node.js:283:19)"
    ]

If I repackage lambda code myself with all prod-scoped dependencies - it works fine

cdk-blue-green allow specifying alarms to trigger a rollback

The aws-sdk exposes an alarmConfigurationattribute to configure alarms that trigger a rollback of the blue-green deployment.

This could be exposed to the CDK.

I will look at opening a PR at some point soon to implement this if that is ok?

Graceful Deletion of Lambda@Edge support stack

Hi,

I started using your awesome package recently to support lambda@edge function from a non us-east-1 stack.

I have a problem though regarding graceful deletion of the stack that used EdgeFunction construct.

When I try to delete my main stack, it fails because the edge support stack cannot be deleted because the replicated function used by cloudfront could not be deleted either.

I was wondering if there is a way to mark edge function removal policy as RETAIN, so deleting the edge support stack would not fail ?

Bug: `ApprovalRuleTemplateRepositoryAssociation` creates only one `CustomResourceProviderRole`

"@aws-cdk/core": "1.102.0",
"@cloudcomponents/cdk-pull-request-approval-rule": "1.35.0",

Bug: ApprovalRuleTemplateRepositoryAssociation creates only one CustomResourceProviderRole. while it should create one separate for each instance.

Reproduction steps:

I created a construct called CodeCommitPRApprovers that creates the approval rule template and its association:

export class CodeCommitPRApprovers extends Construct {
  constructor(scope: Construct, id: string, { repo }: CodeCommitPRApproversProps) {
    super(scope, id);

    // At the moment Esen will be required to approve all the pull requests.
    const userARN = User.fromUserName(this, 'user', 'user').userArn;

    const { approvalRuleTemplateName } = new ApprovalRuleTemplate(this, `${id}ApprovalRuleTemplate`, {
      approvalRuleTemplateName: `master-branch-required-approvers-for-${id}`,
      template: {
        approvers: {
          approvalPoolMembers: [userARN],
          numberOfApprovalsNeeded: 1
        },
        branches: ['master']
      }
    });

    new ApprovalRuleTemplateRepositoryAssociation(this, `${id}ApprovalRuleTemplateRepositoryAssociation`, {
      approvalRuleTemplateName,
      repository: repo,
    });
  }
}

Then in a stack I instantiate this construct twice, one for each repository as follows:

export class DevStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const infrastructureRepository = new Repository(this, 'InfrastructureRepository', {
      repositoryName: 'infrastructure',
      description: 'The CodeCommit repository for the infrastructure code.',
    });

    new CodeCommitPRApprovers(this, 'InfrastructurePRApprovers', {
      repo: infrastructureRepository
    });

    const websiteRepo = new Repository(this, 'WebRepository', {
      repositoryName: 'web',
      description: "The CodeCommit repository for the Web application code.",
    });

    new CodeCommitPRApprovers(this, 'WebsitePRApprovers', {
      repo: websiteRepo
    });

The generated CloudFormation template includes only one CustomResourceProviderRole:

"CustomApprovalRuleTemplateRepositoryAssociationCustomResourceProviderRoleD1B94887": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Action": "sts:AssumeRole",
              "Effect": "Allow",
              "Principal": {
                "Service": "lambda.amazonaws.com"
              }
            }
          ]
        },
        "ManagedPolicyArns": [
          {
            "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
          }
        ],
        "Policies": [
          {
            "PolicyName": "Inline",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "codecommit:AssociateApprovalRuleTemplateWithRepository",
                    "codecommit:DisassociateApprovalRuleTemplateFromRepository"
                  ],
                  "Resource": {
                    "Fn::GetAtt": [
                      "WebRepository0EB245C6",
                      "Arn"
                    ]
                  }
                }
              ]
            }
          }
        ]
      },
      "Metadata": {
        "aws:cdk:path": "DevStack/Custom::ApprovalRuleTemplateRepositoryAssociationCustomResourceProvider/Role"
      }
    },

The same CustomResourceProviderRole is not created for the infrastructure CodeCommit repository which means Lambda will have permissions to perform operations only to the specified Web repository.

Am I using this correctly?

codepipeline-slack usage with multiple pipelines in a single stack

Context

I'm following this tutorial to setup a CDK pipeline.
As I want to follow a gitflow like workflow (develop deploying to Staging and main deploying to Prod), I am creating multiple CDK pipelines within a single CDK stack.
And for each pipeline, I would like to setup a slack notifier and in some case a slack approval action.
However when deploying, I am facing this error:

[Container] 2020/12/16 11:09:22 Running command npx cdk synth
Bundling asset MyProjectPipelineStack/Staging/MyStack/MyLambda/Code/Stage...
There is already a Construct with name 'SlackNotifierFunction' in MyProjectPipelineStack [MyProjectPipelineStack]
Subprocess exited with error 1

This is due to the fact that all the resources in @cloudcomponents/cdk-codepipeline-slack have static names, widh prevent from deploying multiple instances in the same stack, in this case SlackNotifierFunction.

My first thought was that we should add the construct ID to the resources it creates. However, that means it would create multiples lambda and API gateway endpoints, which would mean creating multiple slack apps (one for each endpoints) and wouldn't be convenient.

What is, in your opinion, the best way to allow deploying multiple pipelines with slack in a single stack?

Code of the pipeline stack

import * as codepipeline from '@aws-cdk/aws-codepipeline';
import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions';
import { Construct, SecretValue, Stack, StackProps } from '@aws-cdk/core';
import { CdkPipeline, SimpleSynthAction } from '@aws-cdk/pipelines';
import { SlackApprovalAction, SlackNotifier } from '@cloudcomponents/cdk-codepipeline-slack';
import { MyProjectStage } from './my-project-stage';

export class MyProjectPipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    this.createPipeline('develop', 'Staging');
    this.createPipeline('main', 'Prod', true);
  }

  createPipeline(branch: string, stage: string, slack=false) {
    const sourceArtifact = new codepipeline.Artifact();
    const cloudAssemblyArtifact = new codepipeline.Artifact();
    const pipeline = new CdkPipeline(this, `${stage}-Pipeline`, {
      // The pipeline name
      pipelineName: `${stage}-MyProjectPipeline`,
      cloudAssemblyArtifact,

      // Where the source can be found
      sourceAction: new codepipeline_actions.GitHubSourceAction({
        actionName: 'GitHub',
        output: sourceArtifact,
        oauthToken: SecretValue.secretsManager('github-token'),
        owner: '<GITHUB_OWNER>',
        repo: '<GITHUB_REPO>',
        branch,
      }),

      // How it will be built and synthesized
      synthAction: SimpleSynthAction.standardNpmSynth({
        sourceArtifact,
        cloudAssemblyArtifact,

        // We need a build step to compile the TypeScript Lambda
        buildCommand: 'npm run build',
      }),
    });

    const slackBotToken = SecretValue.secretsManager('slack-bot-token').toString();
    const slackSigningSecret = SecretValue.secretsManager('slack-signing-secret').toString();
    const slackChannel = 'notifications-aws';

    const applicationStage = pipeline.addApplicationStage(new MyProjectStage(this, stage, {
      env: { account: '<AWS_ACCOUNT_ID>', region: '<AWS_REGION>' },
    }));
    if (slack) {
      applicationStage.addActions(new SlackApprovalAction({
        actionName: `${stage}-SlackApproval`,
        slackBotToken,
        slackSigningSecret,
        slackChannel,
        // externalEntityLink: 'http://cloudcomponents.org',
        additionalInformation: `Would you like to promote the build to ${stage}?`,
      }));
      new SlackNotifier(this, `${stage}-SlackNotifier`, {
        pipeline: pipeline.codePipeline,
        slackBotToken,
        slackSigningSecret,
        slackChannel,
      });
    }

    return pipeline;
  }
}

Unable to send custom Role for Task definition

When using this cdk-blue-green-container-deployment plugin, For task definition it creates the roles by default. There should be a provision to supply own roles.

const taskDefinition = new DummyTaskDefinition(
this,
'DummyTaskDefinition',
{
image: 'nginx',
family: 'blue-green',
},
executionRole:
);

fix(dynamodb-seeder): Grant `encryptionKey` access

When a table has an encryptionKey, the SingletonFunction does not have the proper access.

The manual policy entry, should be replaced by grantWriteData, which gives the appropriate access to the KMS key if it exists.

props.table.grantWriteData(handler);

I can, and may put a PR in for this myself, but I ran into some test failures that I didn't have time to research at the moment, and wanted to get this documented in the very least.

Compilation error for cloudfront-authorization lambdas

I'm trying to build & deploy an unmodified instance of the cdk-cloudfront-authorization stack, but I'm continually getting an error from ./src/lambdas/shared/config.ts saying that template.html is not found:

cdkdx build
ERROR Failed to compile with 1 errors 11:30:47 AM

This relative module was not found:
./template.html in ./src/lambdas/shared/config.ts

template.html is definitely in the /shared directory.

This happens while running 'npm run-script build' or a 'cdk deploy...' command from /packages/cdk-cloudfront-authorization

Deploying to Static Website

It'd be awesome if passing in a source path to a directory also created a BucketDeployment so users can deploy to the static website along with creating it.

(I'd be happy to make a PR for this if it's desired behaviour.)

Feature request: CloudFormation Outputs

First, this is an amazing resource and thanks for the work that has gone into it.

It would be extremely helpful to include CloudFormation Outputs for each stack in order to facilitate cross-stack integration with other CDK apps. Things like ARNs for the Lambda@Edge functions in the cdk-cloudfront-authorization stack, for example.

@cloudcomponents/cdk-static-website support CustomErrorResponse option

@cloudcomponents/cdk-static-website support CustomErrorResponse option

I placed SPA web in S3, so I want users to return to index.html when refreshing the page

截圖 2020-12-28 下午1 18 21

I hope @cloudcomponents/cdk-static-website can add option CustomErrorResponse like this:

    const distibutionConfig: CloudFrontWebDistributionProps = {
      webACLId,
      enableIpV6: !disableIPv6,
      originConfigs: [
        {
          s3OriginSource: {
            ...websiteBucket.s3OriginConfig,
          },
          behaviors: [{ isDefaultBehavior: true }],
        },
      ],
      aliasConfiguration,
      customErrorResponses: this.customErrorResponses ?? undefined,
    };

Use the same Slack Chat with diferents pipelines

Hi,

I would like if it is possible to know how I can use the same Slack Channel with different stacks, currently, I received the next error:

Invalid request provided: Slack channel with ID XXXXXXXXX in Slack team XXXXXXXXX has already been configured for AWS account XXXXXXXXX. (Service: AWSChatbot; Status Code: 400; Error Code: InvalidRequestException; Request ID: XXXXXXXXX; Proxy: null)

Use Slack Conversation API instead of deprecated methods

I noticed a deprecation warning in the CloudWatch logs of the Slack notifier Lambda.

[WARN]  web-api:WebClient:0 channels.history is deprecated. Please use the Conversations API instead. For more info, go to https://api.slack.com/changelog/2020-01-deprecating-antecedents-to-the-conversations-api

Slack will stop supporting the channels.*, groups.*, im.*, and mpim.* methods in favor of their new Conversations API (see here).

Starting from June 10th, 2020 newly created apps will no longer be allowed to use the deprecated methods.
On February 24th, 2021 the deprecated methods will be removed.

autoRollbackConfiguration not configurable

currently the custom construct for ecs blue green CreateDeploymentGroup you cant enable the auto rollback configuration.
as a minimum this should be allowed to be enabled when a deployment fails (DEPLOYMENT_FAILURE) or on request (DEPLOYMENT_STOP_ON_REQUEST )

more info on the api here: https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_AutoRollbackConfiguration.html

Improve documentation for Slack integration setup

The README describes adding the channels::history scope to the app.

However, different scopes seem to be required. CloudWatch logs for the Slack notifier Lambda contain the following error message:

{
    "errorType": "Runtime.UnhandledPromiseRejection",
    "errorMessage": "Error: An API error occurred: missing_scope",
    "reason": {
        "errorType": "Error",
        "errorMessage": "An API error occurred: missing_scope",
        "code": "slack_webapi_platform_error",
        "data": {
            "ok": false,
            "error": "missing_scope",
            "needed": "channels:read,groups:read,mpim:read,im:read",
            "provided": "channels:history",
            "response_metadata": {
                "scopes": [
                    "channels:history"
                ],
                "acceptedScopes": [
                    "channels:read",
                    "groups:read",
                    "mpim:read",
                    "im:read"
                ]
            }
        },
        "stack": [
            "Error: An API error occurred: missing_scope",
            "    at Object.platformErrorFromResult (/var/task/node_modules/@slack/web-api/dist/errors.js:50:33)",
            "    at WebClient.apiCall (/var/task/node_modules/@slack/web-api/dist/WebClient.js:491:28)",
            "    at process._tickCallback (internal/process/next_tick.js:68:7)"
        ]
    },
    "promise": {},
    "stack": [
        "Runtime.UnhandledPromiseRejection: Error: An API error occurred: missing_scope",
        "    at process.on (/var/runtime/index.js:37:15)",
        "    at process.emit (events.js:198:13)",
        "    at process.EventEmitter.emit (domain.js:448:20)",
        "    at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)",
        "    at process._tickCallback (internal/process/next_tick.js:69:34)"
    ]
}

It appears that the scopes channels:read, groups:read, mpim:read, im:read are required (instead of channels:history?).

Slack is deprecating a lot of methods in favor of their new Conversations API (see #33). The required scopes might possibly change as well

Slack Notifier: expose Api

I'd gladly submit a PR if you're ok with this. I'm interested in accessing the Api Gateway a little easier than using the escape hatch to get to the L1 constructs. Would you be ok with that?

The reason being is I'd like to add a route53 entry, and change the name so I can tell the difference between them in the console, and maybe a few other properties.

And thanks for publishing this! 🍺

Slack integrations for CodePipeline break with CDK 1.41.0

CodePipeline Slack integrations stopped working after upgrading to CDK 1.41.0 (released today).

SlackApprovalAction:

error TS2322: Type '(CloudFormationExecuteChangeSetAction | CloudFormationCreateReplaceChangeSetAction | SlackApprovalAction)[]' is not assignable to type 'IAction[]'.
  Type 'CloudFormationExecuteChangeSetAction | CloudFormationCreateReplaceChangeSetAction | SlackApprovalAction' is not assignable to type 'IAction'.
    Type 'SlackApprovalAction' is not assignable to type 'IAction'.
      The types of 'actionProperties.role' are incompatible between these types.
        Type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/role").IRole | undefined' is not assignable to type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/role").IRole | undefined'.
          Type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/role").IRole' is not assignable to type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/role").IRole'.
            Types of property 'grant' are incompatible.
              Type '(grantee: import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/principals").IPrincipal, ...actions: string[]) => import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/grant").Grant' is not assignable to type '(grantee: import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/principals").IPrincipal, ...actions: string[]) => import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/grant").Grant'.
                Types of parameters 'grantee' and 'grantee' are incompatible.
                  Type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/principals").IPrincipal' is not assignable to type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/principals").IPrincipal'.
                    Types of property 'addToPolicy' are incompatible.
                      Type '(statement: import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/policy-statement").PolicyStatement) => boolean' is not assignable to type '(statement: import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/policy-statement").PolicyStatement) => boolean'.
                        Types of parameters 'statement' and 'statement' are incompatible.
                          Type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-events/node_modules/@aws-cdk/aws-iam/lib/policy-statement").PolicyStatement' is not assignable to type 'import("/Users/erikmuller/Documents/Detelling/cdk/node_modules/@aws-cdk/aws-iam/lib/policy-statement").PolicyStatement'.
                            Types have separate declarations of a private property 'action'.

SlackNotifier:

error TS2345: Argument of type 'this' is not assignable to parameter of type 'Construct'.
  Type 'PipelineStack' is not assignable to type 'Construct'.
    Property 'onValidate' is protected but type 'Construct' is not a class derived from 'Construct'.

add permissions boundary option for iam roles regarding the custom resources of cdk-pull-request-approval-rule

Sorry for the lack of description.

The custom resource will invoke a lambda function for cdk-pull-request-approval-rule and for cdk-pull-request-approval-rule-association.
This lambda function requires an execution/invocation IAM role.
The cdk deploy will fail with explicit deny creating the necessary role(s):

2020-11-18 09:29:46 UTC+0200 | CustomApprovalRuleTemplateCustomResourceProviderRoleBFA17D2F | CREATE_FAILED | API: iam:CreateRole User: arn:aws:sts::123456789012:assumed-role/Engineer/lagrianitis is not authorized to perform: iam:CreateRole on resource: arn:aws:iam::123456789012:role/cdk-constructs-CustomApprovalRuleTemplateCustomRes-1JBWAZH9LHIGR with an explicit deny
-- | -- | -- | --
2020-11-18 09:29:45 UTC+0200 | CustomApprovalRuleTemplateCustomResourceProviderRoleBFA17D2F | CREATE_IN_PROGRESS | Did not have IAM permissions to process tags on AWS::IAM::Role resource.

The reason for that is that there is a company policy where all principals require to attach a role permissions boundary in any IAM role to be able to deploy it due to security reason.

Said that I am unsure where exactly this can be fit in the custom construct as my Typescript skill are poor.
I think https://docs.aws.amazon.com/cdk/api/latest/docs/custom-resources-readme.html#customizing-the-lambda-function-implementing-the-custom-resource might help.

[cdk-cloudfront-authorization] SpaAuthorization doesn't work inside NestedStack with CDK 1.86

This took me a bit to track down, but for some reason, after updating from CDK 1.80 to 1.86, my Stack started failing during synth with

Unable to determine ARN separator for SSM parameter since the parameter name is an unresolved token. Use "fromAttributes" and specify "simpleName" explicitly
Subprocess exited with error 1

I traced this to my usage of the SpaAuthorization construct inside a NestedStack like so:

export class CloudFrontAuthorizationStack extends NestedStack {
  constructor(scope: Construct, id: string, props: NestedStackProps) {
    super(scope, id, props);

    const userPool = new UserPool(this, 'UserPool', {
      selfSignUpEnabled: false,
      userPoolName: 'cloudfront-authorization-userpool',
    });

    // UserPool must have a domain!
    userPool.addDomain('Domain', {
      cognitoDomain: {
        domainPrefix: 'cloudcomponents',
      },
    });

    const authorization = new SpaAuthorization(this, 'Authorization', {
      userPool: userPool
    });
  }
}

If I change NestedStack to Stack, it starts working again. As mentioned, this used to work in CDK 1.80, and my preference is to continue using NestedStack.

StaticSiteAuthorization cannot exist in multiple stacks within same aws account

I have a situation where I'd like to have multiple stacks in the same account & region so multiple developers can have their own independent stack, however StaticSiteAuthorization appears to create a resource that does not generate a different id based on the id of the StaticSiteAuthorization which causes ownership conflicts.

Error:

File "/home/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 83, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/home/static_website/authenticated_site_stack.py", line 26, in __init__
    authorization = StaticSiteAuthorization(
  File "/home/.venv/lib/python3.8/site-packages/jsii/_runtime.py", line 83, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/home/.venv/lib/python3.8/site-packages/cloudcomponents/cdk_cloudfront_authorization/__init__.py", line 2290, in __init__
    jsii.create(StaticSiteAuthorization, self, [scope, id, props])
  File "/home/.venv/lib/python3.8/site-packages/jsii/_kernel/__init__.py", line 275, in create
    response = self.provider.create(
  File "/home/.venv/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 344, in create
    return self._process.send(request, CreateResponse)
  File "/home/.venv/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 326, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: There is already a Construct with name 'EdgeRole' in Stack [lambda-at-edge-support-stack]

Declaration of StaticSiteAuthorization where suffix and app_domain vary by stack

StaticSiteAuthorization(
            self,
            id="{}-static-auth".format(suffix),
            user_pool=user_pool,
            identity_providers=identity_providers,
            oauth_scopes=[aws_cognito.OAuthScope.EMAIL,
                          aws_cognito.OAuthScope.PROFILE,
                          aws_cognito.OAuthScope.OPENID],
            sign_out_url="https://{}/logout".format(app_domain),
        )

cloudfront-authorization failing to create at SecretGenerator lambda

I'm getting the following error while trying to deploy the cloudfront-authorization stack. It's failing while trying to create the secret-generator lambda function in CloudFormation, although it does compile it successfully locally. It's not clear what's causing the 'invalid parameter exception' error for this function. The other @edge lambda functions do compile and deploy correctly, but the whole stack fails to deploy due to this.

Screen Shot 2020-11-22 at 10 23 05 PM

Screen Shot 2020-11-22 at 10 22 09 PM

Screen Shot 2020-11-22 at 10 28 04 PM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.