Search code examples
amazon-web-servicesamazon-ec2windows-server-2012

AWS EC2 - Run a Script on Instance Launch With Windows Server 2012


I would like to run a script to clear out a folder (ie: C:/myfolder) on Windows Server 2012. I thought about adding an item to the Startup Scripts list under Edit Group Policy, but this would clear out my folder any time any of my servers rebooted. I only want the folder cleared out on a new instance launch from an existing AMI.

What's the best way to achieve this?


Solution

  • The best way to achieve this is EC2 User Data, which is essentially a user-defined script that is executed during instance launch. On Windows, you can run user data as cmd or powershell. User Data is provided when you make a request to launch a new instance.

    The existing AMI needs to be configured to run user data at launch. This can be managed from the EC2 Config Service, which Amazon provides pre-installed on community AMIs of Windows Server 2012. By default, the EC2 Config Service will execute the user data during the first launch, and then set itself to not execute user data again unless you manually change it to do so.

    Here's an example from the AWS documentation where the caller is invoking Rename-Computer via powershell:

    EC2 User Data during instance configuration

    To empty out the folder without deleting the folder itself, your script will probably look something like this:

    <powershell>
    Remove-Item "C:\myfolder\*" -Force -Recurse
    </powershell>
    

    When running user data, it is important to be aware of what the cmdlets you're executing do, and particularly when to use the -Force flag to skip interactive prompts. Some cmdlets will situationally ask the client for input, and when you're executing user data that will cause your script to hang because this is being executed by the system user during startup.