AWS Developer Tools Blog
Installing Scheduled Tasks on EC2 Windows Instances Using EC2 Run
Today’s guest post is the second part of the two part series by AWS Solutions Architect Russell Day. Part one can be found here.
In the previous post, we showed how to use the User data field to install Windows scheduled tasks automatically when Windows EC2 instances are launched. In this post, we will demonstrate how to do the same thing using the new EC2 Run Command, which provides a simple way to remotely execute PowerShell commands against EC2 instances.
Use the EC2 Run Command to Install scheduled tasks automatically
Just as we did in the previous post, we will demonstrate two methods for using the EC2 Run Command: the Amazon EC2 console and AWS Tools for PowerShell.
Use the EC2 console to execute the EC2 Run Command
- Complete steps 1 through 4 in the previous post.
- In the EC2 console, choose Commands.
- Choose the Run a command button.
- Under Command document, choose AWS-RunPowerShellScript.
- Select your target instances.
- Paste the PowerShell script from step 5 of the previous post into the Commands text box as shown.
- Leave all other fields at their defaults, and choose Run to invoke the PowerShell script on the target instances.
- You can monitor progress and view the output of the invoked scripts as shown.
Use PowerShell to Execute the EC2 Run Command
Alternatively, you can use PowerShell to invoke the EC2 Run Command as shown.
- If you have not already configured your PowerShell environment, follow these instructions to configure your PowerShell console to use the AWS Tools for Windows PowerShell.
- Save the PowerShell script from step 5 in the previous post as InstallWindowsTasks.ps1.
From a PowerShell session, simply replace ‘Instance-ID’ with the instance IDs of your target instances and provide the path to InstallWindowsTasks.ps1 as shown.
$runPSCommand=Send-SSMCommand
-InstanceId @('Instance-ID', 'Instance-ID')
-DocumentName AWS-RunPowerShellScript
-Parameter @{'commands'=
@([System.IO.File]::ReadAllText("C:...InstallWindowsTasks.ps1"))}
You can use the following commands to monitor the status.
Retrieve the command execution status:
Get-SSMCommand -CommandId $runPSCommand.CommandId
Retrieve the status of the command execution on a per-instance basis:
Get-SSMCommandInvocation -CommandId $runPSCommand.CommandId
Retrieve the command information with response data for an instance. (Be sure to replace Instance-ID)
Get-SSMCommandInvocation -CommandId $runPSCommand.CommandId `
-Details $true -InstanceId Instance-ID |
select -ExpandProperty CommandPlugins
Summary
The EC2 Run Command simplifies remote management and customization of your EC2 instances. For more information, see the following resources:
http://docs.thinkwithwp.com/AWSEC2/latest/WindowsGuide/execute-remote-commands.html
https://thinkwithwp.com/ec2/run-command/.