How to use the @aws-cdk/aws-lambda.Runtime function in @aws-cdk/aws-lambda

To help you get started, we’ve selected a few @aws-cdk/aws-lambda 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 / aws-cdk / packages / @aws-cdk / aws-s3-deployment / lib / bucket-deployment.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: BucketDeploymentProps) {
    super(scope, id);

    if (props.distributionPaths && !props.distribution) {
      throw new Error("Distribution must be specified if distribution paths are specified");
    }

    const sourceHash = calcSourceHash(handlerSourceDirectory);
    // tslint:disable-next-line: no-console
    console.error({sourceHash});

    const handler = new lambda.SingletonFunction(this, 'CustomResourceHandler', {
      uuid: this.renderSingletonUuid(props.memoryLimit),
      code: lambda.Code.fromAsset(handlerCodeBundle, { sourceHash }),
      runtime: lambda.Runtime.PYTHON_3_6,
      handler: 'index.handler',
      lambdaPurpose: 'Custom::CDKBucketDeployment',
      timeout: cdk.Duration.minutes(15),
      role: props.role,
      memorySize: props.memoryLimit
    });

    const sources: SourceConfig[] = props.sources.map((source: ISource) => source.bind(this));
    sources.forEach(source => source.bucket.grantRead(handler));

    props.destinationBucket.grantReadWrite(handler);
    if (props.distribution) {
      handler.addToRolePolicy(new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ['cloudfront:GetInvalidation', 'cloudfront:CreateInvalidation'],
        resources: ['*'],
github aws / aws-cdk / packages / @aws-cdk / aws-eks / lib / helm-chart.ts View on Github external
private getOrCreateHelmChartHandler(cluster: Cluster): lambda.IFunction | undefined {
    if (!cluster.kubectlEnabled) {
      return undefined;
    }

    let handler = cluster.node.tryFindChild('HelmChartHandler') as lambda.IFunction;
    if (!handler) {
      handler = new lambda.Function(cluster, 'HelmChartHandler', {
        code: lambda.Code.fromAsset(path.join(__dirname, 'helm-chart')),
        runtime: lambda.Runtime.PYTHON_3_7,
        handler: 'index.handler',
        timeout: Duration.minutes(15),
        layers: [ KubectlLayer.getOrCreate(this, { version: "2.0.0-beta1" }) ],
        memorySize: 256,
        environment: {
          CLUSTER_NAME: cluster.clusterName,
        },

        // NOTE: we must use the default IAM role that's mapped to "system:masters"
        // as the execution role of this custom resource handler. This is the only
        // way to be able to interact with the cluster after it's been created.
        role: cluster._defaultMastersRole,
      });
    }
    return handler;
  }
github aws / aws-cdk / packages / @aws-cdk / aws-stepfunctions-tasks / lib / evaluate-expression.ts View on Github external
function createEvalFn(runtime: lambda.Runtime, scope: cdk.Construct) {
  const code = lambda.Code.asset(path.join(__dirname, `eval-${runtime.name}-handler`));
  const lambdaPurpose = 'Eval';

  switch (runtime) {
    case lambda.Runtime.NODEJS_10_X:
      return new lambda.SingletonFunction(scope, 'EvalFunction', {
        runtime,
        handler: 'index.handler',
        uuid: 'a0d2ce44-871b-4e74-87a1-f5e63d7c3bdc',
        lambdaPurpose,
        code,
      });
    // TODO: implement other runtimes
    default:
      throw new Error(`The runtime ${runtime.name} is currently not supported.`);
  }
}
github aws / aws-cdk / packages / @aws-cdk / aws-eks / lib / cluster-resource.ts View on Github external
constructor(scope: Construct, id: string, props: CfnClusterProps) {
    super(scope, id);

    // each cluster resource will have it's own lambda handler since permissions
    // are scoped to this cluster and related resources like it's role
    const handler = new lambda.Function(this, 'ResourceHandler', {
      code: lambda.Code.fromAsset(path.join(__dirname, 'cluster-resource')),
      runtime: lambda.Runtime.PYTHON_3_7,
      handler: 'index.handler',
      timeout: Duration.minutes(15),
      memorySize: 512,
      layers: [ KubectlLayer.getOrCreate(this) ],
    });

    if (!props.roleArn) {
      throw new Error(`"roleArn" is required`);
    }

    // since we don't know the cluster name at this point, we must give this role star resource permissions
    handler.addToRolePolicy(new iam.PolicyStatement({
      actions: [ 'eks:CreateCluster', 'eks:DescribeCluster', 'eks:DeleteCluster', 'eks:UpdateClusterVersion' ],
      resources: [ '*' ]
    }));
github aws / aws-cdk / packages / @aws-cdk / aws-certificatemanager / lib / dns-validated-certificate.ts View on Github external
super(scope, id);

        this.domainName = props.domainName;
        this.normalizedZoneName = props.hostedZone.zoneName;
        // Remove trailing `.` from zone name
        if (this.normalizedZoneName.endsWith('.')) {
            this.normalizedZoneName = this.normalizedZoneName.substring(0, this.normalizedZoneName.length - 1);
        }

        // Remove any `/hostedzone/` prefix from the Hosted Zone ID
        this.hostedZoneId = props.hostedZone.hostedZoneId.replace(/^\/hostedzone\//, '');

        const requestorFunction = new lambda.Function(this, 'CertificateRequestorFunction', {
            code: lambda.Code.fromAsset(path.resolve(__dirname, '..', 'lambda-packages', 'dns_validated_certificate_handler', 'lib')),
            handler: 'index.certificateRequestHandler',
            runtime: lambda.Runtime.NODEJS_10_X,
            timeout: cdk.Duration.minutes(15),
            role: props.customResourceRole
        });
        requestorFunction.addToRolePolicy(new iam.PolicyStatement({
            actions: ['acm:RequestCertificate', 'acm:DescribeCertificate', 'acm:DeleteCertificate'],
            resources: ['*'],
        }));
        requestorFunction.addToRolePolicy(new iam.PolicyStatement({
            actions: ['route53:GetChange'],
            resources: ['*'],
        }));
        requestorFunction.addToRolePolicy(new iam.PolicyStatement({
            actions: ['route53:changeResourceRecordSets'],
            resources: [`arn:aws:route53:::hostedzone/${this.hostedZoneId}`],
        }));
github duo-labs / cloudtrail-partitioner / lib / cloudtrail_partitioner-stack.js View on Github external
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
      alarmDescription: "Detect errors",
      alarmName: "cloudtrail_partitioner_errors"
    });

    // Create SNS for alarms to be sent to
    const sns_topic = new sns.Topic(this, 'cloudtrail_partitioner_alarm', {
      displayName: 'cloudtrail_partitioner_alarm'
    });

    // Connect the alarm to the SNS
    error_alarm.addAlarmAction(new cloudwatch_actions.SnsAction(sns_topic));

    // Create Lambda to forward alarms
    const alarm_forwarder = new lambda.Function(this, "alarm_forwarder", {
      runtime: lambda.Runtime.PYTHON_3_7,
      code: lambda.Code.asset("resources/alarm_forwarder"),
      handler: "main.handler",
      description: "Forwards alarms from the local SNS to another",
      logRetention: logs.RetentionDays.TWO_WEEKS,
      timeout: cdk.Duration.seconds(30),
      memorySize: 128,
      environment: {
        "ALARM_SNS": config['alarm_sns_arn']
      },
    });

    // Add priv to publish the events so the alarms can be forwarded
    alarm_forwarder.addToRolePolicy(new iam.PolicyStatement({
      resources: [config['alarm_sns_arn']],
      actions: ['sns:Publish']
    }));
github aws / aws-cdk / packages / @aws-cdk / aws-ecs / lib / drain-hook / instance-drain-hook.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: InstanceDrainHookProps) {
    super(scope, id);

    const drainTime = props.drainTime || cdk.Duration.minutes(5);

    // Invoke Lambda via SNS Topic
    const fn = new lambda.Function(this, 'Function', {
      code: lambda.Code.fromInline(fs.readFileSync(path.join(__dirname, 'lambda-source', 'index.py'), { encoding: 'utf-8' })),
      handler: 'index.lambda_handler',
      runtime: lambda.Runtime.PYTHON_3_6,
      // Timeout: some extra margin for additional API calls made by the Lambda,
      // up to a maximum of 15 minutes.
      timeout: cdk.Duration.seconds(Math.min(drainTime.toSeconds() + 10, 900)),
      environment: {
        CLUSTER: props.cluster.clusterName
      }
    });

    // Hook everything up: ASG -> Topic, Topic -> Lambda
    props.autoScalingGroup.addLifecycleHook('DrainHook', {
      lifecycleTransition: autoscaling.LifecycleTransition.INSTANCE_TERMINATING,
      defaultResult: autoscaling.DefaultResult.CONTINUE,
      notificationTarget: new hooks.FunctionHook(fn),
      heartbeatTimeout: drainTime,
    });
github seagull-js / seagull / packages / deploy / src / cdk_stack.ts View on Github external
private addLambda() {
    const name = `${this.appName}-lambda`
    const code = lambda.Code.asset(`${this.folder}/.seagull/deploy`)
    const description = 'universal route'
    const functionName = `${name}-handler`
    const handler = 'dist/assets/backend/lambda.handler'
    const runtime = lambda.Runtime.NodeJS810
    const timeout = 300
    const conf = { code, description, functionName, handler, runtime, timeout }

    const lambdaFunction = new lambda.Function(this, name, conf)
    this.defaultIntegration = new api.LambdaIntegration(lambdaFunction)
  }
github aws / aws-cdk / packages / @aws-cdk / custom-resources / lib / provider-framework / provider.ts View on Github external
private createFunction(entrypoint: string) {
    const fn = new lambda.Function(this, `framework-${entrypoint}`, {
      code: lambda.Code.fromAsset(RUNTIME_HANDLER_PATH),
      runtime: lambda.Runtime.NODEJS_10_X,
      handler: `framework.${entrypoint}`,
      timeout: FRAMEWORK_HANDLER_TIMEOUT,
    });

    fn.addEnvironment(consts.USER_ON_EVENT_FUNCTION_ARN_ENV, this.onEventHandler.functionArn);
    this.onEventHandler.grantInvoke(fn);

    if (this.isCompleteHandler) {
      fn.addEnvironment(consts.USER_IS_COMPLETE_FUNCTION_ARN_ENV, this.isCompleteHandler.functionArn);
      this.isCompleteHandler.grantInvoke(fn);
    }

    return fn;
  }
github guardian / editions / projects / aws / lib / constructs.ts View on Github external
name: string,
    {
        stack,
        stage,
        deployBucket,
        outputBucket,
        frontsTopicArn,
        frontsTopicRole,
    }: Params,
    environment?: { [key: string]: string },
    overrides?: Partial,
) => {
    const lambdaName = `EditionsArchiver${toTitleCase(name)}`
    const fn = new lambda.Function(scope, lambdaName, {
        functionName: `editions-archiver-stepmachine-${name}-${stage}`,
        runtime: lambda.Runtime.NODEJS_10_X,
        timeout: Duration.minutes(5),
        memorySize: 1500,
        code: Code.bucket(
            deployBucket,
            `${stack}/${stage}/archiver/archiver.zip`,
        ),
        handler: `index.${name}`,
        environment: {
            ...environment,
            stage: stage,
            bucket: outputBucket.bucketName,
            topic: frontsTopicArn,
            role: frontsTopicRole.roleArn,
        },
        initialPolicy: [
            new iam.PolicyStatement({