Skip to main content

Search the Dev Center

Search tutorials, templates, examples, and more.

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.

Architecture diagram of the AWS Virtual Machine template AWS VPC Public Subnet Internet Gateway EC2 instance

Before you begin#

For this walkthrough, you'll need:

Create a new project#

Create a new project from the template:

Terminal window
mkdir my-virtual-machine; cd my-virtual-machine
pulumi new vm-aws-typescript

The 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:

KeyDescriptionDefault
aws:regionThe AWS region to deploy intous-west-2
instanceTypeThe Amazon EC2 instance typet3.micro
vpcNetworkCidrThe network CIDR to use for the VPC10.0.0.0/16
You can change values like these later with pulumi config set :
Terminal window
pulumi config set aws:region <value>
pulumi config set instanceType <value>
pulumi config set vpcNetworkCidr <value>

Review the code#

When setup completes, you’ll see a few files:

  • Pulumi.yaml contains the project name and the language it’s written in.
  • Pulumi.dev.yaml contains the dev stack’s settings, including the values you just entered.
  • index.ts contains 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.ts:

index.ts
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 instance
const userData = `#!/bin/bash
echo "Hello, World from Pulumi!" > index.html
nohup 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}`;

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.

Terminal window
pulumi up

Pulumi 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:

Terminal window
open $(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:

Terminal window
curl $(pulumi stack output url)
Need help?

If pulumi up reports No valid credential sources found or ExpiredToken, sign in again:

Terminal window
aws login

Still 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.

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.ts:

const server = new 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:

Terminal window
pulumi up
aws ec2 describe-instances --region $(pulumi config get aws:region) --filters "Name=ip-address,Values=$(pulumi stack output ip)" --query "Reservations[].Instances[].Tags" --output table

To 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:

Terminal window
pulumi destroy

Learn more#

Related

The infrastructure platform for humans and agents.