trigger AWS Lambda function from S3 to windows with AWS SSM

Preparations;

– create your lambda, and connect trigger from s3 as shown below.
– grant permissions for your lambda. (use the key icon on the left)

 

– After installing SSM Agent to your Instance, grant AmazonSSM rights to your instance.

Action in python;

#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 will have the name of the file uploaded to s3 bucket. And bucket_name has the name of the bucket. You can pass these values as argument to your PS script. You can create an s3 put test example and test your code.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.