How to use the @aws-cdk/core.Duration.seconds function in @aws-cdk/core

To help you get started, we’ve selected a few @aws-cdk/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws-samples / amazon-cognito-example-for-external-idp / cdk / src / customResourceConstructs / cognitoDomainCustomResourceConstruct.ts View on Github external
constructor(scope: Construct, id: string, props: Omit<CreateUserPoolDomainRequest, "UserPoolId">,
              userPool: CfnUserPool | UserPool) {
    super(scope, id);

    this.node.addDependency(userPool);

    const userPoolArn = userPool instanceof CfnUserPool? userPool.attrArn : userPool.userPoolArn;
    const userPoolId = userPool instanceof CfnUserPool? userPool.ref : userPool.userPoolId;

    this.lambda = new lambda.SingletonFunction(this, "CognitoDomainCustomResource", {
      uuid: "090E4EFC-161E-4EBD-ADA2-72A7BE4A3120",
      code: Code.asset("./src/customResourceLambdas"),
      handler: "cognitoDomainCustomResourceHandler.handler",
      timeout: Duration.seconds(300),
      runtime: lambda.Runtime.NODEJS_10_X,

    });

    this.lambda.addToRolePolicy(
      // * is needed in case the user pool has changed, we may have more than one user pool this lambda needs to interact with
      new iam.PolicyStatement({actions: ["cognito-idp:*UserPoolDomain"], resources: [userPoolArn]})
    );
    this.lambda.addToRolePolicy(
      new iam.PolicyStatement({actions: ["cognito-idp:DescribeUserPoolDomain"], resources: ["*"]})
    );

    const resource = new cfn.CustomResource(this, "CognitoDomain", {
      provider: cfn.CustomResourceProvider.lambda(this.lambda),
      properties: {
        Props: {...props, UserPoolId: userPoolId}
github aws / aws-cdk / packages / @aws-cdk / aws-autoscaling / lib / auto-scaling-group.ts View on Github external
function renderRollingUpdateConfig(config: RollingUpdateConfiguration = {}): CfnAutoScalingRollingUpdate {
  const waitOnResourceSignals = config.minSuccessfulInstancesPercent !== undefined ? true : false;
  const pauseTime = config.pauseTime || (waitOnResourceSignals ? Duration.minutes(5) : Duration.seconds(0));

  return {
    maxBatchSize: config.maxBatchSize,
    minInstancesInService: config.minInstancesInService,
    minSuccessfulInstancesPercent: validatePercentage(config.minSuccessfulInstancesPercent),
    waitOnResourceSignals,
    pauseTime: pauseTime && pauseTime.toISOString(),
    suspendProcesses: config.suspendProcesses !== undefined ? config.suspendProcesses :
      // Recommended list of processes to suspend from here:
      // https://aws.amazon.com/premiumsupport/knowledge-center/auto-scaling-group-rolling-updates/
      [ScalingProcess.HEALTH_CHECK, ScalingProcess.REPLACE_UNHEALTHY, ScalingProcess.AZ_REBALANCE,
        ScalingProcess.ALARM_NOTIFICATION, ScalingProcess.SCHEDULED_ACTIONS],
  };
}
github aws-samples / amazon-cognito-example-for-external-idp / cdk / src / cdk.ts View on Github external
// ========================================================================
    // Resource: AWS Lambda Function - CRUD API Backend
    // ========================================================================

    // Purpose: serverless backend for the demo app, uses express.js

    // See also:
    // - https://aws.amazon.com/lambda/
    // - https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-readme.html

    const apiFunction = new lambda.Function(this, "APIFunction", {
      runtime: nodeRuntime,
      handler: "index.handler",
      code: lambda.Code.fromAsset("../lambda/api/dist/src"),
      timeout: Duration.seconds(30),
      memorySize: lambdaMemory,
      environment: {
        ITEMS_TABLE_NAME: itemsTable.tableName,
        USERS_TABLE_NAME: usersTable.tableName,
        ALLOWED_ORIGIN: corsOrigin,
        ADMINS_GROUP_NAME: adminsGroupName,
        USERS_GROUP_NAME: usersGroupName,
        USER_POOL_ID: userPoolCfn.ref,
        AUTHORIZATION_HEADER_NAME: authorizationHeaderName,
      },
    });

    // grant the lambda full access to the tables (for a high level construct, we have a syntactic sugar way of doing it
    itemsTable.grantReadWriteData(apiFunction.role!);
    usersTable.grantReadWriteData(apiFunction.role!);
github aws-samples / amazon-cognito-example-for-external-idp / cdk / src / customResourceConstructs / cognitoAppClientCustomResourceConstruct.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: Omit<CognitoAppClientCustomResourceParams, "UserPoolId">, userPool: CfnUserPool | UserPool) {
    super(scope, id);

    this.node.addDependency(userPool);

    const userPoolArn = userPool instanceof CfnUserPool? userPool.attrArn : userPool.userPoolArn;
    const userPoolId = userPool instanceof CfnUserPool? userPool.ref : userPool.userPoolId;

    this.lambda = new lambda.SingletonFunction(this, "CognitoAppClientCustomResource", {
      uuid: "EBAA2A90-1BE2-44B4-ADF1-C267F9CD910A",
      code: Code.asset("./src/customResourceLambdas"),
      handler: "cognitoAppClientCustomResourceHandler.handler",
      timeout: Duration.seconds(300),
      runtime: lambda.Runtime.NODEJS_10_X,

    });

    this.lambda.addToRolePolicy(new iam.PolicyStatement({
      actions: ["cognito-idp:*UserPoolClient*"],
      resources: ["*"] // needed in case the user pool has changed, we may have more than one
    }));


    const resource = new cfn.CustomResource(this, "CognitoAppClient", {
      provider: cfn.CustomResourceProvider.lambda(this.lambda),
      properties: {
        Props: {...props, UserPoolId: userPoolId}
      }
    });
github humank / EventStormingWorkShop / deployment / coffeeshop-cdk / lib / coffee-shop-code-pipeline.ts View on Github external
// if the default image is not from ECR, the ECS task execution role will not have ECR pull privileges
        // we need grant the pull for it explicitly
        this.ecrRepository.grantPull({
            grantPrincipal: (fargatesvc.service.taskDefinition.executionRole as iam.IRole)
        })

        // reduce the default deregistration delay timeout from 300 to 30 to accelerate the rolling update
        fargatesvc.targetGroup.setAttribute('deregistration_delay.timeout_seconds', '30')
        // customize the healthcheck to speed up the ecs rolling update
        fargatesvc.targetGroup.configureHealthCheck({
            interval: Duration.seconds(5),
            healthyHttpCodes: '200',
            healthyThresholdCount: 2,
            unhealthyThresholdCount: 3,
            timeout: Duration.seconds(4),
        })

        // CodePipeline
        const codePipeline = new codepipeline.Pipeline(this, 'CoffeeShopPipeline', {
            pipelineName: 'CoffeeShopPipeline',
        });

        const sourceOutputEcr = new codepipeline.Artifact();
        const sourceOutputCodeCommit = new codepipeline.Artifact();
        const sourceActionECR = new codepipeline_actions.EcrSourceAction({
            actionName: 'ECR',
            repository: this.ecrRepository,
            imageTag: 'latest', // optional, default: 'latest'
            output: sourceOutputEcr,
        });
github aws-samples / amazon-cognito-example-for-external-idp / cdk / src / customResourceConstructs / cognitoIdPCustomResourceConstruct.ts View on Github external
constructor(scope: Construct, id: string, props: Omit<CreateIdentityProviderRequest | CreateIdentityProviderRequestSAML, "UserPoolId">,
              userPool: CfnUserPool | UserPool) {
    super(scope, id);

    this.node.addDependency(userPool);

    const userPoolArn = userPool instanceof CfnUserPool? userPool.attrArn : userPool.userPoolArn;
    const userPoolId = userPool instanceof CfnUserPool? userPool.ref : userPool.userPoolId;

    this.lambda = new lambda.SingletonFunction(this, "CognitoIdPCustomResource", {
      uuid: "3C33B180-0D96-48BF-8A5E-6FD13B71511E",
      code: Code.asset("./src/customResourceLambdas"),
      handler: "cognitoIdPCustomResourceHandler.handler",
      timeout:  Duration.seconds(300),
      runtime: lambda.Runtime.NODEJS_10_X,

    });

    this.lambda.addToRolePolicy(new iam.PolicyStatement({
      actions: ["cognito-idp:*IdentityProvider*"],
      resources: [userPoolArn]
    }));

    const resource = new cfn.CustomResource(this, "CognitoIdP", {
      provider: cfn.CustomResourceProvider.lambda(this.lambda),
      properties: {
        Props: {...props, UserPoolId: userPoolId}
      }
    });
  }
github aws / aws-cdk / packages / @aws-cdk / custom-resources / lib / provider-framework / util.ts View on Github external
import * as sfn from '@aws-cdk/aws-stepfunctions';
import { Duration } from '@aws-cdk/core';

const DEFAULT_TIMEOUT = Duration.minutes(30);
const DEFAULT_INTERVAL = Duration.seconds(5);

export function calculateRetryPolicy(props: { totalTimeout?: Duration, queryInterval?: Duration } = { }): sfn.RetryProps {
  const totalTimeout = props.totalTimeout || DEFAULT_TIMEOUT;
  const interval = props.queryInterval || DEFAULT_INTERVAL;
  const maxAttempts = totalTimeout.toSeconds() / interval.toSeconds();

  if (Math.round(maxAttempts) !== maxAttempts) {
    throw new Error(`Cannot determine retry count since totalTimeout=${totalTimeout.toSeconds()}s is not integrally dividable by queryInterval=${interval.toSeconds()}s`);
  }

  return {
    maxAttempts,
    interval,
    backoffRate: 1
  };
}
github guardian / editions / projects / aws / lib / aws-stack.ts View on Github external
const backendURL = `${publishedGatewayId}.execute-api.eu-west-1.amazonaws.com/prod/` //Yes, this (the region) really should not be hard coded.

        const dist = new cloudfront.CloudFrontWebDistribution(
            this,
            'backend-cloudfront-distribution',
            {
                comment: `Cloudfront distribution for editions ${stageParameter.valueAsString}`,
                defaultRootObject: '',
                originConfigs: [
                    {
                        originPath: '/prod', //This is hard coded and could be the deployment id
                        behaviors: [
                            {
                                isDefaultBehavior: true,
                                defaultTtl: Duration.seconds(10),
                            },
                        ],
                        customOriginSource: {
                            domainName: `${gatewayId}.execute-api.eu-west-1.amazonaws.com`, //Yes, this (the region) really should not be hard coded.
                        },
                    },
                ],
            },
        )
        new CfnOutput(this, 'Cloudfront-distribution', {
            description: 'URL for distribution',
            value: `https://${dist.domainName}`,
        })

        const archive = s3.Bucket.fromBucketName(
            this,