Having error when I am trying to execute the python file in Ec2 (Windows) instance using lambda trigger

0

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?

질문됨 8달 전336회 조회
3개 답변
1

target_region = 'us-west-2b' is an AZ, you probably mean us-west-2.

전문가
답변함 8달 전
profile picture
전문가
검토됨 8달 전
  • 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!

0

If your lambda is connected to your VPC, it needs to be connected on a subnet which has a route to a NAT gateway or the SSM vpc endpoints need configuring.

Also ensure the security group on the Lambda function has the allowed outbound rules and any security groups on the VPC endpoints allow lambda to connect.

profile picture
전문가
답변함 8달 전
0

Is your function attached to a VPC? If so, it doesn't have internet access by default so it can't access the SSM endpoint. You need to create an SSM VPC endpoint, create a NAT gateway, or remove the function from the VPC (It does not need to be there to invoke the python file).

Another option is to send the S3 notification to SQS and let the python file read messages from the queue and handle the event when it is received, without the Lambda function, without SSM.

profile pictureAWS
전문가
Uri
답변함 8달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠