We have a requirement to monitor a directory on an EC2 instance and send any created files to an S3 bucket.
To meet this requirement, I have a script that uses Powershell's FileSystemWatcher to watch the directory and the aws s3 cp command to send the files. Furthermore, the script creates a Scheduled Job to run the File System Watcher continuously. Here is the script with the FileSystemWatcher code removed (the original is pretty lengthy)
file_watcher_task.ps1
$action = {
# File System Watcher code removed
} #close job action
$trigger = New-JobTrigger -AtStartup
Register-ScheduledJob -Name "FileWatcher" -ScriptBlock $action -Trigger $trigger
This script works fine when executed from Powershell with Admin rights. However, I need to deploy this to multiple machines and I want to avoid remoting into each instance. To do this I'm attempting to use an AWS Systems Manager Run Command. Here is the command AWS CLI command I'm using to deploy the script.
aws ssm send-command --document-name "AWS-RunRemoteScript" --targets "Key=instanceids,Values=i-034b37daf8167c03b" --parameters '{"sourceType":["S3"],"sourceInfo":["{\"path\":\"https://analytics-chc-dev-upbs.s3.amazonaws.com/spotfire/remoteadmin/file_watcher_task.ps1\"}"],"commandLine":["file_watcher_task.ps1"]}' --output-s3-region us-east-1 --output-s3-bucket-name analytics-chc-dev-upbs --output-s3-key-prefix logging/sendcommand
The command is executed on the instance, but it gives the following error:
Register-ScheduledJob : An error occurred while registering scheduled job
definition FileWatcher to the Windows Task Scheduler. The Task Scheduler
error is: (13,8):UserId:.
This is caused by the fact that the Systems Manager agent processes all commands in the context of the Local System user. The LocalSystem user is unable to execute Register-ScheduledJob.
I've tried configuring the job to run with the NT AUTHORITY\SYSTEM account but that resulted in a similar error. Also, tried using a Scheduled Task instead of a Scheduled Job but got a different error.
Register-ScheduledTask : No mapping between account names and security IDs was done
Is there a way create a Scheduled Job while in the LocalSystem user context?
"Register-ScheduledJob" requires Admin role credentials, create temporary user with admin permission and delete post creating scheduled job.