Skip to main content
Menu
Terraform Script to Provision Windows Server | Cheatsheets
Terraform Script to Provision Windows Server

Terraform Script to Provision Windows Server

January 16, 2020
devops
terraform

File Structure #

── windows-server-tf/
    ├── key.tf
    ├── provider.tf
    ├── test.txt
    ├── vars.tf
    ├── versions.tf
    └── windows.tf

key.tf file #

resource "aws_key_pair" "windows-key" {
  key_name   = "windows-key"
  public_key = file(var.PATH_TO_PUBLIC_KEY)
}

provider.tf file #

provider "aws" {
  region = var.AWS_REGION
}

test.txt file #

test file

vars.tf file #

variable "AWS_REGION" {
  default = "us-east-1"
}

variable "PATH_TO_PRIVATE_KEY" {
  default = "windows"
}

variable "PATH_TO_PUBLIC_KEY" {
  default = "windows.pub"
}

variable "INSTANCE_USERNAME" {
  default = "username"
}

variable "INSTANCE_PASSWORD" {
  default = "password"
}

versions.tf file #

terraform {
  required_version = ">= 0.12"
}

windows.tf file #

resource "aws_instance" "windows_server" {
  ami = "ami-07df9d1e2a40d2856"
  instance_type = "t2.micro"
  key_name = "windows-key"
  security_groups = [
    "${aws_security_group.allow_rdp.name}"]

  user_data = <<EOF
    <script>
    echo "" > _INIT_STARTED_
    net user ${var.INSTANCE_USERNAME} /add /y
    net user ${var.INSTANCE_USERNAME} ${var.INSTANCE_PASSWORD}
    net localgroup administrators ${var.INSTANCE_USERNAME} /add
    md C:\test
    echo ${base64encode(file("./test.txt"))} > tmp2.b64 && certutil -decode tmp2.b64 C:/test/test.txt
    echo "" > _INIT_COMPLETE_
    </script>
    <persist>false</persist>
    EOF
}

resource "aws_security_group" "allow_rdp" {
  name = "allow_rdp"
  description = "Allow rdp traffic"

  ingress {

    from_port = 3389
    #  By default, the windows server listens on TCP port 3389 for RDP
    to_port = 3389
    protocol = "tcp"

    cidr_blocks = [
      "0.0.0.0/0"]
  }
}

output "{{ user }}bastion_server" {
  value = aws_instance.{{ user }}devsecops-labs-bastion.public_ip
}

Generate SSH windows key #

ssh-keygen -m PEM -t rsa -b 4096 -C "your_email@example.com" -f windows

Terraform command #

terraform init
terraform plan
terraform apply  --auto-approve

Note: Please wait at least 4 minutes after launching an instance before trying to login using credential.

Destroy Instance #

terraform destroy --force