1. Docs
  2. Pulumi IaC
  3. Clouds
  4. AWS
  5. Guides
  6. More examples

More AWS examples

    In addition to the higher-level abstractions in Pulumi Crosswalk, the @pulumi/aws library offers complete, fine-grained control over all available AWS resources. The snippets below are designed to help you address some of the most common scenarios.

    Create an Athena Database and NamedQuery

    This example provisions an S3 bucket and an Athena database, then creates a named query in Athena to select and limit records from the database.

    import * as aws from "@pulumi/aws";
    
    const databaseBucket = new aws.s3.Bucket("mydatabasebucket", {
        forceDestroy: true,
    });
    
    const database = new aws.athena.Database("mydatabase", {
        name: "mydatabase",
        bucket: databaseBucket.bucket,
    });
    
    const namedQuery = new aws.athena.NamedQuery("mynamedquery", {
        database: database.id,
        query: database.id.apply((n) => `SELECT * FROM ${n} limit 10;`),
    });
    

    Create a CloudWatch dashboard

    This example sets up a CloudWatch dashboard with metrics and text widgets, configures an SNS topic for login events, creates an event rule to trigger SNS notifications on AWS console sign-ins, and establishes CloudWatch log groups, metric filters, streams, and alarms for monitoring EC2 CPU utilization.

    import * as aws from "@pulumi/aws";
    
    const dashboard = new aws.cloudwatch.Dashboard("mydashboard", {
        dashboardName: "my-dashboard",
        dashboardBody: JSON.stringify({
            widgets: [
                {
                    type: "metric",
                    x: 0,
                    y: 0,
                    width: 12,
                    height: 6,
                    properties: {
                        metrics: [
                            ["AWS/EC2", "CPUUtilization", "InstanceId", "i-012345"],
                        ],
                        period: 300,
                        stat: "Average",
                        region: "us-east-1",
                        title: "EC2 Instance CPU",
                    },
                },
                {
                    type: "text",
                    x: 0,
                    y: 7,
                    width: 3,
                    height: 3,
                    properties: {
                        markdown: "Hello world",
                    },
                },
            ],
        }),
    });
    
    const loginsTopic = new aws.sns.Topic("myloginstopic");
    
    const eventRule = new aws.cloudwatch.EventRule("myeventrule", {
        eventPattern: JSON.stringify({
            "detail-type": ["AWS Console Sign In via CloudTrail"],
        }),
    });
    
    const eventTarget = new aws.cloudwatch.EventTarget("myeventtarget", {
        rule: eventRule.name,
        targetId: "SendToSNS",
        arn: loginsTopic.arn,
    });
    
    const logGroup = new aws.cloudwatch.LogGroup("myloggroup");
    
    const logMetricFilter = new aws.cloudwatch.LogMetricFilter(
        "mylogmetricfilter",
        {
            pattern: "",
            logGroupName: logGroup.name,
            metricTransformation: {
                name: "EventCount",
                namespace: "YourNamespace",
                value: "1",
            },
        },
    );
    
    const logStream = new aws.cloudwatch.LogStream("mylogstream", {
        logGroupName: logGroup.name,
    });
    
    const metricAlarm = new aws.cloudwatch.MetricAlarm("mymetricalarm", {
        comparisonOperator: "GreaterThanOrEqualToThreshold",
        evaluationPeriods: 2,
        metricName: "CPUUtilization",
        namespace: "AWS/EC2",
        period: 120,
        statistic: "Average",
        threshold: 80,
        alarmDescription: "This metric monitors ec2 cpu utilization",
    });
    

    Create a DynamoDB table

    This example provisions an AWS DynamoDB table with a string attribute of Id as the hash key and sets read and write capacities to 1 unit each.

    import * as aws from "@pulumi/aws";
    
    const db = new aws.dynamodb.Table("mytable", {
        attributes: [{ name: "Id", type: "S" }],
        hashKey: "Id",
        readCapacity: 1,
        writeCapacity: 1,
    });
    

    Create an EC2 instance

    This example provisions a VPC with an internet gateway, public subnet, route table, and security group, and launches an Amazon Linux EC2 instance with NGINX into the public subnet, exporting its publicly accessible URL.

    "use strict";
    const pulumi = require("@pulumi/pulumi");
    const aws = require("@pulumi/aws");
    
    // Create a VPC.
    const vpc = new aws.ec2.Vpc("vpc", {
        cidrBlock: "10.0.0.0/16",
    });
    
    // Create an internet gateway.
    const gateway = new aws.ec2.InternetGateway("gateway", {
        vpcId: vpc.id,
    });
    
    // Create a subnet that automatically assigns new instances a public IP address.
    const subnet = new aws.ec2.Subnet("subnet", {
        vpcId: vpc.id,
        cidrBlock: "10.0.1.0/24",
        mapPublicIpOnLaunch: true,
    });
    
    // Create a route table.
    const routes = new aws.ec2.RouteTable("routes", {
        vpcId: vpc.id,
        routes: [
            {
                cidrBlock: "0.0.0.0/0",
                gatewayId: gateway.id,
            },
        ],
    });
    
    // Associate the route table with the public subnet.
    const routeTableAssociation = new aws.ec2.RouteTableAssociation("route-table-association", {
        subnetId: subnet.id,
        routeTableId: routes.id,
    });
    
    // Create a security group allowing inbound access over port 80 and outbound
    // access to anywhere.
    const securityGroup = new aws.ec2.SecurityGroup("security-group", {
        vpcId: vpc.id,
        ingress: [
            {
                cidrBlocks: ["0.0.0.0/0"],
                protocol: "tcp",
                fromPort: 80,
                toPort: 80,
            },
        ],
        egress: [
            {
                cidrBlocks: ["0.0.0.0/0"],
                fromPort: 0,
                toPort: 0,
                protocol: "-1",
            },
        ],
    });
    
    // Find the latest Amazon Linux 2 AMI.
    const ami = pulumi.output(
        aws.ec2.getAmi({
            owners: ["amazon"],
            mostRecent: true,
            filters: [{ name: "description", values: ["Amazon Linux 2 *"] }],
        }),
    );
    
    // Create and launch an Amazon Linux EC2 instance into the public subnet.
    const instance = new aws.ec2.Instance("instance", {
        ami: ami.id,
        instanceType: "t3.nano",
        subnetId: subnet.id,
        vpcSecurityGroupIds: [securityGroup.id],
        userData: `
            #!/bin/bash
            sudo yum update -y
            sudo yum upgrade -y
            sudo amazon-linux-extras install nginx1 -y
            sudo systemctl enable nginx
            sudo systemctl start nginx;
        `,
    });
    
    // Export the instance's publicly accessible URL.
    exports.instanceURL = pulumi.interpolate`http://${instance.publicIp}`;
    
    import * as pulumi from "@pulumi/pulumi";
    import * as aws from "@pulumi/aws";
    
    // Create a VPC.
    const vpc = new aws.ec2.Vpc("vpc", {
        cidrBlock: "10.0.0.0/16",
    });
    
    // Create an an internet gateway.
    const gateway = new aws.ec2.InternetGateway("gateway", {
        vpcId: vpc.id,
    });
    
    // Create a subnet that automatically assigns new instances a public IP address.
    const subnet = new aws.ec2.Subnet("subnet", {
        vpcId: vpc.id,
        cidrBlock: "10.0.1.0/24",
        mapPublicIpOnLaunch: true,
    });
    
    // Create a route table.
    const routes = new aws.ec2.RouteTable("routes", {
        vpcId: vpc.id,
        routes: [
            {
                cidrBlock: "0.0.0.0/0",
                gatewayId: gateway.id,
            },
        ],
    });
    
    // Associate the route table with the public subnet.
    const routeTableAssociation = new aws.ec2.RouteTableAssociation("route-table-association", {
        subnetId: subnet.id,
        routeTableId: routes.id,
    });
    
    // Create a security group allowing inbound access over port 80 and outbound
    // access to anywhere.
    const securityGroup = new aws.ec2.SecurityGroup("security-group", {
        vpcId: vpc.id,
        ingress: [
            {
                cidrBlocks: ["0.0.0.0/0"],
                protocol: "tcp",
                fromPort: 80,
                toPort: 80,
            },
        ],
        egress: [
            {
                cidrBlocks: ["0.0.0.0/0"],
                fromPort: 0,
                toPort: 0,
                protocol: "-1",
            },
        ],
    });
    
    // Find the latest Amazon Linux 2 AMI.
    const ami = pulumi.output(
        aws.ec2.getAmi({
            owners: ["amazon"],
            mostRecent: true,
            filters: [{ name: "description", values: ["Amazon Linux 2 *"] }],
        }),
    );
    
    // Create and launch an Amazon Linux EC2 instance into the public subnet.
    const instance = new aws.ec2.Instance("instance", {
        ami: ami.id,
        instanceType: "t3.nano",
        subnetId: subnet.id,
        vpcSecurityGroupIds: [securityGroup.id],
        userData: `
            #!/bin/bash
            sudo yum update -y
            sudo yum upgrade -y
            sudo amazon-linux-extras install nginx1 -y
            sudo systemctl enable nginx
            sudo systemctl start nginx;
        `,
    });
    
    // Export the instance's publicly accessible URL.
    export const instanceURL = pulumi.interpolate`http://${instance.publicIp}`;
    
    import pulumi
    import pulumi_aws as aws
    
    # Create a VPC.
    vpc = aws.ec2.Vpc("vpc",
        cidr_block="10.0.0.0/16",
    )
    
    # Create an internet gateway.
    gateway = aws.ec2.InternetGateway("gateway",
        vpc_id=vpc.id,
    )
    
    # Create a subnet that automatically assigns new instances a public IP address.
    subnet = aws.ec2.Subnet("subnet",
        vpc_id=vpc.id,
        cidr_block="10.0.1.0/24",
        map_public_ip_on_launch=True,
    )
    
    # Create a route table.
    routes = aws.ec2.RouteTable("routes",
        vpc_id=vpc.id,
        routes=[
            aws.ec2.RouteTableRouteArgs(
                cidr_block="0.0.0.0/0",
                gateway_id=gateway.id,
            ),
        ],
    )
    
    # Associate the route table with the public subnet.
    route_table_association = aws.ec2.RouteTableAssociation("route-table-association",
        subnet_id=subnet.id,
        route_table_id=routes.id,
    )
    
    # Create a security group allowing inbound access over port 80 and outbound
    # access to anywhere.
    security_group = aws.ec2.SecurityGroup("security-group",
        vpc_id=vpc.id,
        ingress=[
            aws.ec2.SecurityGroupIngressArgs(
                cidr_blocks=["0.0.0.0/0"],
                protocol="tcp",
                from_port=80,
                to_port=80,
            ),
        ],
        egress=[
            aws.ec2.SecurityGroupEgressArgs(
                cidr_blocks=["0.0.0.0/0"],
                from_port=0,
                to_port=0,
                protocol="-1",
            ),
        ],
    )
    
    # Find the latest Amazon Linux 2 AMI.
    ami = pulumi.Output.from_input(aws.ec2.get_ami(
        owners=["amazon"],
        most_recent=True,
        filters=[{"name": "description", "values": ["Amazon Linux 2 *"]}],
    )).apply(lambda ami: ami.id)
    
    # Create and launch an Amazon Linux EC2 instance into the public subnet.
    instance = aws.ec2.Instance("instance",
        ami=ami,
        instance_type="t3.nano",
        subnet_id=subnet.id,
        vpc_security_group_ids=[security_group.id],
        user_data="""
            #!/bin/bash
            sudo yum update -y
            sudo yum upgrade -y
            sudo amazon-linux-extras install nginx1 -y
            sudo systemctl enable nginx
            sudo systemctl start nginx;
        """,
    )
    
    # Export the instance's publicly accessible URL.
    pulumi.export("instanceURL", pulumi.Output.concat("http://", instance.public_ip))
    
    package main
    
    import (
    	"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/ec2"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		// Create a VPC.
    		vpc, err := ec2.NewVpc(ctx, "vpc", &ec2.VpcArgs{
    			CidrBlock: pulumi.String("10.0.0.0/16"),
    		})
    		if err != nil {
    			return err
    		}
    
    		// Create an internet gateway.
    		gateway, err := ec2.NewInternetGateway(ctx, "gateway", &ec2.InternetGatewayArgs{
    			VpcId: vpc.ID(),
    		})
    		if err != nil {
    			return err
    		}
    
    		// Create a subnet that automatically assigns new instances a public IP address.
    		subnet, err := ec2.NewSubnet(ctx, "subnet", &ec2.SubnetArgs{
    			VpcId:               vpc.ID(),
    			CidrBlock:           pulumi.String("10.0.1.0/24"),
    			MapPublicIpOnLaunch: pulumi.Bool(true),
    		})
    		if err != nil {
    			return err
    		}
    
    		// Create a route table.
    		routes, err := ec2.NewRouteTable(ctx, "routes", &ec2.RouteTableArgs{
    			VpcId: vpc.ID(),
    			Routes: ec2.RouteTableRouteArray{
    				&ec2.RouteTableRouteArgs{
    					CidrBlock: pulumi.String("0.0.0.0/0"),
    					GatewayId: gateway.ID(),
    				},
    			},
    		})
    		if err != nil {
    			return err
    		}
    
    		// Associate the route table with the public subnet.
    		_, err = ec2.NewRouteTableAssociation(ctx, "route-table-association", &ec2.RouteTableAssociationArgs{
    			SubnetId:     subnet.ID(),
    			RouteTableId: routes.ID(),
    		})
    		if err != nil {
    			return err
    		}
    
    		// Create a security group allowing inbound access over port 80 and outbound access to anywhere.
    		securityGroup, err := ec2.NewSecurityGroup(ctx, "security-group", &ec2.SecurityGroupArgs{
    			VpcId: vpc.ID(),
    			Ingress: ec2.SecurityGroupIngressArray{
    				&ec2.SecurityGroupIngressArgs{
    					CidrBlocks: pulumi.StringArray{
    						pulumi.String("0.0.0.0/0"),
    					},
    					Protocol: pulumi.String("tcp"),
    					FromPort: pulumi.Int(80),
    					ToPort:   pulumi.Int(80),
    				},
    			},
    			Egress: ec2.SecurityGroupEgressArray{
    				&ec2.SecurityGroupEgressArgs{
    					CidrBlocks: pulumi.StringArray{
    						pulumi.String("0.0.0.0/0"),
    					},
    					FromPort: pulumi.Int(0),
    					ToPort:   pulumi.Int(0),
    					Protocol: pulumi.String("-1"),
    				},
    			},
    		})
    		if err != nil {
    			return err
    		}
    
    		// Find the latest Amazon Linux 2 AMI.
    		ami, err := ec2.LookupAmi(ctx, &ec2.LookupAmiArgs{
    			Owners:     []string{"amazon"},
    			MostRecent: pulumi.BoolRef(true),
    			Filters: []ec2.GetAmiFilter{
    				{
    					Name:   "description",
    					Values: []string{"Amazon Linux 2 *"},
    				},
    			},
    		})
    		if err != nil {
    			return err
    		}
    
    		// Create and launch an Amazon Linux EC2 instance into the public subnet.
    		instance, err := ec2.NewInstance(ctx, "instance", &ec2.InstanceArgs{
    			Ami:                 pulumi.String(ami.Id),
    			InstanceType:        pulumi.String("t3.nano"),
    			SubnetId:            subnet.ID(),
    			VpcSecurityGroupIds: pulumi.StringArray{securityGroup.ID()},
    			UserData: pulumi.String(`
    				#!/bin/bash
    				sudo yum update -y
    				sudo yum upgrade -y
    				sudo amazon-linux-extras install nginx1 -y
    				sudo systemctl enable nginx
    				sudo systemctl start nginx;
    			`),
    		})
    		if err != nil {
    			return err
    		}
    
    		// Export the instance's publicly accessible URL.
    		ctx.Export("instanceURL", pulumi.Sprintf("http://%s", instance.PublicIp))
    		return nil
    	})
    }
    
    using Pulumi;
    using Pulumi.Aws.Ec2;
    using Pulumi.Aws.Ec2.Inputs;
    using System.Collections.Generic;
    
    return await Deployment.RunAsync(() => 
    {
        // Create a VPC.
        var vpc = new Vpc("vpc", new VpcArgs
        {
            CidrBlock = "10.0.0.0/16",
        });
    
        // Create an internet gateway.
        var gateway = new InternetGateway("gateway", new InternetGatewayArgs
        {
            VpcId = vpc.Id,
        });
    
        // Create a subnet that automatically assigns new instances a public IP address.
        var subnet = new Subnet("subnet", new SubnetArgs
        {
            VpcId = vpc.Id,
            CidrBlock = "10.0.1.0/24",
            MapPublicIpOnLaunch = true,
        });
    
        // Create a route table.
        var routes = new RouteTable("routes", new RouteTableArgs
        {
            VpcId = vpc.Id,
            Routes = new List<RouteTableRouteArgs>
            {
                new RouteTableRouteArgs
                {
                    CidrBlock = "0.0.0.0/0",
                    GatewayId = gateway.Id,
                },
            },
        });
    
        // Associate the route table with the public subnet.
        var routeTableAssociation = new RouteTableAssociation("route-table-association", new RouteTableAssociationArgs
        {
            SubnetId = subnet.Id,
            RouteTableId = routes.Id,
        });
    
        // Create a security group allowing inbound access over port 80 and outbound access to anywhere.
        var securityGroup = new SecurityGroup("security-group", new SecurityGroupArgs
        {
            VpcId = vpc.Id,
            Ingress = new List<SecurityGroupIngressArgs>
            {
                new SecurityGroupIngressArgs
                {
                    CidrBlocks = new List<string> { "0.0.0.0/0" },
                    Protocol = "tcp",
                    FromPort = 80,
                    ToPort = 80,
                },
            },
            Egress = new List<SecurityGroupEgressArgs>
            {
                new SecurityGroupEgressArgs
                {
                    CidrBlocks = new List<string> { "0.0.0.0/0" },
                    FromPort = 0,
                    ToPort = 0,
                    Protocol = "-1",
                },
            },
        });
    
        // Find the latest Amazon Linux 2 AMI.
        var ami = Output.Create(GetAmi.InvokeAsync(new GetAmiArgs
        {
            Owners = new List<string> { "amazon" },
            MostRecent = true,
            Filters = new List<GetAmiFilterArgs>
            {
                new GetAmiFilterArgs
                {
                    Name = "description",
                    Values = new List<string> { "Amazon Linux 2 *" },
                },
            },
        })).Apply(ami => ami.Id);
    
        // Create and launch an Amazon Linux EC2 instance into the public subnet.
        var instance = new Instance("instance", new InstanceArgs
        {
            Ami = ami,
            InstanceType = "t3.nano",
            SubnetId = subnet.Id,
            VpcSecurityGroupIds = new InputList<string> { securityGroup.Id },
            UserData = @"
                #!/bin/bash
                sudo yum update -y
                sudo yum upgrade -y
                sudo amazon-linux-extras install nginx1 -y
                sudo systemctl enable nginx
                sudo systemctl start nginx;
            ",
        });
    
        // Export the instance's publicly accessible URL.
        return new Dictionary<string, object?>
        {
            ["instanceURL"] = Output.Format($"http://{instance.PublicIp}")
        };
    });
    
    package myproject;
    
    import com.pulumi.Context;
    import com.pulumi.Pulumi;
    import com.pulumi.core.Output;
    import com.pulumi.aws.ec2.Vpc;
    import com.pulumi.aws.ec2.VpcArgs;
    import com.pulumi.aws.ec2.Instance;
    import com.pulumi.aws.ec2.InstanceArgs;
    import com.pulumi.aws.ec2.InternetGateway;
    import com.pulumi.aws.ec2.InternetGatewayArgs;
    import com.pulumi.aws.ec2.Subnet;
    import com.pulumi.aws.ec2.SubnetArgs;
    import com.pulumi.aws.ec2.RouteTable;
    import com.pulumi.aws.ec2.RouteTableArgs;
    import com.pulumi.aws.ec2.inputs.RouteTableRouteArgs;
    import com.pulumi.aws.ec2.RouteTableAssociation;
    import com.pulumi.aws.ec2.RouteTableAssociationArgs;
    import com.pulumi.aws.ec2.SecurityGroup;
    import com.pulumi.aws.ec2.SecurityGroupArgs;
    import com.pulumi.aws.vpc.SecurityGroupIngressRule;
    import com.pulumi.aws.vpc.SecurityGroupIngressRuleArgs;
    import com.pulumi.aws.vpc.SecurityGroupEgressRule;
    import com.pulumi.aws.vpc.SecurityGroupEgressRuleArgs;
    import com.pulumi.aws.ec2.Ec2Functions;
    import com.pulumi.aws.ec2.inputs.GetAmiArgs;
    import com.pulumi.aws.ec2.inputs.GetAmiFilterArgs;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(ctx -> {
                // Create a VPC.
                var vpc = new Vpc("vpc", VpcArgs.builder()
                    .cidrBlock("10.0.0.0/16")
                    .build());
    
                // Create an internet gateway.
                var gateway = new InternetGateway("gateway", InternetGatewayArgs.builder()
                    .vpcId(vpc.id())
                    .build());
    
                // Create a subnet that automatically assigns new instances a public IP address.
                var subnet = new Subnet("subnet", SubnetArgs.builder()
                    .vpcId(vpc.id())
                    .cidrBlock("10.0.1.0/24")
                    .mapPublicIpOnLaunch(true)
                    .build());
    
                // Create a route table.
                var routes = new RouteTable("routes", RouteTableArgs.builder()
                    .vpcId(vpc.id())
                    .routes(RouteTableRouteArgs.builder()
                        .cidrBlock("0.0.0.0/0")
                        .gatewayId(gateway.id())
                        .build())
                    .build());
    
                // Associate the route table with the public subnet.
                var routeTableAssociation = new RouteTableAssociation("route-table-association", RouteTableAssociationArgs.builder()
                    .subnetId(subnet.id())
                    .routeTableId(routes.id())
                    .build());
    
                // Create a security group allowing inbound access over port 80 and outbound access to anywhere.
                var securityGroup = new SecurityGroup("security-group", SecurityGroupArgs.builder()        
                    .name("allow_public")
                    .vpcId(vpc.id())
                    .build());
        
                var allowPort80Ipv4 = new SecurityGroupIngressRule("allowPort80Ingress", SecurityGroupIngressRuleArgs.builder()        
                    .securityGroupId(securityGroup.id())
                    .cidrIpv4("0.0.0.0/0")
                    .fromPort(80)
                    .ipProtocol("tcp")
                    .toPort(80)
                    .build());
    
                var allowAllTrafficIpv4 = new SecurityGroupEgressRule("allowAllTrafficEgress", SecurityGroupEgressRuleArgs.builder()        
                    .securityGroupId(securityGroup.id())
                    .cidrIpv4("0.0.0.0/0")
                    .ipProtocol("-1")
                    .build());
    
                // Find the latest Amazon Linux 2 AMI.
                var ami = Ec2Functions.getAmi(GetAmiArgs.builder()
                    .owners("amazon")
                    .mostRecent(true)
                    .filters(GetAmiFilterArgs.builder()
                        .name("description")
                        .values("Amazon Linux 2 *")
                        .build())
                    .build()).applyValue(getAmiResult -> getAmiResult.id());
    
                // Create and launch an Amazon Linux EC2 instance into the public subnet.
                var instance = new Instance("instance", InstanceArgs.builder()
                    .ami(ami)
                    .instanceType("t3.nano")
                    .subnetId(subnet.id())
                    .vpcSecurityGroupIds(Output.all(securityGroup.id()))
                    .userData(
                            "#!/bin/bash\n" +
                            "sudo yum update -y\n" +
                            "sudo yum upgrade -y\n" +
                            "sudo amazon-linux-extras install nginx1 -y\n" +
                            "sudo systemctl enable nginx\n" +
                            "sudo systemctl start nginx;\n"
                    )
                    .build());
    
                // Export the instance's publicly accessible URL.
                ctx.export("instanceURL", Output.format("http://%s", instance.publicIp()));
            });
        }
    }
    
    name: aws-ec2-vpc-resources-yaml
    runtime: yaml
    description: An example that deploys a VPC with an internet gateway, public subnet, route table, and security group, and launches an Amazon Linux EC2 instance with NGINX.
    
    resources:
      myVpc:
        type: aws:ec2:Vpc
        properties:
          cidrBlock: "10.0.0.0/16"
      myInternetGateway:
        type: aws:ec2:InternetGateway
        properties:
          vpcId: ${myVpc.id}
    
      mySubnet:
        type: aws:ec2:Subnet
        properties:
          vpcId: ${myVpc.id}
          cidrBlock: "10.0.1.0/24"
          mapPublicIpOnLaunch: true
    
      myRouteTable:
        type: aws:ec2:RouteTable
        properties:
          vpcId: ${myVpc.id}
          routes:
            - cidrBlock: "0.0.0.0/0"
              gatewayId: ${myInternetGateway.id}
    
      myRouteTableAssociation:
        type: aws:ec2:RouteTableAssociation
        properties:
          routeTableId: ${myRouteTable.id}
          subnetId: ${mySubnet.id}
    
      mySecurityGroup:
        type: aws:ec2:SecurityGroup
        properties:
          vpcId: ${myVpc.id}
          description: "Allow HTTP inbound traffic"
          ingress:
            - protocol: tcp
              fromPort: 80
              toPort: 80
              cidrBlocks:
                - "0.0.0.0/0"
          egress:
            - protocol: "-1"
              fromPort: 0
              toPort: 0
              cidrBlocks:
                - "0.0.0.0/0"
    
      myInstance:
        type: aws:ec2:Instance
        properties:
          ami: ${myAmi.id}
          instanceType: "t2.micro"
          subnetId: ${mySubnet.id}
          securityGroups:
            - ${mySecurityGroup.id}
          userData: |
            #!/bin/bash
            sudo yum update -y
            sudo yum upgrade -y
            sudo amazon-linux-extras install nginx1 -y
            sudo systemctl enable nginx
            sudo systemctl start nginx;        
    
    variables:
      myAmi:
        fn::invoke:
          function: aws:ec2:getAmi
          arguments:
            mostRecent: true
            filters:
              - name: description
                values:
                  - "Amazon Linux 2 *"
            owners:
              - "amazon"
    
    outputs:
      publicUrl: http://${myInstance.publicIp}
    

    Create an ECR repository

    This example sets up an Amazon Elastic Container Registry (ECR) repository and defines a repository policy and configures a lifecycle policy for the repository to automatically expire images older than 14 days.

    import * as aws from "@pulumi/aws";
    
    const repository = new aws.ecr.Repository("myrepository");
    
    const repositoryPolicy = new aws.ecr.RepositoryPolicy("myrepositorypolicy", {
        repository: repository.id,
        policy: JSON.stringify({
            Version: "2012-10-17",
            Statement: [
                {
                    Effect: "Allow",
                    Principal: "*",
                    Action: [
                        "ecr:GetDownloadUrlForLayer",
                        "ecr:BatchGetImage",
                        "ecr:BatchCheckLayerAvailability",
                        "ecr:PutImage",
                        "ecr:InitiateLayerUpload",
                        "ecr:UploadLayerPart",
                        "ecr:CompleteLayerUpload",
                        "ecr:DescribeRepositories",
                        "ecr:GetRepositoryPolicy",
                        "ecr:ListImages",
                        "ecr:DeleteRepository",
                        "ecr:BatchDeleteImage",
                        "ecr:SetRepositoryPolicy",
                        "ecr:DeleteRepositoryPolicy",
                    ],
                },
            ],
        }),
    });
    
    const lifecyclePolicy = new aws.ecr.LifecyclePolicy("mylifecyclepolicy", {
        repository: repository.id,
        policy: JSON.stringify({
            rules: [
                {
                    rulePriority: 1,
                    description: "Expire images older than 14 days",
                    selection: {
                        tagStatus: "untagged",
                        countType: "sinceImagePushed",
                        countUnit: "days",
                        countNumber: 14,
                    },
                    action: {
                        type: "expire",
                    },
                },
            ],
        }),
    });
    

    Create a Kinesis stream

    This example creates an Amazon Kinesis stream with one shard.

    import * as aws from "@pulumi/aws";
    
    const stream = new aws.kinesis.Stream("mystream", {
        shardCount: 1,
    });
    

    Create S3 bucket resources

    This example provisions an S3 bucket, bucket metric, bucket notification, and bucket object, and applies the necessary access controls to allow anyone on the internet to retrieve objects from the bucket.

    "use strict";
    const aws = require("@pulumi/aws");
    
    const bucket = new aws.s3.Bucket("my-bucket");
    
    const ownershipControls = new aws.s3.BucketOwnershipControls("ownership-controls", {
        bucket: bucket.id,
        rule: {
            objectOwnership: "ObjectWriter",
        },
    });
    
    const publicAccessBlock = new aws.s3.BucketPublicAccessBlock("public-access-block", {
        bucket: bucket.id,
        blockPublicAcls: false,
    });
    
    const bucketMetric = new aws.s3.BucketMetric("my-bucket-metric", {
        bucket: bucket.bucket,
    });
    
    const bucketNotification = new aws.s3.BucketNotification("my-bucket-notification", {
        bucket: bucket.bucket,
    });
    
    const bucketObject = new aws.s3.BucketObject(
        "my-bucket-object",
        {
            bucket: bucket.bucket,
            content: "hello world",
        },
        { dependsOn: [publicAccessBlock, ownershipControls] },
    );
    
    const bucketPolicy = new aws.s3.BucketPolicy(
        "my-bucket-policy",
        {
            bucket: bucket.bucket,
            policy: bucket.bucket.apply(publicReadPolicyForBucket),
        },
        { dependsOn: [publicAccessBlock, ownershipControls] },
    );
    
    function publicReadPolicyForBucket(bucketName) {
        return JSON.stringify({
            Version: "2012-10-17",
            Statement: [
                {
                    Effect: "Allow",
                    Principal: "*",
                    Action: ["s3:GetObject"],
                    Resource: [
                        `arn:aws:s3:::${bucketName}/*`, // policy refers to bucket name explicitly
                    ],
                },
            ],
        });
    }
    
    import * as aws from "@pulumi/aws";
    
    const bucket = new aws.s3.Bucket("my-bucket");
    
    const ownershipControls = new aws.s3.BucketOwnershipControls("ownership-controls", {
        bucket: bucket.id,
        rule: {
            objectOwnership: "ObjectWriter",
        },
    });
    
    const publicAccessBlock = new aws.s3.BucketPublicAccessBlock("public-access-block", {
        bucket: bucket.id,
        blockPublicAcls: false,
    });
    
    const bucketMetric = new aws.s3.BucketMetric("my-bucket-metric", {
        bucket: bucket.id,
    });
    
    const bucketNotification = new aws.s3.BucketNotification("my-bucket-notification", {
        bucket: bucket.id,
    });
    
    const bucketObject = new aws.s3.BucketObject(
        "my-bucket-object",
        {
            bucket: bucket.id,
            content: "hello world",
        },
        { dependsOn: [publicAccessBlock, ownershipControls] },
    );
    
    const bucketPolicy = new aws.s3.BucketPolicy(
        "my-bucket-policy",
        {
            bucket: bucket.id,
            policy: bucket.id.apply(publicReadPolicyForBucket),
        },
        { dependsOn: [publicAccessBlock, ownershipControls] },
    );
    
    function publicReadPolicyForBucket(bucketName: string): string {
        return JSON.stringify({
            Version: "2012-10-17",
            Statement: [
                {
                    Effect: "Allow",
                    Principal: "*",
                    Action: "s3:GetObject",
                    Resource: `arn:aws:s3:::${bucketName}/*`, // policy refers to bucket name explicitly
                },
            ],
        });
    }
    
    import json
    import pulumi
    import pulumi_aws as aws
    
    bucket = aws.s3.Bucket("my-bucket")
    
    ownership_controls = aws.s3.BucketOwnershipControls(
        "ownership-controls",
        bucket=bucket.id,
        rule=aws.s3.BucketOwnershipControlsRuleArgs(
            object_ownership="ObjectWriter",
        ),
    )
    
    public_access_block = aws.s3.BucketPublicAccessBlock(
        "public-access-block",
        bucket=bucket.id,
        block_public_acls=False,
    )
    
    bucket_metric = aws.s3.BucketMetric(
        "my-bucket-metric",
        bucket=bucket.id,
    )
    
    bucket_notification = aws.s3.BucketNotification(
        "my-bucket-notification",
        bucket=bucket.id,
    )
    
    bucket_object = aws.s3.BucketObject(
        "my-bucket-object",
        bucket=bucket.id,
        content="hello world",
        opts=pulumi.ResourceOptions(depends_on=[public_access_block, ownership_controls]),
    )
    
    
    def public_read_policy_for_bucket(bucket_name):
        return pulumi.Output.all(bucket_name).apply(
            lambda args: json.dumps(
                {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": "*",
                            "Action": "s3:GetObject",
                            "Resource": f"arn:aws:s3:::{args[0]}/*",
                        }
                    ],
                }
            )
        )
    
    
    bucket_policy = aws.s3.BucketPolicy(
        "my-bucket-policy",
        bucket=bucket.id,
        policy=bucket.id.apply(public_read_policy_for_bucket),
        opts=pulumi.ResourceOptions(depends_on=[public_access_block, ownership_controls]),
    )
    
    package main
    
    import (
    	"encoding/json"
    
    	"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/s3"
    	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    )
    
    func main() {
    	pulumi.Run(func(ctx *pulumi.Context) error {
    		bucket, err := s3.NewBucket(ctx, "my-bucket", nil)
    		if err != nil {
    			return err
    		}
    
    		ownershipControls, err := s3.NewBucketOwnershipControls(ctx, "ownership-controls", &s3.BucketOwnershipControlsArgs{
    			Bucket: bucket.ID(),
    			Rule: &s3.BucketOwnershipControlsRuleArgs{
    				ObjectOwnership: pulumi.String("ObjectWriter"),
    			},
    		})
    		if err != nil {
    			return err
    		}
    
    		publicAccessBlock, err := s3.NewBucketPublicAccessBlock(ctx, "public-access-block", &s3.BucketPublicAccessBlockArgs{
    			Bucket:          bucket.ID(),
    			BlockPublicAcls: pulumi.Bool(false),
    		})
    		if err != nil {
    			return err
    		}
    
    		_, err = s3.NewBucketMetric(ctx, "my-bucket-metric", &s3.BucketMetricArgs{
    			Bucket: bucket.ID(),
    		})
    		if err != nil {
    			return err
    		}
    
    		_, err = s3.NewBucketNotification(ctx, "my-bucket-notification", &s3.BucketNotificationArgs{
    			Bucket: bucket.ID(),
    		})
    		if err != nil {
    			return err
    		}
    
    		_, err = s3.NewBucketObject(ctx, "my-bucket-object", &s3.BucketObjectArgs{
    			Bucket:  bucket.ID(),
    			Content: pulumi.String("hello world"),
    		}, pulumi.DependsOn([]pulumi.Resource{
    			publicAccessBlock,
    			ownershipControls,
    		}))
    		if err != nil {
    			return err
    		}
    
    		_, err = s3.NewBucketPolicy(ctx, "my-bucket-policy", &s3.BucketPolicyArgs{
    			Bucket: bucket.ID(),
    			Policy: bucket.ID().ToStringOutput().ApplyT(func(bucketName string) (string, error) {
    				policy := map[string]interface{}{
    					"Version": "2012-10-17",
    					"Statement": []interface{}{
    						map[string]interface{}{
    							"Effect":    "Allow",
    							"Principal": "*",
    							"Action":    "s3:GetObject",
    							"Resource":  "arn:aws:s3:::" + bucketName + "/*",
    						},
    					},
    				}
    				policyJSON, err := json.Marshal(policy)
    				return string(policyJSON), err
    			}).(pulumi.StringOutput),
    		}, pulumi.DependsOn([]pulumi.Resource{
    			publicAccessBlock,
    			ownershipControls,
    		}))
    		if err != nil {
    			return err
    		}
    
    		return nil
    	})
    }
    
    using System.Collections.Generic;
    using System.Text.Json;
    using Pulumi;
    using Aws = Pulumi.Aws;
    
    return await Deployment.RunAsync(() =>
    {
        var bucket = new Aws.S3.Bucket("my-bucket");
    
        var ownershipControls = new Aws.S3.BucketOwnershipControls(
            "ownership-controls",
            new()
            {
                Bucket = bucket.Id,
                Rule = new Aws.S3.Inputs.BucketOwnershipControlsRuleArgs
                {
                    ObjectOwnership = "ObjectWriter"
                }
            }
        );
    
        var publicAccessBlock = new Aws.S3.BucketPublicAccessBlock(
            "public-access-block",
            new() { Bucket = bucket.Id, BlockPublicAcls = false }
        );
    
        var bucketMetric = new Aws.S3.BucketMetric("my-bucket-metric", new() { Bucket = bucket.Id });
    
        var bucketNotification = new Aws.S3.BucketNotification(
            "my-bucket-notification",
            new() { Bucket = bucket.Id }
        );
    
        var bucketObject = new Aws.S3.BucketObject(
            "my-bucket-object",
            new Aws.S3.BucketObjectArgs { Bucket = bucket.Id, Content = "hello world" },
            new CustomResourceOptions
            {
                DependsOn = new List<Resource> { publicAccessBlock, ownershipControls }
            }
        );
    
        var bucketPolicy = new Aws.S3.BucketPolicy(
            "my-bucket-policy",
            new() { Bucket = bucket.Id, Policy = bucket.Id.Apply(id => PublicReadPolicyForBucket(id)) },
            new CustomResourceOptions
            {
                DependsOn = new List<Resource> { publicAccessBlock, ownershipControls }
            }
        );
    
        return new Dictionary<string, object?> { { "bucketName", bucket.Id } };
    });
    
    static string PublicReadPolicyForBucket(string bucketName)
    {
        return JsonSerializer.Serialize(
            new
            {
                Version = "2012-10-17",
                Statement = new[]
                {
                    new
                    {
                        Effect = "Allow",
                        Principal = "*",
                        Action = "s3:GetObject",
                        Resource = $"arn:aws:s3:::{bucketName}/*"
                    }
                }
            }
        );
    }
    
    package myproject;
    
    import com.pulumi.Pulumi;
    import com.pulumi.aws.s3.Bucket;
    import com.pulumi.aws.s3.BucketArgs;
    import com.pulumi.aws.s3.BucketMetric;
    import com.pulumi.aws.s3.BucketMetricArgs;
    import com.pulumi.aws.s3.BucketNotification;
    import com.pulumi.aws.s3.BucketNotificationArgs;
    import com.pulumi.aws.s3.BucketObject;
    import com.pulumi.aws.s3.BucketObjectArgs;
    import com.pulumi.aws.s3.BucketOwnershipControls;
    import com.pulumi.aws.s3.BucketOwnershipControlsArgs;
    import com.pulumi.aws.s3.BucketPolicy;
    import com.pulumi.aws.s3.BucketPolicyArgs;
    import com.pulumi.aws.s3.BucketPublicAccessBlock;
    import com.pulumi.aws.s3.BucketPublicAccessBlockArgs;
    import com.pulumi.aws.s3.inputs.BucketOwnershipControlsRuleArgs;
    import com.pulumi.resources.CustomResourceOptions;
    import static com.pulumi.codegen.internal.Serialization.*;
    
    public class App {
        public static void main(String[] args) {
            Pulumi.run(ctx -> {
                var bucket = new Bucket("my-bucket", BucketArgs.builder().build());
    
                var ownershipControls = new BucketOwnershipControls("ownership-controls", BucketOwnershipControlsArgs.builder()
                    .bucket(bucket.id())
                    .rule(BucketOwnershipControlsRuleArgs.builder()
                        .objectOwnership("ObjectWriter")
                        .build())
                    .build());
    
                var publicAccessBlock = new BucketPublicAccessBlock("public-access-block", BucketPublicAccessBlockArgs.builder()
                    .bucket(bucket.id())
                    .blockPublicAcls(false)
                    .build());
    
                var bucketMetric = new BucketMetric("my-bucket-metric", BucketMetricArgs.builder()
                    .bucket(bucket.id())
                    .build());
    
                var bucketNotification = new BucketNotification("my-bucket-notification", BucketNotificationArgs.builder()
                    .bucket(bucket.id())
                    .build());
    
                var bucketObject = new BucketObject("my-bucket-object", BucketObjectArgs.builder()
                    .bucket(bucket.id())
                    .content("hello world")
                    .build(), CustomResourceOptions.builder()
                    .dependsOn(publicAccessBlock, ownershipControls)
                    .build());
    
                var bucketPolicy = new BucketPolicy("my-bucket-policy", BucketPolicyArgs.builder()
                    .bucket(bucket.id())
                    .policy(bucket.id().applyValue(App::publicReadPolicyForBucket))
                    .build(), CustomResourceOptions.builder()
                    .dependsOn(publicAccessBlock, ownershipControls)
                    .build());
            });
        }
    
        private static String publicReadPolicyForBucket(String bucketName) {
            return String.format(serializeJson(
                jsonObject(
                    jsonProperty("Version", "2012-10-17"),
                    jsonProperty("Statement", jsonArray(jsonObject(
                        jsonProperty("Effect", "Allow"),
                        jsonProperty("Action", "s3:GetObject"),
                        jsonProperty("Principal", "*"),
                        jsonProperty("Resource", "arn:aws:s3:::%s/*")
                    )))
                )), bucketName);
        }
    }
    
    name: aws-s3-bucket-resources-yaml
    runtime: yaml
    description: An example that deploys S3 bucket, metric, notification, object, and policy resources.
    
    resources:
      my-bucket:
        type: aws:s3:Bucket
        properties: {}
    
      ownership-controls:
        type: aws:s3:BucketOwnershipControls
        properties:
          bucket: ${my-bucket.id}
          rule:
            objectOwnership: ObjectWriter
    
      public-access-block:
        type: aws:s3:BucketPublicAccessBlock
        properties:
          bucket: ${my-bucket.id}
          blockPublicAcls: false
    
      my-bucket-metric:
        type: aws:s3:BucketMetric
        properties:
          bucket: ${my-bucket.id}
    
      my-bucket-notification:
        type: aws:s3:BucketNotification
        properties:
          bucket: ${my-bucket.id}
    
      my-bucket-object:
        type: aws:s3:BucketObject
        properties:
          bucket: ${my-bucket.id}
          content: hello world
        options:
          dependsOn:
            - ${public-access-block}
            - ${ownership-controls}
    
      my-bucket-policy:
        type: aws:s3:BucketPolicy
        properties:
          bucket: ${my-bucket.id}
          policy:
            fn::toJSON:
              Version: "2012-10-17"
              Statement:
                - Effect: Allow
                  Principal: "*"
                  Action: "s3:GetObject"
                  Resource: "arn:aws:s3:::${my-bucket.id}/*"
        options:
          dependsOn:
            - ${public-access-block}
            - ${ownership-controls}
    

    Create an SQS queue

    This example provisions an Amazon SQS queue.

    import * as aws from "@pulumi/aws";
    
    const queue = new aws.sqs.Queue("myqueue");
    

    Create an SNS topic and subscription

    This example provisions an Amazon SNS topic an SQS queue, then subscribes the queue to the SNS topic, enabling messages published to the topic to be delivered to the queue.

    import * as aws from "@pulumi/aws";
    
    const topic = new aws.sns.Topic("mytopic");
    const queue = new aws.sqs.Queue("myqueue");
    
    const topicSubscription = new aws.sns.TopicSubscription("mytopicsubscription", {
        topic: topic,
        protocol: "sqs",
        endpoint: queue.arn,
    });
    
      PulumiUP 2024. Watch On Demand.