Pulumi Amazon Web Services (AWS) Infrastructure Components
repository·master·Indexed 42 days ago
https://github.com/pulumi/pulumi-awsxHigh-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.
What's inside Pulumi AWSX
- 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.
Use Pulumi AWSX Components
masterPulumi 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.Create CloudWatch Dashboards from Metrics
masterVersion 0.18.2 introduced a workflow for creating CloudWatch Dashboards usingawsx.cloudwatch.Metricobjects. You can define metrics (e.g.,awsx.lambda.metrics.duration) and then use theawsx.cloudwatch.Dashboardhelper to visualize them.Create a Raw Data Route
masterUse a Raw Data Route when you need direct control over the Swagger/OpenAPI specification. The
datafield accepts an object that is merged into the final Swagger spec. This is useful for configuring advancedx-amazon-apigateway-integrationsettings.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", }, }, }], });Use Lambda Authorizers
masterLambda 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 arequesttype authorizer.awsx.apigateway.getTokenLambdaAuthorizer: Simplifies defining atokentype 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
roleusingnew 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); }, })], }], });Use Target Tracking scaling policies
masterTarget 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 passdisableScaleIn: trueto prevent the ASG from removing instances when usage drops. - Network Throughput: Use
scaleToTrackAverageNetworkInorscaleToTrackAverageNetworkOut. - Request Count per Target: Use
scaleToTrackRequestCountPerTarget. This requires the ASG to be associated with anawsx.lb.ApplicationTargetGroupwheretargetTypeis 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, });- CPU Utilization: Use
Configure Request Validation
masterAPI 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
nameand the location (in):path,query, orheader.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", });Configure NLB Listeners and Target Groups
masterOnce an NLB is created, you can manage traffic using
ListenersandTargetGroups.- Manual Creation: You can manually create a
TargetGroupusingnlb.createTargetGroup()and then create aListenerfrom that group usingtg.createListener(). - Automatic Creation: If you call
nlb.createListener()without specifying aTargetGroup, 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 anHTTPredirect.
// 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", }, }, });- Manual Creation: You can manually create a
How `Auto` strategy handles Gateway Endpoints
masterWhen
vpcEndpointStrategyis set to"Auto"and a spec hasvpcEndpointType: "Gateway"(or the type is omitted, as Gateway is the provider default), AWSX manages the route tables:- Route Tables: If
routeTableIdsis omitted, AWSX automatically selects all generated VPC route tables. This includes generatedPrivate,Isolated, andPublicroute 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.Vpccomponent. Ensure you do not have overlapping Gateway endpoint routes if mixing AWSX-managed and manually managed endpoints.- Route Tables: If
How CloudWatch Metrics work in Pulumi
masterMetrics 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.metricsprovides metrics specifically for Lambda functions.When working with metrics, you can typically specify:
period: The time period over which data is collected.statistic: The type of statistic to collect (e.g.,Average,Maximum).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" });Understand Pulumi AWS Infrastructure Components (awsx)
masterThe
@pulumi/awsxpackage 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 usingawsx.ec2.DefaultNetworkto 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 likelb.defaultTargetcan be passed directly into otherawsxcomponents (e.g., as aportMappingtarget forecs.FargateService).
Push an existing image to an ECR repository using RegistryImage
masterThe
awsx.ecr.RegistryImageresource manages the lifecycle of a Docker image in a registry by performing adocker pushoperation. Unlikeawsx.ecr.Image, which builds an image from source,RegistryImageis used to push an existing image (identified by a source tag) to an ECR repository. The image is pushed whenever thesourceImageproperty changes or is updated.To use this, you must provide the
repositoryUrlof the target ECR repository and thesourceImagestring (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", });