c.cem dogan.← Back to journal
TECHNOLOGY

Trigger AWS Lambda from S3 to Windows with SSM.

Originally published in 2018. This historical example is reproduced as displayed on the original site; formatting, syntax, services, and permissions may need updating before use.

Preparations:

AWS Lambda S3 trigger configuration

After installing SSM Agent on your instance, grant it AmazonSSM permissions.

The Python example:

#09-03-2018 – Cem Dogan
import boto3
import json

def lambda_handler(event, context):
records = [x for x in event.get(‘Records’, []) if x.get(‘eventName’) == ‘ObjectCreated:Put’]
sorted_events = sorted(records, key=lambda e: e.get(‘eventTime’))
latest_event = sorted_events[-1] if sorted_events else {}
info = latest_event.get(‘s3’, {})
file_key = info.get(‘object’, {}).get(‘key’)
bucket_name = info.get(‘bucket’, {}).get(‘name’)
command = ‘C:\folder\your_PSscript.ps1 ‘ + file_key
print command
ssm = boto3.client(‘ssm’)
ssmresponse = ssm.send_command(InstanceIds=[‘i-instanceID’], DocumentName=’AWS-RunPowerShellScript’, Parameters= { ‘commands’: [command] } )
return ssmresponse

file_key contains the name of the file uploaded to the S3 bucket, and bucket_name contains the bucket name. You can pass these values as arguments to your PowerShell script and test the code with an S3 put event.

← Back to journal