Skip to content

Instantly share code, notes, and snippets.

@developerck
Last active May 15, 2023 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerck/2230aa32bd309f308667c5f4a47c7378 to your computer and use it in GitHub Desktop.
Save developerck/2230aa32bd309f308667c5f4a47c7378 to your computer and use it in GitHub Desktop.
aws lambda for executing run command using python

aws lambda for executing run command using python

you must have following pre-requsite

instance_id = '' # hard-code for example

document_name = '<>' # run command document name

command_param = {'commands': ['sh /root/shellscript.sh '+ shellparam]}, # shell script path

s3_bucket = 'mybucket' # to store the logs

s3_region = 'eu-west-1'

sns_arn = '<>' # for notification

sns_role_arn = '<>' # to push the notificatan the role must have assume role permission

dynamodb_table = '<>' # to store the status and shell param

#!/usr/bin/python
# -*- coding: utf-8 -*-
import boto3
import botocore
import time
import json
from pprint import pprint
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key
instance_id = '<instance id>' # hard-code for example
document_name = '<>' # run command document name
command_param = {'commands': ['sh /root/shellscript.sh '+ shellparam]}, # shell script path
s3_bucket = 'mybucket'
s3_region = 'eu-west-1'
sns_arn = '<>'
sns_role_arn = '<>'
dynamodb_table = '<>'
def lambda_handler(event=None, context=None):
_log(event)
#prase event
shellparam = '';
if(isinstance(event, str)):
event = json.loads(event)
if("shellparam" in event):
shellparam = event["shellparam"]
if not shellparam:
_log("Exiting : blank shellparam "+shellparam);
return False
client = boto3.client('ssm')
_log("Stating with shellparam : " + shellparam);
# all well, so start the shell script execution
response = client.send_command(
InstanceIds=[instance_id],
DocumentName=document_name,
Parameters=command_param,
OutputS3Region=s3_region,
OutputS3BucketName=s3_bucket,
OutputS3KeyPrefix='/lambda/log'+shellparam,
NotificationConfig={'NotificationArn': sns_arn # notification arn
, 'NotificationEvents': ['All'],
'NotificationType': 'Command'},
ServiceRoleArn=sns_role_arn, # service role arn
)
command_id = response['Command']['CommandId']
_log('Gettign command id ' + command_id)
# create an entry in table
db_record_created = create_record(command_id, shellparam, '',
instance_id)
if db_record_created:
_log("Command Invocation");
time.sleep(0.5) # some delay always required...
result = client.get_command_invocation(CommandId=command_id,
InstanceId=instance_id)
output = result['StandardOutputContent']
_log('Final result')
_log(result)
return True
else:
_log('Request could not processed.')
# delete record
delete_record(command_id)
return false
def delete_record(commandid):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodb_table)
_log('Deleting command id ' + commandid)
try:
response = table.delete_item(Key={'commandid': commandid})
except ClientError as e:
_log(e.response['Error']['Message'])
return False
else:
return True
def check_shellparam(shellparam):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodb_table)
_log('checking shellparam availability ' + shellparam)
try:
response = table.scan(FilterExpression=Key('shellparam').eq(shellparam))
_log(response)
except ClientError as e:
_log(e.response['Error']['Message'])
return False
else:
return response['Count']
def create_record(
commandid,
shellparam,
status,
instanceid,
):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(dynamodb_table)
_log('create record')
try:
response = table.put_item(Item={
'commandid': commandid,
'shellparam': shellparam,
'cmdstatus': status,
'info': {'instanceid': instanceid},
})
_log(response)
except ClientError as e:
_log(e.response['Error']['Message'])
return False
else:
return True
def _log(str):
print(str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment