Wednesday 29 March 2017

AWS - Custom Windows AMI configured via Powershell Script in S3

This post will outline the approach to create a custom Windows AMI which can be used to serve IIS based Web applications.
The actual contents can be deployed at startup using a UserData or Custom Script loaded in S3 bucket.

The External script in S3 gives us flexibility to modify and deploy new configuration easily without touching the AMI instances.

Powershell Script to be deployed in Windows AMI
Invoke-WebRequest -Uri "https://s3.amazonaws.com/<bucketname>/<scriptname>Demo_Script.ps1" -OutFile .\S3-Script.ps1
./S3-Script.ps1 "parameter IIS_Demo_Script"

Save this file as script.ps1 and then create a Task in Windows Task Scheduler to be triggered at Startup which can execute without even a user logging in.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -File C:\bootstrap.ps1

In S3, you can create powershell script which can be used for generating let's say Index.html file or registering new IIS Site and copying content.

Following script set custom background color for instance and pick Hostname from Metadata URL, so for Autoscaling scenario, you can easily identify that data is served from which instance.

echo "<!DOCTYPE html><html lang='en'><body style='background-color:" > C:\inetpub\wwwroot\index.html
($a = "INDIANRED", "LIGHTCORAL", "SALMON", "DARKSALMON", "LIGHTSALMON", "CRIMSON", "RED", "ANTIQUEWHITE", "LINEN", "LAVENDERBLUSH", "MISTYROSE", "GAINSBORO", "LIGHTGRAY", "SILVER", "DARK
GRAY", "GRAY", "DIMGRAY", "LIGHTSLATEGRAY", "SLATEGRAY", "DARKSLATEGRAY") | Get-Random >> C:\inetpub\wwwroot\index.html
echo "'><div align='center'><h1>" >> C:\inetpub\wwwroot\index.html
invoke-restmethod -uri http://169.254.169.254/latest/meta-data/public-hostname >> C:\inetpub\wwwroot\index.html
echo "</h1><br/><br/><video width='800' height='600' <align='middle' controls><source src='https://<s3-bucket-url>/example/video.mp4' type='video/mp4'>Your browser does not support the video tag.</video></div></body></html>" >> C:\inetpub\wwwroot\index.html

No comments:

Post a Comment