Search code examples
amazon-ec2aws-lambda

How to access EC2 instance in different region from lambda in another region


In the same account, I have lambda in us-east-2 and EC2 instance in us-east-1. I want to connect to the EC2 instance either by ssh or having a api server running in EC2 from the lambda.

How can i Achieve this


Solution

  • Yes you can just enable the SSM agent on a target ec2 instance and attach a Systems manager Instance core Instance profile to target machine and create a lambda in source region where you want to run commands. Here is the sample lambda code below`import boto3

    def lambda_handler(event, context): # Specify the EC2 instance ID and the target region instance_id = 'your-instance-id' target_region = 'us-west-2' # Replace with your desired region

    # Initialize the SSM client in the target region
    ssm_client = boto3.client('ssm', region_name=target_region)
    
    # Specify the SSM command to run on the EC2 instance
    ssm_command = 'ls -la /'
    
    try:
        # Execute the SSM command on the EC2 instance
        response = ssm_client.send_command(
            InstanceIds=[instance_id],
            DocumentName='AWS-RunShellScript',
            Parameters={'commands': [ssm_command]}
        )
    
        command_id = response['Command']['CommandId']
        print(f"SSM command sent to EC2 instance. Command ID: {command_id}")
    
        return {
            'statusCode': 200,
            'body': f"SSM command sent to EC2 instance. Command ID: {command_id}"
        }
    
    except Exception as e:
        print(f"Error sending SSM command: {e}")
        return {
            'statusCode': 500,
            'body': f"Error sending SSM command: {e}"
        }
    

    `