CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pulumi--aws

A Pulumi package for creating and managing Amazon Web Services (AWS) cloud resources with infrastructure-as-code.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

functions.mddocs/core/

Top-Level Utility Functions

Global utility functions available directly from the @pulumi/aws package for common AWS operations.

Common Tasks

Quick examples for the most frequent utility function scenarios:

// Get current AWS account information
const caller = await aws.getCallerIdentity();
console.log(`Account: ${caller.accountId}`);

// List available availability zones
const azs = await aws.getAvailabilityZones({ state: "available" });
const subnets = azs.names.map((az, i) =>
    new aws.ec2.Subnet(`subnet-${i}`, {
        vpcId: vpc.id,
        availabilityZone: az,
        cidrBlock: `10.0.${i}.0/24`,
    })
);

// Parse ARN components
const arnInfo = await aws.getArn({ arn: "arn:aws:s3:::my-bucket/my-key" });
console.log(`Service: ${arnInfo.service}, Resource: ${arnInfo.resource}`);

// Get service principal for IAM policies
const lambdaPrincipal = await aws.getServicePrincipal({ serviceName: "lambda" });

Capabilities

ARN Parsing

Parse and validate Amazon Resource Names (ARNs).

/**
 * Parse an ARN string into its components
 * @param args.arn - The ARN string to parse
 * @returns Parsed ARN components
 */
function getArn(args: GetArnArgs): Promise<GetArnResult>;

interface GetArnArgs {
    arn: string;
}

interface GetArnResult {
    partition: string;
    service: string;
    region: string;
    accountId: string;
    resource: string;
}

Usage Example:

import * as aws from "@pulumi/aws";

const arnInfo = await aws.getArn({
    arn: "arn:aws:s3:::my-bucket/my-key",
});

console.log(arnInfo.service);    // "s3"
console.log(arnInfo.resource);   // "my-bucket/my-key"

When to Use:

  • Extracting service name from an ARN
  • Validating ARN format
  • Getting account ID from resource ARN
  • Parsing resource identifiers
// Extract bucket name from S3 ARN
const bucketArn = "arn:aws:s3:::my-bucket";
const arnInfo = await aws.getArn({ arn: bucketArn });
const bucketName = arnInfo.resource;

// Verify resource is in correct account
const resourceArn = "arn:aws:ec2:us-west-2:123456789012:instance/i-1234567890abcdef0";
const arnInfo = await aws.getArn({ arn: resourceArn });
if (arnInfo.accountId !== expectedAccountId) {
    throw new Error("Resource in wrong account");
}

Availability Zone Information

Get information about AWS availability zones.

/**
 * Get information about a specific availability zone
 * @param args.name - The name of the availability zone
 * @param args.zoneId - The ID of the availability zone
 * @returns Availability zone details
 */
function getAvailabilityZone(args: GetAvailabilityZoneArgs): Promise<GetAvailabilityZoneResult>;

/**
 * List all availability zones in the region
 * @param args.state - Filter by state (e.g., "available")
 * @param args.filters - Additional filters
 * @returns List of availability zones
 */
function getAvailabilityZones(args?: GetAvailabilityZonesArgs): Promise<GetAvailabilityZonesResult>;

interface GetAvailabilityZoneArgs {
    name?: string;
    zoneId?: string;
}

interface GetAvailabilityZoneResult {
    name: string;
    zoneId: string;
    state: string;
    region: string;
    groupName: string;
    networkBorderGroup: string;
}

interface GetAvailabilityZonesArgs {
    allAvailabilityZones?: boolean;
    state?: string;
    filters?: { name: string; values: string[] }[];
    excludeNames?: string[];
    excludeZoneIds?: string[];
}

interface GetAvailabilityZonesResult {
    names: string[];
    zoneIds: string[];
    groupNames: string[];
}

Usage Example:

const azs = await aws.getAvailabilityZones({
    state: "available",
});

// Use in resource creation
const subnets = azs.names.map((az, i) =>
    new aws.ec2.Subnet(`subnet-${i}`, {
        vpcId: vpc.id,
        availabilityZone: az,
        cidrBlock: `10.0.${i}.0/24`,
    })
);

When to Use:

  • Creating multi-AZ deployments
  • Distributing resources across availability zones
  • Validating AZ availability
// Create RDS instance with multi-AZ
const azs = await aws.getAvailabilityZones({ state: "available" });
const dbSubnetGroup = new aws.rds.SubnetGroup("db-subnet", {
    subnetIds: azs.names.slice(0, 2).map((az, i) =>
        new aws.ec2.Subnet(`db-subnet-${i}`, {
            vpcId: vpc.id,
            availabilityZone: az,
            cidrBlock: `10.0.${i + 10}.0/24`,
        }).id
    ),
});

// Exclude specific AZs
const filteredAzs = await aws.getAvailabilityZones({
    state: "available",
    excludeNames: ["us-east-1e"], // Known problematic AZ
});

Caller Identity

Get information about the AWS account and caller.

/**
 * Get details about the current AWS account and caller
 * @returns Account ID, ARN, and user ID
 */
function getCallerIdentity(): Promise<GetCallerIdentityResult>;

interface GetCallerIdentityResult {
    accountId: string;
    arn: string;
    userId: string;
}

Usage Example:

const caller = await aws.getCallerIdentity();

console.log(`Account ID: ${caller.accountId}`);
console.log(`ARN: ${caller.arn}`);
console.log(`User ID: ${caller.userId}`);

// Use in resource policies
const policy = pulumi.interpolate`{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Principal": {"AWS": "${caller.arn}"},
        "Action": "s3:GetObject",
        "Resource": "*"
    }]
}`;

When to Use:

  • Verifying you're in the correct AWS account
  • Building account-specific ARNs
  • Creating IAM policies with current user/role
  • Account validation in CI/CD
// Validate deployment account
const caller = await aws.getCallerIdentity();
const expectedAccount = pulumi.getStack() === "prod" ? "123456789012" : "987654321098";
if (caller.accountId !== expectedAccount) {
    throw new Error(`Wrong account! Expected ${expectedAccount}, got ${caller.accountId}`);
}

// Create bucket policy allowing current account
const bucket = new aws.s3.BucketV2("my-bucket");
const bucketPolicy = new aws.s3.BucketPolicy("bucket-policy", {
    bucket: bucket.id,
    policy: pulumi.all([bucket.arn, caller.accountId]).apply(([arn, accountId]) =>
        JSON.stringify({
            Version: "2012-10-17",
            Statement: [{
                Effect: "Allow",
                Principal: { AWS: `arn:aws:iam::${accountId}:root` },
                Action: "s3:GetObject",
                Resource: `${arn}/*`,
            }],
        })
    ),
});

Region Information

Get information about AWS regions.

/**
 * Get information about the current region
 * @param args.name - Specific region name
 * @param args.endpoint - Specific endpoint name
 * @returns Region details
 */
function getRegion(args?: GetRegionArgs): Promise<GetRegionResult>;

/**
 * List all available AWS regions
 * @param args.filters - Filter regions
 * @returns List of region names and endpoints
 */
function getRegions(args?: GetRegionsArgs): Promise<GetRegionsResult>;

interface GetRegionArgs {
    name?: string;
    endpoint?: string;
}

interface GetRegionResult {
    name: string;
    description: string;
    endpoint: string;
}

interface GetRegionsArgs {
    allRegions?: boolean;
    filters?: { name: string; values: string[] }[];
}

interface GetRegionsResult {
    names: string[];
}

Usage Example:

const currentRegion = await aws.getRegion();
console.log(`Current region: ${currentRegion.name}`);

const allRegions = await aws.getRegions();
console.log(`Available regions: ${allRegions.names.join(", ")}`);

When to Use:

  • Multi-region deployments
  • Region-specific configuration
  • Validating region availability
// Deploy to multiple regions
const regions = await aws.getRegions();
const regionalBuckets = regions.names.slice(0, 3).map(region => {
    const provider = new aws.Provider(`provider-${region}`, { region });
    return new aws.s3.BucketV2(`bucket-${region}`, {}, { provider });
});

// Get current region for naming
const region = await aws.getRegion();
const bucket = new aws.s3.BucketV2(`app-${region.name}-data`);

Partition Information

Get the AWS partition (aws, aws-cn, aws-us-gov).

/**
 * Get the AWS partition for the current region
 * @returns Partition name
 */
function getPartition(): Promise<GetPartitionResult>;

interface GetPartitionResult {
    partition: string;
    dnsSuffix: string;
}

Usage Example:

const partition = await aws.getPartition();

// Build ARNs correctly for different partitions
const arn = `arn:${partition.partition}:s3:::my-bucket`;

When to Use:

  • Building ARNs programmatically
  • Supporting AWS China or GovCloud
  • Cross-partition validation
// Create partition-aware ARNs
const partition = await aws.getPartition();
const caller = await aws.getCallerIdentity();
const roleArn = `arn:${partition.partition}:iam::${caller.accountId}:role/MyRole`;

// Partition-specific logic
if (partition.partition === "aws-cn") {
    // Special handling for AWS China
    console.log("Deploying to AWS China");
}

Billing Service Account

Get the AWS billing service account ID for a region.

/**
 * Get the AWS billing service account ID
 * @param args.region - AWS region
 * @returns Account ID
 */
function getBillingServiceAccount(args?: GetBillingServiceAccountArgs): Promise<GetBillingServiceAccountResult>;

interface GetBillingServiceAccountArgs {
    region?: string;
}

interface GetBillingServiceAccountResult {
    id: string;
    arn: string;
}

When to Use:

  • Setting up S3 bucket policies for billing logs
  • Configuring billing exports
  • Cost and usage reports
const billingAccount = await aws.getBillingServiceAccount();

const billingBucket = new aws.s3.BucketV2("billing-logs");
const billingPolicy = new aws.s3.BucketPolicy("billing-policy", {
    bucket: billingBucket.id,
    policy: pulumi.all([billingBucket.arn, billingAccount.arn]).apply(([bucketArn, billingArn]) =>
        JSON.stringify({
            Version: "2012-10-17",
            Statement: [{
                Effect: "Allow",
                Principal: { AWS: billingArn },
                Action: "s3:PutObject",
                Resource: `${bucketArn}/*`,
            }],
        })
    ),
});

IP Ranges

Get AWS IP address ranges for services.

/**
 * Get AWS IP ranges for services
 * @param args.services - Services to get IP ranges for (e.g., ["S3", "EC2"])
 * @param args.regions - Regions to filter by
 * @returns IP ranges in CIDR notation
 */
function getIpRanges(args?: GetIpRangesArgs): Promise<GetIpRangesResult>;

interface GetIpRangesArgs {
    services?: string[];
    regions?: string[];
    url?: string;
}

interface GetIpRangesResult {
    cidrBlocks: string[];
    ipv6CidrBlocks: string[];
    createDate: string;
    syncToken: string;
}

Usage Example:

const s3Ranges = await aws.getIpRanges({
    services: ["S3"],
    regions: ["us-west-2"],
});

// Use in security group rules
const securityGroup = new aws.ec2.SecurityGroup("allow-s3", {
    ingress: s3Ranges.cidrBlocks.map(cidr => ({
        protocol: "tcp",
        fromPort: 443,
        toPort: 443,
        cidrBlocks: [cidr],
    })),
});

When to Use:

  • Creating security group rules for AWS services
  • Configuring firewall rules
  • Network ACL configuration
// Allow CloudFront IP ranges
const cloudFrontRanges = await aws.getIpRanges({
    services: ["CLOUDFRONT"],
});

const webAcl = new aws.wafv2.WebAcl("web-acl", {
    // Use cloudFrontRanges.cidrBlocks in rules
});

// Region-specific service access
const regionalS3 = await aws.getIpRanges({
    services: ["S3"],
    regions: ["us-west-2", "us-east-1"],
});

Service Information

Get information about AWS services.

/**
 * Get information about an AWS service
 * @param args.service - Service name
 * @param args.region - AWS region
 * @returns Service details
 */
function getService(args: GetServiceArgs): Promise<GetServiceResult>;

interface GetServiceArgs {
    service?: string;
    region?: string;
    reverseEngineerMode?: string;
    dnsName?: string;
    serviceId?: string;
}

interface GetServiceResult {
    partition: string;
    region: string;
    reverseDnsName: string;
    reverseDnsPrefix: string;
    serviceId: string;
    supported: boolean;
}

When to Use:

  • Validating service availability in a region
  • Service endpoint discovery
  • Building service-specific configurations

Service Principal

Get the service principal for an AWS service.

/**
 * Get the service principal for an AWS service
 * @param args.serviceName - Name of the AWS service
 * @param args.region - AWS region
 * @returns Service principal string
 */
function getServicePrincipal(args: GetServicePrincipalArgs): Promise<GetServicePrincipalResult>;

interface GetServicePrincipalArgs {
    serviceName: string;
    region?: string;
}

interface GetServicePrincipalResult {
    name: string;
    suffix: string;
}

Usage Example:

const lambdaPrincipal = await aws.getServicePrincipal({
    serviceName: "lambda",
});

// Use in IAM trust policies
const role = new aws.iam.Role("lambda-role", {
    assumeRolePolicy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Effect: "Allow",
            Principal: {
                Service: lambdaPrincipal.name,
            },
            Action: "sts:AssumeRole",
        }],
    }),
});

When to Use:

  • Creating IAM role trust policies
  • Service-to-service permissions
  • Cross-account access policies
// Multiple service principals
const ec2Principal = await aws.getServicePrincipal({ serviceName: "ec2" });
const ecsTasksPrincipal = await aws.getServicePrincipal({ serviceName: "ecs-tasks" });

const role = new aws.iam.Role("multi-service-role", {
    assumeRolePolicy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
            {
                Effect: "Allow",
                Principal: { Service: ec2Principal.name },
                Action: "sts:AssumeRole",
            },
            {
                Effect: "Allow",
                Principal: { Service: ecsTasksPrincipal.name },
                Action: "sts:AssumeRole",
            },
        ],
    }),
});

// Region-specific principals
const s3Principal = await aws.getServicePrincipal({
    serviceName: "s3",
    region: "cn-north-1", // AWS China
});

Default Tags

Retrieve default tags configuration.

/**
 * Get default tags configuration
 * @returns Default tags
 */
function getDefaultTags(): Promise<GetDefaultTagsResult>;

interface GetDefaultTagsResult {
    tags: { [key: string]: string };
}

When to Use:

  • Retrieving provider-level default tags
  • Merging with resource-specific tags
  • Tag validation and compliance
const defaultTags = await aws.getDefaultTags();

// Merge with resource-specific tags
const bucket = new aws.s3.BucketV2("my-bucket", {
    tags: {
        ...defaultTags.tags,
        Application: "my-app",
        Component: "storage",
    },
});

Utility Functions

SHA1 Hash

Compute a partial SHA1 hash of a string.

/**
 * Compute SHA1 hash (partial, for Pulumi internal use)
 * @param s - String to hash
 * @returns Hash string
 */
function sha1hash(s: string): string;

When to Use:

  • Generating deterministic resource names
  • Creating unique identifiers
  • Internal Pulumi operations

Conditional Value

Return a value if input is undefined.

/**
 * Return value if input is undefined
 * @param input - Input value to check
 * @param value - Value to return if input is undefined
 * @returns Input value or default value
 */
function ifUndefined<T>(input: pulumi.Input<T> | undefined, value: pulumi.Input<T>): pulumi.Output<T>;

Usage Example:

const instanceType = aws.ifUndefined(args.instanceType, "t3.micro");

When to Use:

  • Providing default values for optional inputs
  • Simplifying conditional logic
  • Type-safe default handling
// Complex default handling
const config = {
    instanceType: aws.ifUndefined(args.instanceType, "t3.micro"),
    volumeSize: aws.ifUndefined(args.volumeSize, 20),
    keyName: aws.ifUndefined(args.keyName, "default-key"),
};

const instance = new aws.ec2.Instance("web-server", {
    instanceType: config.instanceType,
    keyName: config.keyName,
    rootBlockDevice: {
        volumeSize: config.volumeSize,
    },
});

Type Utilities

Overwrite Type

Type utility for overwriting properties in existing types.

/**
 * Type utility to overwrite properties in an existing type
 */
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

Usage Example:

interface BaseConfig {
    name: string;
    size: number;
}

// Override size to be a string
type CustomConfig = Overwrite<BaseConfig, { size: string }>;

When to Use:

  • Modifying existing type definitions
  • Creating specialized variants of base types
  • Type-safe configuration overrides
// Override resource args
type CustomInstanceArgs = Overwrite<aws.ec2.InstanceArgs, {
    instanceType: "t3.micro" | "t3.small" | "t3.medium";
    tags: { Environment: string; Owner: string };
}>;

function createInstance(args: CustomInstanceArgs) {
    return new aws.ec2.Instance("instance", args);
}

Related Topics

  • Provider Configuration - Configure AWS provider settings
  • Core Concepts - Understanding Pulumi AWS patterns
  • IAM Guide - IAM roles and policies
  • Multi-Region Deployments - Deploying across regions

Install with Tessl CLI

npx tessl i tessl/npm-pulumi--aws

docs

index.md

quickstart.md

README.md

tile.json