Deploying a EC2 Instance with PowerShell to AWS

Share on:

Previously, I covered how to Deploy and Bootstrap an EC2 Instance in AWS using Terraform. Not everyone may use Terraform, but quite a few people are using PowerShell today. Lets take a Look at how we can use AWSPowerShell to deploy an EC2 instance in AWS.


PowerShell is a great tool when it comes to creating scripts as there are so many packages in the PowerShell Gallery. PowerShell has been my scripting language of choice for quite some time, and it made perfect sense to create a script to deploy EC2 instances with PowerShell for those that may not be familiar with Terraform.



  • This is used to automate the provisioning.

AWSPowerShell Module

  • This is the module that contains the cmdlets we need. Can be installed using Install-Module -Name AWSPowerShell

Amazon Web Services Account

  • This is the infrastructure to run the EC2 virtual machines.

Terraform Variables Configuration

Download the sample script from GitHub and update the variables for your environment. This includes the Vault Token and Secret Name, and the AWS Region, AMI, Instance Type, VPC Security Groups, Subnet ID, KeyPair and Instance Name.

 2$AccessKey = "YOURACCESSKEY"
 3$SecretAccessKey = "YOURSECRETKEY"
 5$NameTag = @{ Key="Name"; Value="INSTANCENAME" }
 6$TagSpec = New-Object Amazon.EC2.Model.TagSpecification
 7$TagSpec.ResourceType = "instance"
 9$UserDataScript = Get-Content -Raw <PATH TO .TXT WITH SCRIPT TO RUN>
10$UserData = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($UserDataScript))
12$EC2InstanceDeploymentParameters = @{
13    ImageId = "ami-id"
14    InstanceType = "t2.micro"
15    SecurityGroupId = "sg-id","sg-id2","sg-id3"
16    SubnetId = "subnet-id"
17    KeyName = "keypair"
18    MinCount = "1"
19    MaxCount = "1"
20    Region = "us-west-2"
21    TagSpecification = $TagSpec
22    UserData = $UserData

Here is an example RAW Script file containing text to run. This exampler will start the msiscsi and custom name the IQN. if persist is true it will run on every restart, if you want it to run once, set persist to false.

2if (((Get-WindowsFeature Multipath-io).InstallState) -like "Available") {
3    Set-Service -Name msiscsi -StartupType Automatic
4    Start-Service -Name msiscsi
5    Set-InitiatorPort -NodeAddress (Get-InitiatorPort).NodeAddress -NewNodeAddress ""
6    Add-WindowsFeature -Name 'Multipath-IO' -Restart

Save and Run the Script


If everything is successful your EC2 instance should be deployed in ~ 2minutes and after a reboot or two will be fully configured and running!


Hopefully this has helped you add another deployment method to your toolbelt and get deployments automated with PowerShell!

Any questions or comments? Leave them below.

comments powered by Disqus

See Also