Virtual Machine on AWS
The AWS Virtual Machine template scaffolds a Pulumi project that provisions an Amazon EC2 instance running Amazon Linux 2023 inside a new Amazon VPC. The instance boots a small Python HTTP server on port 80 from user data, so the project deploys end to end out of the box. Use it as a starting point for a web application, backend service, or database VM.
Before you begin#
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
- A current version of Go installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
- A current version of .NET installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
For this walkthrough, you'll need:
- A current version of the Pulumi CLI (Pulumi HCL requires no additional runtime)
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage Amazon EC2 and VPC resources
Create a new project#
Create a new project from the template:
mkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-typescriptmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-typescriptmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-pythonmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-pythonmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-gomkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-gomkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-csharpmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-csharpmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-yamlmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-yamlmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-hclmkdir my-virtual-machine; cd my-virtual-machinepulumi new vm-aws-hclThe pulumi new command walks you through creating and configuring the new project and stack. A stack is an instance of a project, and you can have many of them (dev, staging, prod), each with its own configuration settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.
This template’s settings include:
| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instanceType | The Amazon EC2 instance type | t3.micro |
| vpcNetworkCidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instanceType <value>pulumi config set vpcNetworkCidr <value>pulumi config set aws:region "<value>"pulumi config set instanceType "<value>"pulumi config set vpcNetworkCidr "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instanceType | The Amazon EC2 instance type | t3.micro |
| vpcNetworkCidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instanceType <value>pulumi config set vpcNetworkCidr <value>pulumi config set aws:region "<value>"pulumi config set instanceType "<value>"pulumi config set vpcNetworkCidr "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instanceType | The Amazon EC2 instance type | t3.micro |
| vpcNetworkCidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instanceType <value>pulumi config set vpcNetworkCidr <value>pulumi config set aws:region "<value>"pulumi config set instanceType "<value>"pulumi config set vpcNetworkCidr "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instanceType | The Amazon EC2 instance type | t3.micro |
| vpcNetworkCidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instanceType <value>pulumi config set vpcNetworkCidr <value>pulumi config set aws:region "<value>"pulumi config set instanceType "<value>"pulumi config set vpcNetworkCidr "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instanceType | The Amazon EC2 instance type | t3.micro |
| vpcNetworkCidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instanceType <value>pulumi config set vpcNetworkCidr <value>pulumi config set aws:region "<value>"pulumi config set instanceType "<value>"pulumi config set vpcNetworkCidr "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
| instance_type | The Amazon EC2 instance type | t3.micro |
| vpc_network_cidr | The network CIDR to use for the VPC | 10.0.0.0/16 |
| service_port | The HTTP service port to expose on the VM | 80 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set instance_type <value>pulumi config set vpc_network_cidr <value>pulumi config set service_port <value>pulumi config set aws:region "<value>"pulumi config set instance_type "<value>"pulumi config set vpc_network_cidr "<value>"pulumi config set service_port "<value>"Review the code#
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the resources it declares.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
Take a moment to open them up and have a look. Here’s what’s in index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
import * as pulumi from "@pulumi/pulumi";import * as aws from "@pulumi/aws";
// Get some configuration values or set default values.const config = new pulumi.Config();const instanceType = config.get("instanceType") || "t3.micro";const vpcNetworkCidr = config.get("vpcNetworkCidr") || "10.0.0.0/16";
// Look up the latest Amazon Linux 2023 AMI.const ami = aws.ec2.getAmi({ filters: [{ name: "name", values: ["al2023-ami-2023.*-x86_64"], }], owners: ["amazon"], mostRecent: true,}).then(invoke => invoke.id);
// User data to start a HTTP server in the EC2 instanceconst userData = `#!/bin/bashecho "Hello, World from Pulumi!" > index.htmlnohup python3 -m http.server 80 &`;
// Create VPC.const vpc = new aws.ec2.Vpc("vpc", { cidrBlock: vpcNetworkCidr, enableDnsHostnames: true, enableDnsSupport: true,});
// 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 routeTable = new aws.ec2.RouteTable("routeTable", { 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("routeTableAssociation", { subnetId: subnet.id, routeTableId: routeTable.id,});
// Create a security group allowing inbound access over port 80 and outbound// access to anywhere.const secGroup = new aws.ec2.SecurityGroup("secGroup", { description: "Enable HTTP access", vpcId: vpc.id, ingress: [{ fromPort: 80, toPort: 80, protocol: "tcp", cidrBlocks: ["0.0.0.0/0"], }], egress: [{ fromPort: 0, toPort: 0, protocol: "-1", cidrBlocks: ["0.0.0.0/0"], }],});
// Create and launch an EC2 instance into the public subnet.const server = new aws.ec2.Instance("server", { instanceType: instanceType, subnetId: subnet.id, vpcSecurityGroupIds: [secGroup.id], userData: userData, ami: ami, tags: { Name: "webserver", },});
// Export the instance's publicly accessible IP address and hostname.export const ip = server.publicIp;export const hostname = server.publicDns;export const url = pulumi.interpolate`http://${server.publicDns}`;import pulumiimport pulumi_aws as aws
# Get some configuration values or set default values.config = pulumi.Config()instance_type = config.get("instanceType")if instance_type is None: instance_type = "t3.micro"vpc_network_cidr = config.get("vpcNetworkCidr")if vpc_network_cidr is None: vpc_network_cidr = "10.0.0.0/16"
# Look up the latest Amazon Linux 2023 AMI.ami = aws.ec2.get_ami( filters=[ { "name": "name", "values": ["al2023-ami-2023.*-x86_64"], } ], owners=["amazon"], most_recent=True,).id
# User data to start a HTTP server in the EC2 instanceuser_data = """#!/bin/bashecho "Hello, World from Pulumi!" > index.htmlnohup python3 -m http.server 80 &"""
# Create VPC.vpc = aws.ec2.Vpc( "vpc", cidr_block=vpc_network_cidr, enable_dns_hostnames=True, enable_dns_support=True,)
# 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.route_table = aws.ec2.RouteTable( "routeTable", vpc_id=vpc.id, routes=[ { "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( "routeTableAssociation", subnet_id=subnet.id, route_table_id=route_table.id)
# Create a security group allowing inbound access over port 80 and outbound# access to anywhere.sec_group = aws.ec2.SecurityGroup( "secGroup", description="Enable HTTP access", vpc_id=vpc.id, ingress=[ { "from_port": 80, "to_port": 80, "protocol": "tcp", "cidr_blocks": ["0.0.0.0/0"], } ], egress=[ { "from_port": 0, "to_port": 0, "protocol": "-1", "cidr_blocks": ["0.0.0.0/0"], } ],)
# Create and launch an EC2 instance into the public subnet.server = aws.ec2.Instance( "server", instance_type=instance_type, subnet_id=subnet.id, vpc_security_group_ids=[sec_group.id], user_data=user_data, ami=ami, tags={ "Name": "webserver", },)
# Export the instance's publicly accessible IP address and hostname.pulumi.export("ip", server.public_ip)pulumi.export("hostname", server.public_dns)pulumi.export("url", server.public_dns.apply(lambda public_dns: f"http://{public_dns}"))package main
import ( "fmt" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/ec2" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" "github.com/pulumi/pulumi/sdk/v3/go/pulumi/config")
func main() { pulumi.Run(func(ctx *pulumi.Context) error { // Get some configuration values or set default values. cfg := config.New(ctx, "") instanceType := "t3.micro" if param := cfg.Get("instanceType"); param != "" { instanceType = param } vpcNetworkCidr := "10.0.0.0/16" if param := cfg.Get("vpcNetworkCidr"); param != "" { vpcNetworkCidr = param }
// Look up the latest Amazon Linux 2023 AMI. ami, err := ec2.LookupAmi(ctx, &ec2.LookupAmiArgs{ Filters: []ec2.GetAmiFilter{ ec2.GetAmiFilter{ Name: "name", Values: []string{ "al2023-ami-2023.*-x86_64", }, }, }, Owners: []string{ "amazon", }, MostRecent: pulumi.BoolRef(true), }, nil) if err != nil { return err }
// User data to start a HTTP server in the EC2 instance userData := "#!/bin/bash\necho \"Hello, World from Pulumi!\" > index.html\nnohup python3 -m http.server 80 &\n"
// Create VPC. vpc, err := ec2.NewVpc(ctx, "vpc", &ec2.VpcArgs{ CidrBlock: pulumi.String(vpcNetworkCidr), EnableDnsHostnames: pulumi.Bool(true), EnableDnsSupport: pulumi.Bool(true), }) 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. routeTable, err := ec2.NewRouteTable(ctx, "routeTable", &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, "routeTableAssociation", &ec2.RouteTableAssociationArgs{ SubnetId: subnet.ID(), RouteTableId: routeTable.ID(), }) if err != nil { return err }
// Create a security group allowing inbound access over port 80 and outbound // access to anywhere. secGroup, err := ec2.NewSecurityGroup(ctx, "secGroup", &ec2.SecurityGroupArgs{ Description: pulumi.String("Enable HTTP access"), VpcId: vpc.ID(), Ingress: ec2.SecurityGroupIngressArray{ &ec2.SecurityGroupIngressArgs{ FromPort: pulumi.Int(80), ToPort: pulumi.Int(80), Protocol: pulumi.String("tcp"), CidrBlocks: pulumi.StringArray{ pulumi.String("0.0.0.0/0"), }, }, }, Egress: ec2.SecurityGroupEgressArray{ &ec2.SecurityGroupEgressArgs{ FromPort: pulumi.Int(0), ToPort: pulumi.Int(0), Protocol: pulumi.String("-1"), CidrBlocks: pulumi.StringArray{ pulumi.String("0.0.0.0/0"), }, }, }, }) if err != nil { return err }
// Create and launch an EC2 instance into the public subnet. server, err := ec2.NewInstance(ctx, "server", &ec2.InstanceArgs{ InstanceType: pulumi.String(instanceType), SubnetId: subnet.ID(), VpcSecurityGroupIds: pulumi.StringArray{ secGroup.ID(), }, UserData: pulumi.String(userData), Ami: pulumi.String(ami.Id), Tags: pulumi.StringMap{ "Name": pulumi.String("webserver"), }, }) if err != nil { return err }
// Export the instance's publicly accessible IP address and hostname. ctx.Export("ip", server.PublicIp) ctx.Export("hostname", server.PublicDns) ctx.Export("url", server.PublicDns.ApplyT(func(publicDns string) (string, error) { return fmt.Sprintf("http://%v", publicDns), nil }).(pulumi.StringOutput)) return nil })}using System.Collections.Generic;using Pulumi;using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>{ // Get some configuration values or set default values. var config = new Config(); var instanceType = config.Get("instanceType") ?? "t3.micro"; var vpcNetworkCidr = config.Get("vpcNetworkCidr") ?? "10.0.0.0/16";
// Look up the latest Amazon Linux 2023 AMI. var ami = Aws.Ec2.GetAmi.Invoke(new() { Filters = new[] { new Aws.Ec2.Inputs.GetAmiFilterInputArgs { Name = "name", Values = new[] { "al2023-ami-2023.*-x86_64", }, }, }, Owners = new[] { "amazon", }, MostRecent = true, }).Apply(invoke => invoke.Id);
// User data to start a HTTP server in the EC2 instance var userData = @"#!/bin/bash echo ""Hello, World from Pulumi!"" > index.html nohup python3 -m http.server 80 & ";
// Create VPC. var vpc = new Aws.Ec2.Vpc("vpc", new() { CidrBlock = vpcNetworkCidr, EnableDnsHostnames = true, EnableDnsSupport = true, });
// Create an internet gateway. var gateway = new Aws.Ec2.InternetGateway("gateway", new() { VpcId = vpc.Id, });
// Create a subnet that automatically assigns new instances a public IP address. var subnet = new Aws.Ec2.Subnet("subnet", new() { VpcId = vpc.Id, CidrBlock = "10.0.1.0/24", MapPublicIpOnLaunch = true, });
// Create a route table. var routeTable = new Aws.Ec2.RouteTable("routeTable", new() { VpcId = vpc.Id, Routes = new[] { new Aws.Ec2.Inputs.RouteTableRouteArgs { CidrBlock = "0.0.0.0/0", GatewayId = gateway.Id, }, }, });
// Associate the route table with the public subnet. var routeTableAssociation = new Aws.Ec2.RouteTableAssociation("routeTableAssociation", new() { SubnetId = subnet.Id, RouteTableId = routeTable.Id, });
// Create a security group allowing inbound access over port 80 and outbound // access to anywhere. var secGroup = new Aws.Ec2.SecurityGroup("secGroup", new() { Description = "Enable HTTP access", VpcId = vpc.Id, Ingress = new[] { new Aws.Ec2.Inputs.SecurityGroupIngressArgs { FromPort = 80, ToPort = 80, Protocol = "tcp", CidrBlocks = new[] { "0.0.0.0/0", }, }, }, Egress = new[] { new Aws.Ec2.Inputs.SecurityGroupEgressArgs { FromPort = 0, ToPort = 0, Protocol = "-1", CidrBlocks = new[] { "0.0.0.0/0", }, }, }, });
// Create and launch an EC2 instance into the public subnet. var server = new Aws.Ec2.Instance("server", new() { InstanceType = instanceType, SubnetId = subnet.Id, VpcSecurityGroupIds = new[] { secGroup.Id, }, UserData = userData, Ami = ami, Tags = { { "Name", "webserver" }, }, });
// Export the instance's publicly accessible IP address and hostname. return new Dictionary<string, object?> { ["ip"] = server.PublicIp, ["hostname"] = server.PublicDns, ["url"] = server.PublicDns.Apply(publicDns => $"http://{publicDns}"), };});name: my-projectdescription: A Pulumi YAML program to deploy a virtual machine on Amazon EC2runtime: yaml
template: description: A Pulumi YAML program to deploy a virtual machine on Amazon EC2 config: aws:region: description: The AWS region to deploy into default: us-west-2 instanceType: description: The Amazon EC2 instance type default: t3.micro vpcNetworkCidr: description: The network CIDR to use for the VPC default: 10.0.0.0/16
config: instanceType: type: string default: t3.micro vpcNetworkCidr: type: string default: 10.0.0.0/16
resources: # Create VPC. vpc: type: aws:ec2:Vpc properties: cidrBlock: ${vpcNetworkCidr} enableDnsHostnames: true enableDnsSupport: true # Create an internet gateway. gateway: type: aws:ec2:InternetGateway properties: vpcId: ${vpc.id} # Create a subnet that automatically assigns new instances a public IP address. subnet: type: aws:ec2:Subnet properties: vpcId: ${vpc.id} cidrBlock: 10.0.1.0/24 mapPublicIpOnLaunch: true # Create a route table. routeTable: type: aws:ec2:RouteTable properties: vpcId: ${vpc.id} routes: - cidrBlock: 0.0.0.0/0 gatewayId: ${gateway.id} # Associate the route table with the public subnet. routeTableAssociation: type: aws:ec2:RouteTableAssociation properties: subnetId: ${subnet.id} routeTableId: ${routeTable.id} # Create a security group allowing inbound access over port 80 and outbound # access to anywhere. secGroup: type: aws:ec2:SecurityGroup properties: description: Enable HTTP access vpcId: ${vpc.id} ingress: - fromPort: 80 toPort: 80 protocol: tcp cidrBlocks: - 0.0.0.0/0 egress: - fromPort: 0 toPort: 0 protocol: -1 cidrBlocks: - 0.0.0.0/0 # Create and launch an EC2 instance into the public subnet. server: type: aws:ec2:Instance properties: instanceType: ${instanceType} subnetId: ${subnet.id} vpcSecurityGroupIds: - ${secGroup} userData: ${userData} ami: ${ami} tags: Name: webserver
variables: # Look up the latest Amazon Linux 2023 AMI. ami: fn::invoke: function: aws:ec2:getAmi arguments: filters: - name: name values: - "al2023-ami-2023.*-x86_64" owners: - "amazon" mostRecent: true return: id # User data to start a HTTP server in the EC2 instance userData: | #!/bin/bash echo "Hello, World from Pulumi!" > index.html nohup python3 -m http.server 80 &
# Export the instance's publicly accessible IP address and hostname.outputs: ip: ${server.publicIp} hostname: ${server.publicDns} url: http://${server.publicDns}terraform { required_providers { aws = { source = "pulumi/aws" } }}
variable "instance_type" { description = "The Amazon EC2 instance type" type = string default = "t3.micro"}
variable "vpc_network_cidr" { description = "The network CIDR to use for the VPC" type = string default = "10.0.0.0/16"}
variable "service_port" { description = "The HTTP service port to expose on the VM" type = number default = 80}
locals { user_data = <<-EOF #!/bin/bash echo "Hello, World from Pulumi!" > index.html nohup python3 -m http.server ${var.service_port} & EOF}
# Look up the latest Amazon Linux 2023 AMI.data "aws_ec2_ami" "amazon_linux" { most_recent = true owners = ["amazon"]
filters { name = "name" values = ["al2023-ami-2023.*-x86_64"] }}
# Create VPC.resource "aws_ec2_vpc" "vpc" { cidr_block = var.vpc_network_cidr enable_dns_hostnames = true enable_dns_support = true}
# Create an internet gateway.resource "aws_ec2_internet_gateway" "gateway" { vpc_id = aws_ec2_vpc.vpc.id}
# Create a subnet that automatically assigns new instances a public IP address.resource "aws_ec2_subnet" "subnet" { vpc_id = aws_ec2_vpc.vpc.id cidr_block = "10.0.1.0/24" map_public_ip_on_launch = true}
# Create a route table.resource "aws_ec2_route_table" "route-table" { vpc_id = aws_ec2_vpc.vpc.id
routes { cidr_block = "0.0.0.0/0" gateway_id = aws_ec2_internet_gateway.gateway.id }}
# Associate the route table with the public subnet.resource "aws_ec2_route_table_association" "route-table-association" { subnet_id = aws_ec2_subnet.subnet.id route_table_id = aws_ec2_route_table.route-table.id}
# Create a security group allowing inbound access over port 80 and outbound# access to anywhere.resource "aws_ec2_security_group" "sec-group" { description = "Enable HTTP access" vpc_id = aws_ec2_vpc.vpc.id
ingress { from_port = var.service_port to_port = var.service_port protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] }
egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }}
# Create and launch an EC2 instance into the public subnet.resource "aws_ec2_instance" "server" { instance_type = var.instance_type subnet_id = aws_ec2_subnet.subnet.id vpc_security_group_ids = [aws_ec2_security_group.sec-group.id] user_data = local.user_data ami = data.aws_ec2_ami.amazon_linux.id
tags = { Name = "webserver" }}
# Export the instance's publicly accessible IP address and hostname.output "ip" { value = aws_ec2_instance.server.public_ip}
output "hostname" { value = aws_ec2_instance.server.public_dns}
output "url" { value = "http://${aws_ec2_instance.server.public_dns}:${var.service_port}"}Deploy the project#
Deploy with pulumi up. It starts with a preview of what it’s about to create and asks before it changes anything. Choose yes to deploy.
pulumi uppulumi upPulumi adds a random suffix to most resource names, so the security group’s name ends in something like -4f8a2c1. This is autonaming. It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.
When it finishes, Pulumi prints the stack’s outputs, values it only knows once the resources exist:
- ip
The IP address of the EC2 instance.
- hostname
The provider-assigned hostname of the EC2 instance.
- url
The fully-qualified HTTP URL of the HTTP server running on the EC2 instance.
Read one any time with pulumi stack output <name>, or pass it to another command. This opens the instance’s web page in your browser:
open $(pulumi stack output url)xdg-open $(pulumi stack output url)Start-Process $(pulumi stack output url)To check it from the terminal, fetch the page with curl. It prints Hello, World from Pulumi!. The web server starts as the instance boots, so if curl can’t connect, wait a minute and try again:
curl $(pulumi stack output url)curl.exe $(pulumi stack output url)Need help?
If pulumi up reports No valid credential sources found or ExpiredToken, sign in again:
aws loginaws loginStill stuck? Let us know.
Customize the project#
Projects created with this template expose the following configuration settings:
- instanceType
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpcNetworkCidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.
- instanceType
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpcNetworkCidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.
- instanceType
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpcNetworkCidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.
- instanceType
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpcNetworkCidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.
- instanceType
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpcNetworkCidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.
- instance_type
The EC2 instance type to use for the VM. Defaults to
t3.micro.- vpc_network_cidr
The network CIDR to use for the VPC. Defaults to
10.0.0.0/16.- service_port
The HTTP service port to expose on the VM. Defaults to
80.
All of these settings are optional and may be adjusted either by editing the stack configuration file directly (by default, Pulumi.dev.yaml) or by changing their values with pulumi config set.
Adding a tag#
Tags are key-value labels you can search and filter instances by. The template already tags it Name: webserver. Add an Environment tag in index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
const server = new aws.ec2.Instance("server", { // ... tags: { Name: "webserver", Environment: "dev", },});server = aws.ec2.Instance( "server", # ... tags={ "Name": "webserver", "Environment": "dev", },)server, err := ec2.NewInstance(ctx, "server", &ec2.InstanceArgs{ // ... Tags: pulumi.StringMap{ "Name": pulumi.String("webserver"), "Environment": pulumi.String("dev"), },})var server = new Aws.Ec2.Instance("server", new(){ // ... Tags = { { "Name", "webserver" }, { "Environment", "dev" }, },});server: type: aws:ec2:Instance properties: # ... tags: Name: webserver Environment: devresource "aws_ec2_instance" "server" { # ... tags = { Name = "webserver" Environment = "dev" }}Deploy it. The preview shows the instance as an update. EC2 adds tags without replacing or restarting it, so url keeps working. Then ask EC2 for the tags on the instance at the stack’s IP address; Environment is now in the list:
pulumi upaws ec2 describe-instances --region $(pulumi config get aws:region) --filters "Name=ip-address,Values=$(pulumi stack output ip)" --query "Reservations[].Instances[].Tags" --output tablepulumi upaws ec2 describe-instances --region $(pulumi config get aws:region) --filters "Name=ip-address,Values=$(pulumi stack output ip)" --query "Reservations[].Instances[].Tags" --output tableTo see what else you can add, browse the AWS provider in the Pulumi Registry.
Cleaning up#
You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:
pulumi destroypulumi destroyLearn more#
- Browse other architecture templates in the Templates gallery.
- Explore the AWS provider API docs in the Pulumi Registry.
- Walk through Pulumi from the ground up in Pulumi Tutorials.
- Read the latest AWS posts on the Pulumi blog.