How to use the @aws-cdk/aws-lambda.Code 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'],
github aws / aws-cdk / packages / @aws-cdk / aws-certificatemanager / lib / dns-validated-certificate.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: DnsValidatedCertificateProps) {
        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 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-eks-legacy / lib / cluster.ts View on Github external
private createKubernetesResourceHandler() {
    if (!this.kubectlEnabled) {
      return undefined;
    }

    return new lambda.Function(this, 'KubernetesResourceHandler', {
      code: lambda.Code.fromAsset(path.join(__dirname, 'k8s-resource')),
      runtime: lambda.Runtime.PYTHON_3_7,
      handler: 'index.handler',
      timeout: Duration.minutes(15),
      layers: [ KubectlLayer.getOrCreate(this) ],
      memorySize: 256,
      environment: {
        CLUSTER_NAME: this.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: this._defaultMastersRole,
    });
  }
github duo-labs / cloudtrail-partitioner / lib / cloudtrail_partitioner-stack.js View on Github external
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-samples / aws-cdk-changelogs-demo / changelogs-md.js View on Github external
constructor(parent, id, props) {
    super(parent, id, props);

    // Copy the static files into the static S3 bucket
    this.s3Deployment = new s3Deployment.BucketDeployment(this, 'deploy-web', {
      source: s3Deployment.Source.asset('./static'),
      destinationBucket: props.staticBucket,
    });

    // Create a lambda that regenerates the homepage
    const regenerateHomepage = new lambda.Function(this, 'regenerate-homepage', {
      runtime: lambda.Runtime.NODEJS_10_X,
      handler: 'regenerate-homepage.handle',
      code: lambda.Code.asset('./app/regenerate-homepage'),
      environment: {
        CHANGELOGS_TABLE_NAME: props.changelogsTable.tableName,
        FEEDS_TABLE_NAME: props.feedsTable.tableName,
        WEB_BUCKET_NAME: props.webBucket.bucketName
      }
    });

    // Grant the lambda permission to read the tables
    props.feedsTable.grantReadData(regenerateHomepage.role);
    props.changelogsTable.grantReadData(regenerateHomepage.role);
    props.webBucket.grantReadWrite(regenerateHomepage.role);

    // Schedule this lambda to run once a minute
    this.eventRule = new events.Rule(this, 'homepage-regeneration-schedule', {
      schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
      targets: [
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 deepalert / deepalert / test / workflow / bin / stack.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: properties) {
    super(scope, id, props);

    const table = new dynamodb.Table(this, "resultTable", {
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
      sortKey: { name: "sk", type: dynamodb.AttributeType.STRING },
    });

    const buildPath = lambda.Code.fromAsset("./build");

    const testInspector = new lambda.Function(this, "testInspector", {
      runtime: lambda.Runtime.GO_1_X,
      handler: "inspector",
      timeout: cdk.Duration.seconds(30),
      code: buildPath,
      events: [new SnsEventSource(props.deepalert.taskTopic)],
      environment: {
        RESULT_TABLE: table.tableName,
        FINDING_QUEUE: props.deepalert.findingQueue.queueUrl,
        ATTRIBUTE_QUEUE: props.deepalert.attributeQueue.queueUrl,
      },
    });

    const testEmitter = new lambda.Function(this, "testEmitter", {
      runtime: lambda.Runtime.GO_1_X,
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 / aws-eks / lib / cluster-resource-provider.ts View on Github external
private constructor(scope: Construct, id: string) {
    super(scope, id);

    const onEvent = new lambda.Function(this, 'OnEventHandler', {
      code: lambda.Code.fromAsset(HANDLER_DIR),
      description: 'onEvent handler for EKS cluster resource provider',
      runtime: HANDLER_RUNTIME,
      handler: 'index.onEvent',
      timeout: Duration.minutes(1)
    });

    const isComplete = new lambda.Function(this, 'IsCompleteHandler', {
      code: lambda.Code.fromAsset(HANDLER_DIR),
      description: 'isComplete handler for EKS cluster resource provider',
      runtime: HANDLER_RUNTIME,
      handler: 'index.isComplete',
      timeout: Duration.minutes(1)
    });

    this.provider = new cr.Provider(this, 'Provider', {
      onEventHandler: onEvent,