Hackernoon logoSet Up a New AWS EC2 Instance From Scratch Using PowerShell by@adamtheautomator

Set Up a New AWS EC2 Instance From Scratch Using PowerShell

Author profile picture

@adamtheautomatorAdam Bertram

Adam is an online business professional, Microsoft MVP, blogger, trainer, and published author.

Creating an Amazon Web Services (AWS) instance with PowerShell requires creating the dependencies that PowerShell requires. Below, we will outline how to create these dependencies as well as the new-EC2instance itself!

The Network Stack

The first thing you’ll need to do is to create the VPC that the network stack needs. In the example below, we use a network of, which is a fairly big network. To create the VPC, you will use the New-EC2Vpc command with the CidrBlock parameter. You can then pass the network to the New-EC2Vpc command.

PS> $network = ''
PS> $vpc = New-EC2Vpc -CidrBlock $network
PS> $vpc

CidrBlock                   :
CidrBlockAssociationSet     : {vpc-cidr-assoc-03f1edbc052e8c207}
DhcpOptionsId               : dopt-3c9c3047
InstanceTenancy             : default
Ipv6CidrBlockAssociationSet : {}
IsDefault                   : False
State                       : pending
Tags                        : {}
VpcId                       : vpc-03e8c773094d52eb3

Once you’ve done this, you’ll have created a basic VPC!

Note that we’re using the Edit-EC2VpcAttribute commands below. You don’t have to use this command to create the basic VPC, but it can be used to enable DNS support and DNS host names. This allows the AWS to assign DNS names and lets the EC2 instance to resolve names.

PS> Edit-EC2VpcAttribute -VpcId $vpc.VpcId -EnableDnsSupport $true
PS> Edit-EC2VpcAttribute -VpcId $vpc.VpcId -EnableDnsHostnames $true

The Internet Gateway

Setting up the internet gateway is also not necessary to create an new-EC2instance, but it can be done to allow access to the instance from the internet. For those who use Windows, this is your default gateway. By using the New-EC2InternetGateway command shown below, you’ll create a way for your EC2 instance to access and be accessed online. Notice that there are no parameters to add to the command. It simply creates the internet gateway.

$gw = New-ECZInternetGateway

The following command creates an EC2 internet gateway. This command assigns the newly created internet gateway to the VPC so that the EC2 instance can access the internet.

Add-EC2InternetGateway -InternetGatewayId $gw.InternetGatewayId -VpcId $vpc.VpcId

Create a Default Route

Next, you have to create a routing table with a default route to the instance. Otherwise, even with the internet gateway assigned to the VPC, the new-EC2instance cannot actually access the internet. There must be a route for the instance to go online, so you must create the route and the route table. To do this, you first use the New-EC2RouteTable command and assign it to the $rt variable. That creates the routing table and links it to the VPC.

$rt = New-EC2RouteTable -VpcId $vpc.VpcId

Next, you’ll create a route within the route table. The parameters to include in the New-EC2Route command include the RouteTableID, the GatewayId, and the DestinationCidrBlock. For the default route, simply enter all zeros in the address of the CIDR block as shown below. Once this is done, all of the traffic from the EC2 instances connected to the VPC you created will be routed to the internet gateway.

New-EC2Route -RouteTableId $rt.RouteTab1eId ~GatewayId $gw.InternetGatewayId -DestinationCidrBlock ''

Create the Subnet

Next, you need to create the subnet. This assigns subnets to the IP addresses within the VPC.

$sn = New-EC2Subnet -VpcId $vpc.VpcId -CidrBlock '' -Avai1abi1ityZone 'us-east-ld'
Register-EC2RouteTab1e -RouteTab1eId $rt.RouteTab1eId -SubnetId $sn.SubnetId

You may notice that the parameters above include the availability zone. The EC2 subnet command requires this information, but you may not know what the availability zone is. You can find this information by running the Get-EC2AvailabilityZone command.

This command may return a few different available zones as shown below.

You can select whichever zone you’d like. In this case, it doesn’t matter.

Once you have the zone information, you can create the EC2 subnet with the command shown above. You’ll include your VPC ID and the CIDR Block of the VPC. In this example, the CIDR Block is That means the subnet will be Once this command is run with the required information, it will create a subnet object.

Once you’ve created the subnet, you have to register it with the route table you created earlier. To do that, you’ll need to use the Register-EC2RouteTable command. You will use the route table ID you created earlier and the subnet ID you just created.

Register-EC2RouteTabIe -RouteTableId $rt.RouteTableId -SubnetId $sn.SubnetId

Find the AMI or OS Image to Use

With the above commands finished, you’ve created your base network stack. Next, you have to find the AMI or OS image you want to use.

In this example, we’ll use the WINDOWS_SERVER_2016_BASE image. You can use a number of different platforms and operating systems, of course. To do that, you’ll use the Get-EC2ByImageName command.

When you run this command you’ll receive a list of various Windows images you can use.

In our example, we want to select the WINDOWS_SERVER_2016_BASE. We assigned it to the AMI using the following command:

$ami = Get-EC2ByImageByName -Name 'WINDOWS_2016_BASE'

With the AMI available and the entire network stack completed, it’s now time to create the instance.

Create the New-EC2Instance

To create the instance, you’ll use the New-EC2Instance command. Because of the way we’re creating the instance in our example, we’re not going to be associating a public IP to this instance.

For the instance type, we’re using a type T2 micro. You can’t easily find instance types using PowerShell, but you can go to the AWS resource site and find a document listing all of the available types.

$params = @{
    ImageId = $ami.ImageId
    AssociatePub1icIp = $false
    InstanceType = 't2.micro'
    SubnetId = $sn.SubnetId
 $instance = New-EC2Instance @params

Once you enter the ID of the subnet you created earlier, your instance is code is complete. You can run the code and create the instance.

Creating a Wait Function

Unfortunately, it can a while to create the instance, especially if you’re using a Windows image. You want to create a script that will monitor the process so you don’t have to check to see if the instance is available multiple times. This basic function will do that for you.

function Wait-EC2InstanceState {
    param (
        [int]$RetryInterval = 5
    $instanceId = $Instance.Instances.InstanceId
    while ((Get-EC2InstanceStatus -IncludeAllInstance $true -InstanceId $instanceId).InstanceState.Name.Value -ne $DesiredState) {
    Write-Verbose "Waiting for our instance to reach the state of [$($DesiredState)]..."
    Start-Sleep -Seconds $RetryInterval

This function basically runs the Get-EC2InstanceStatus command over and over until the instance is available.

Below is an example of how you can use this function.

Get-EC2Instance -InstanceId $instance.Instances.InstantId | Wait-EC2InstanceState -DesiredState running -Verbose

If the instance is stopped, the function will simply wait until it’s changed to running.

Bringing it All Together with New-EC2instance

Now it’s time to bring everything together! We’ll do this by creating a function called New-CustomEC2Instance.

While we won’t go into great detail about the function, there are a few things to point out. This function is available in GitHub. As you can see below, the Wait-EC2InstanceState function is embedded in the begin block. It’s a portable function that you can copy and paste wherever you need it.

A number of Get commands are needed in the New-CustomEC2Instance function. The function will check to see if all of these objects exist before it does anything. If they do not, it will create them. This allows you to run the process over and over again to create that accounts for the different states an AWS environment can be in.

For example, let’s run the code in the session we’ve been using:

When the EC2 instance was created, it notes that the subnet already exists and is registered with a VPC. It’s already waiting for the running state, too, which means the wait function created earlier is doing its job. You can confirm that the instance was created by going to your console.

If you like this article, be sure to check out all of the other how-to cloud computing articles on adamtheautomator.com!

Now you know how to quickly set up an AWS new-EC2instance with PowerShell!


Join Hacker Noon

Create your free account to unlock your custom reading experience.