How to Deploy a Windows Server EC2 Instance in AWS using Terraform

Guillermo Musumeci
7 min readFeb 18, 2022

--

In this story, we will learn how to deploy a Windows Server EC2 Instance (VM) in AWS using Terraform.

Prerequisite #1: AWS Credentials

Before creating our AWS EC2 Instance, we will need AWS Credentials to execute our Terraform code.

The AWS provider offers a few options of providing credentials for authentication:

  • Static credentials
  • Environment variables
  • Shared credentials/configuration file

For this story, we will use static credentials. Please refer to the How to create an IAM account and configure Terraform to use AWS static credentials? story, if you need help to create the credentials.

Note: Using static credentials are great for learning and testing however hard-coded credentials are not recommended in production environments. Never push hard-coded credentials to code repositories.

Prerequisite #2: AWS Key Pair

We will need an AWS Key Pair, consisting of a public key and a private key. The AWS Key Pair is a set of security credentials that we need to connect to an Amazon EC2 instance.

Amazon EC2 stores the public key on our instance, and we store the private key. For Windows instances, the private key allows us to obtain the administrator password and then log in the EC2 Instance using RDP.

We can create the AWS Key Pair using the AWS Console, AWS CLI, or PowerShell. The instructions are at the Amazon EC2 key pairs and Windows instances official documentation.

A better way is using Terraform to create the AWS Key Pair. First, we will need to create a file called “key-pair-main.tf”, and we add the following code:

# Generates a secure private key and encodes it as PEM
resource "tls_private_key" "key_pair" {
algorithm = "RSA"
rsa_bits = 4096
}
# Create the Key Pair
resource "aws_key_pair" "key_pair" {
key_name = "windows-key-pair"
public_key = tls_private_key.key_pair.public_key_openssh
}
# Save file
resource "local_file" "ssh_key" {
filename =…

--

--

Guillermo Musumeci

Certified AWS, Azure & GCP Architect | HashiCorp Ambassador | Terraform SME | KopiCloud Founder | ex-AWS | Entrepreneur | Book Author | Husband & Dad of ✌