Pulumi Amazon Web Services (AWS) Infrastructure Components

repository·master·Indexed 42 days ago

https://github.com/pulumi/pulumi-awsx

High-level, opinionated component wrappers around core AWS resources designed to reduce boilerplate and implement best practices for common patterns. Includes tools for API Gateway endpoints, ECS AutoScalingGroups, and CloudWatch metrics, alarms, and dashboards.

Tokens
49.3K
Snippets
112
Records
218
Agent score
48%

What's inside Pulumi AWSX

  1. Overview of Pulumi AWSX Components

    master
    Pulumi AWSX provides high-level, opinionated infrastructure components for Amazon Web Services (AWS). These components are designed to simplify the creation of complex AWS architectures by providing sensible defaults and reducing the amount of boilerplate code required compared to using the standard AWS provider.
  2. Use Pulumi AWSX Components

    master
    Pulumi AWSX provides high-level, opinionated components for Amazon Web Services (AWS). These components simplify the creation of complex infrastructure by providing sensible defaults and reducing the amount of boilerplate code required to deploy common AWS patterns.
  3. Create CloudWatch Dashboards from Metrics

    master
    Version 0.18.2 introduced a workflow for creating CloudWatch Dashboards using awsx.cloudwatch.Metric objects. You can define metrics (e.g., awsx.lambda.metrics.duration) and then use the awsx.cloudwatch.Dashboard helper to visualize them.
  4. Create a Raw Data Route

    master

    Use a Raw Data Route when you need direct control over the Swagger/OpenAPI specification. The data field accepts an object that is merged into the final Swagger spec. This is useful for configuring advanced x-amazon-apigateway-integration settings.

    import * as awsx from "@pulumi/awsx";
    
    let endpoint = new awsx.apigateway.API("example", {
        routes: [{
            path: "/rawdata",
            method: "GET",
            data: {
                "x-amazon-apigateway-integration": {
                    "uri": "https://www.google.com/",
                    "responses": {
                        "default": {
                            "statusCode": "200",
                        },
                    },
                    "passthroughBehavior": "when_no_match",
                    "httpMethod": "GET",
                    "type": "http_proxy",
                },
            },
        }],
    });
  5. Use Lambda Authorizers

    master

    Lambda Authorizers provide access control. API Gateway supports two types:

    • token: Uses an authorization token (e.g., Authorization: Token <token>).
    • request: Uses request parameters (headers, path, or query parameters).

    Helper Functions:

    • awsx.apigateway.getRequestLambdaAuthorizer: Simplifies defining a request type authorizer.
    • awsx.apigateway.getTokenLambdaAuthorizer: Simplifies defining a token type authorizer.
    • awsx.apigateway.authorizerResponse: A helper to generate the required authorizer response object.

    Customizing Roles: If the authorizer needs access to other AWS resources, provide a custom role using new aws.lambda.CallbackFunction.

    import * as awsx from "@pulumi/awsx";
    
    // Example: Request Authorizer
    const api = new awsx.apigateway.API("myapi", {
        routes: [{
            path: "/b",
            method: "GET",
            eventHandler: async () => { return { statusCode: 200, body: "ok" }; },
            authorizers: [awsx.apigateway.getRequestLambdaAuthorizer({
                queryParameters: ["auth"],
                handler: async (event: awsx.apigateway.AuthorizerEvent) => {
                    return awsx.apigateway.authorizerResponse("user", "Allow", event.methodArn);
                },
            })],
        }],
    });
  6. Use Target Tracking scaling policies

    master

    Target tracking scaling policies automatically adjust capacity to keep a specific metric at a target value. AWS manages the CloudWatch alarms and scaling adjustments for you.

    Predefined Metrics

    • CPU Utilization: Use scaleToTrackAverageCPUUtilization. You can pass disableScaleIn: true to prevent the ASG from removing instances when usage drops.
    • Network Throughput: Use scaleToTrackAverageNetworkIn or scaleToTrackAverageNetworkOut.
    • Request Count per Target: Use scaleToTrackRequestCountPerTarget. This requires the ASG to be associated with an awsx.lb.ApplicationTargetGroup where targetType is set to "instance".
    // Scaling based on CPU
    autoScalingGroup.scaleToTrackAverageCPUUtilization("keepAround50Percent", {
        targetValue: 50,
    });
    
    // Scaling based on Request Count per Target
    const targetGroup = loadBalancer.createTargetGroup("testing", { port: 80, targetType: "instance" });
    const autoScalingGroup = cluster.createAutoScalingGroup("testing", {
        targetGroups: [targetGroup],
        // ...
    });
    
    autoScalingGroup.scaleToTrackRequestCountPerTarget("onHighRequest", {
        targetValue: 1000,
        targetGroup: targetGroup,
    });
  7. Configure Request Validation

    master

    API Gateway can validate request parameters or the request body. If validation fails, a 400 error is returned.

    Validators can be set at the API level or the method level (method level overrides API level). Valid values are:

    • ALL: Validates both body and parameters.
    • BODY_ONLY: Validates only the request body.
    • PARAMS_ONLY: Validates only the request parameters.

    Required Parameters must specify a name and the location (in): path, query, or header.

    Note: Request body validation is currently not supported.

    import * as awsx from "@pulumi/awsx";
    
    let endpoint = new awsx.apigateway.API("example", {
        routes: [{
            path: "/www",
            localPath: "www",
            index: false,
            requestValidator: "PARAMS_ONLY",
            requiredParams: [{
                name: "key",
                in: "query",
            }]
        }],
        requestValidator: "ALL",
    });
  8. Configure NLB Listeners and Target Groups

    master

    Once an NLB is created, you can manage traffic using Listeners and TargetGroups.

    • Manual Creation: You can manually create a TargetGroup using nlb.createTargetGroup() and then create a Listener from that group using tg.createListener().
    • Automatic Creation: If you call nlb.createListener() without specifying a TargetGroup, a new one will be automatically created, and both will share the same port.
    • Custom Default Actions: By default, listeners forward requests to their associated target group. You can override this by providing a defaultAction. For example, you can configure a listener to perform an HTTP redirect.
    // continuing from above. Manually create the target group and the listener.
    const tg1 = nlb1.createTargetGroup("tg1", { port: 8080 });
    const listener1 = tg1.createListener("listener1", { port: 80 });
    
    // or, create a listener and have the target group automatically created.
    const listener2 = nlb1.createListener("listener2", { port: 80 });
    
    // Customizing the default action (e.g., redirecting HTTP to HTTPS)
    const listener3 = nlb1.createListener(`redirecthttp`, {
        port: 80,
        protocol: "HTTP",
        defaultAction: {
            type: "redirect",
            redirect: {
                protocol: "HTTPS",
                port: "443",
                statusCode: "HTTP_301",
            },
        },
    });
  9. How `Auto` strategy handles Gateway Endpoints

    master

    When vpcEndpointStrategy is set to "Auto" and a spec has vpcEndpointType: "Gateway" (or the type is omitted, as Gateway is the provider default), AWSX manages the route tables:

    • Route Tables: If routeTableIds is omitted, AWSX automatically selects all generated VPC route tables. This includes generated Private, Isolated, and Public route tables.
    • Preservation: If you provide explicit routeTableIds, AWSX will preserve those values and not perform automatic selection.

    Caution: AWSX does not deduplicate routes against endpoints managed outside of the awsx.ec2.Vpc component. Ensure you do not have overlapping Gateway endpoint routes if mixing AWSX-managed and manually managed endpoints.

  10. How CloudWatch Metrics work in Pulumi

    master

    Metrics are the fundamental building blocks in CloudWatch, representing time-ordered data points for a specific variable (e.g., CPU usage).

    In awsx, metrics are often provided as predefined submodules tied to specific AWS resources. For example, awsx.lambda.metrics provides metrics specifically for Lambda functions.

    When working with metrics, you can typically specify:

    1. period: The time period over which data is collected.
    2. statistic: The type of statistic to collect (e.g., Average, Maximum).
    3. unit: The unit of measure (e.g., Seconds, Megabytes/Second).

    Note: Not all metrics support all statistics or units; check the specific metric documentation for supported values.

    const func = new aws.lambda.CallbackFunction(...);
    const funcMetric = awsx.lambda.metrics.duration({ function: func, unit: "Seconds" });
  11. Understand Pulumi AWS Infrastructure Components (awsx)

    master

    The @pulumi/awsx package provides high-level component wrappers around core AWS 'raw' resources from @pulumi/aws. These components reduce boilerplate and follow AWS best practices by default while still exposing underlying functionality.

    Key modules include:

    • ec2: Simplifies working with networks, subnets, and security groups. A common pattern is using awsx.ec2.DefaultNetwork to acquire a default VPC for a region.
    • ecs: Simplifies creating and configuring clusters, tasks, and services for containerized workloads (EC2 or Fargate).
    • lb: Simplifies setting up Elastic Load Balancing (Network or Application load balancers) with associated Target Groups and Listeners. Components like lb.defaultTarget can be passed directly into other awsx components (e.g., as a portMapping target for ecs.FargateService).
  12. Push an existing image to an ECR repository using RegistryImage

    master

    The awsx.ecr.RegistryImage resource manages the lifecycle of a Docker image in a registry by performing a docker push operation. Unlike awsx.ecr.Image, which builds an image from source, RegistryImage is used to push an existing image (identified by a source tag) to an ECR repository. The image is pushed whenever the sourceImage property changes or is updated.

    To use this, you must provide the repositoryUrl of the target ECR repository and the sourceImage string (e.g., name:tag).

    import * as pulumi from "@pulumi/pulumi";
    import * as awsx from "@pulumi/awsx";
    
    const repository = new awsx.ecr.Repository("repository", { forceDelete: true });
    
    const preTaggedImage = new awsx.ecr.RegistryImage("registry-image", {
      repositoryUrl: repository.url,
      sourceImage: "my-awesome-image:v1.0.0",
    });