I am attempting to execute a Python file in an EC2 (Windows) instance through a lambda trigger function when a file is uploaded to an S3 bucket.
My Code
import boto3
def lambda_handler(event, context):
# Specify the target region where the EC2 instance is located
target_region = 'us-west-2b' # Replace with the desired region code
# Initialize SSM client for the target region
ssm_client = boto3.client('ssm', region_name=target_region)
# Specify the EC2 instance ID in the target region
instance_id = '[ID]' # Replace with the desired instance ID
directory = 'C:/Users/Administrator/Desktop/Automation'
# Specify the Python file you want to run on the EC2 instance
python_file = 'first.py'
command = f'cd {directory} && python {python_file}'
# Build the command to run the Python file
# command = f'python {python_file}'
# Send the command to the specified instance
response = ssm_client.send_command(
InstanceIds=[instance_id],
DocumentName='AWS-RunShellScript',
Parameters={'commands': [command]}
)
return {
'statusCode': 200,
'body': response
}
But When I run the code It throws error
{
"errorMessage": "Could not connect to the endpoint URL: "https://ssm.us-west-2b.amazonaws.com/"",
"errorType": "EndpointConnectionError",
"stackTrace": [
" File "/var/task/lambda_function.py", line 60, in lambda_handler\n Parameters={'commands': [command]}\n",
" File "/var/runtime/botocore/client.py", line 530, in _api_call\n return self._make_api_call(operation_name, kwargs)\n",
" File "/var/runtime/botocore/client.py", line 944, in _make_api_call\n operation_model, request_dict, request_context\n",
" File "/var/runtime/botocore/client.py", line 966, in _make_request\n return self._endpoint.make_request(operation_model, request_dict)\n",
" File "/var/runtime/botocore/endpoint.py", line 119, in make_request\n return self._send_request(request_dict, operation_model)\n",
" File "/var/runtime/botocore/endpoint.py", line 207, in _send_request\n exception,\n",
" File "/var/runtime/botocore/endpoint.py", line 361, in _needs_retry\n request_dict=request_dict,\n",
" File "/var/runtime/botocore/hooks.py", line 412, in emit\n return self._emitter.emit(aliased_event_name, **kwargs)\n",
" File "/var/runtime/botocore/hooks.py", line 256, in emit\n return self._emit(event_name, kwargs)\n",
" File "/var/runtime/botocore/hooks.py", line 239, in _emit\n response = handler(**kwargs)\n",
" File "/var/runtime/botocore/retryhandler.py"
Can Anyone help me to resolve this issue?
BTW I've never tried to execute python like this. I would tend to have a service on the EC2 instance listening on an SQS queue, and send messages to the queue from your Lambda. So consider that option if you have trouble with your approach.
Good spot!