EC2 and Automatic Scripts at Launch - Windows AMIs
In my previous entry, I talked about using user data scripts on Linux AMI's. For this one, let's talk about doing that with Windows AMI's.
For this example, I'm going to install a popular audio streaming program called Icecast. The end goal of this is to be able to launch a windows instance and have it auto install Icecast from an S3 bucket and a few other small tasks, entirely in PowerShell.
Here are the steps needed to perform this:
- Create an EC2 role that has access to S3, and optionally SNS.
- Upload your Icecast installer and any config files into the S3 bucket.
- Create a security group within EC2 that has access to the Icecast ports you desire.
Now here are the juicy bits - the user data execution script. Let's go through this line by line.
Read-S3Object -BucketName "your-bucket-name" -Key "icecast-2.4.0-kh12_win64_setup.exe" -File "C:\Users\Administrator\Desktop\icecast.exe"
Start-Process 'C:\Users\Administrator\Desktop\icecast.exe' "/S" -Wait
netsh advfirewall firewall add rule name="Open Port 80" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="Open Port 8000" dir=in action=allow protocol=TCP localport=8000
netsh advfirewall firewall add rule name="Open Port 8001" dir=in action=allow protocol=TCP localport=8001
netsh advfirewall firewall add rule name="Open Port 443" dir=in action=allow protocol=TCP localport=443
Start-Service Icecast
Set-DefaultAWSRegion -Region your-region-here
Publish-SNSMessage -TopicArn arn:aws:sns:TopicRegion:TopicID:TopicName -Message "Server Setup!" -Subject "Icecast Server Automation Complete"
Read-S3Object takes a bucket name and a file. It then downloads it to the location specified. So in this case, it takes the exe file from my S3 bucket and puts it on the desktop.
Start-Process starts the installer. the /S does it silently, while -Wait makes sure it installs before the script continues.
The netsh stuff opens up the ports on Windows firewall. Note that you need to also open the ports in your EC2 Security Group as well.
Start-Service Icecast starts the icecast service to begin listening for connections.
The lines below that are optional - they are to notify an SNS topic that the server is ready to go.
Starting an EC2 Instance and running the Script
The rest of this is pretty easy. You Start an EC2 Instance (make sure you assign the role for S3 access), and in the user data wrap the PowerShell script in a powershell tag. It should look like this.
<powershell>
your powershell lines here
</powershell>
If anything did not work as intended, you can check the logs within your instance at C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log.