I want to run a custom script when I launch a new Amazon Elastic Compute Cloud (Amazon EC2) Windows instance.
Resolution
Prerequisite: Identify the launch agent that's installed on your EC2 instance based on your Windows Server version:
- For Windows Server 2012 and earlier, the launch agent is EC2Config.
- For Windows Server 2016 and 2019, the launch agent is EC2Launch.
- For Windows Server 2016, 2019, and 2022, the launch agent is EC2Launch v2.
Note: It's a best practice to use this launch agent for Amazon Machine Images (AMIs) that you created in mid-2021 or later.
Run the command at launch
To run a command at launch, update the instance's user data.
Use the launch wizard to launch the instance and expand Advanced details. For User data, enter your script. Make sure that you adhere to the user data script syntax.
To run the user data script each time that you reboot or restart the instance, add the following tags to the end of the script:
<persist>true</persist>
To run the user data script on existing instances, see How do I run a command on an existing Amazon EC2 Windows instance when I reboot or start the instance?
Troubleshoot issues
If you encounter issues, then check the standard output and standard error streams in the EC2Config, EC2Launch, or EC2Launch v2 log files.
To find the log files, check the following locations:
- For EC2Config, check C:\Program Files\Amazon\Ec2ConfigService\Logs\Ec2Config.log.
- For EC2Launch, check C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log.
- For EC2Launch v2, check C:\ProgramData\Amazon\EC2Launch\log\agent.log.
If the script ran once but not on reboot, then make sure that you added the tag to the script. Also, verify that you correctly configured the EC2 Launch v2 agent.
If the script didn't run, then make sure that you correctly saved the user data. If you use AWS Systems Manager, then make sure that you correctly configured AWS Identity and Access Management (IAM) permissions to your instance.
If the script ran but you received an error message, then check the log files for more information. Also, make sure that you configured the Windows PowerShell execution policy. For more information, see about_Execution_Policies on the Microsoft website.