Hi,
Using Zapier to trigger a Lambda function to restart a service.
I am trying to create the Lambda event so i can trigger it when i need to restart API's.
New to Lambda so please help me step though the issue.
I tried creating the Function un AWS Lambda, i am using Runtime Python 3.10 (not sure if this is correct)
When i run the pm2 restart api comment from the console i have to login as ubuntu. Not sure how i set the user to ubuntu in the lambda_funtion below.
I have replaced sensitives info with xxxxxxxxxx
** lambda_funtion**
import boto3
def lambda_handler(event, context):
instance_id = 'i-xxxxxxxxxxxxxxx'
ec2_client = boto3.client('ssm') # Use 'ssm' instead of 'ec2' for the Systems Manager client
try:
# Send the command to restart all using the AWS Systems Manager RunCommand
response = ec2_client.send_command(
InstanceIds=[instance_id],
DocumentName='AWS-RunShellScript',
Parameters={
'commands': ['pm2 restart api']
}
)
# Print the command execution status
command_id = response['Command']['CommandId']
print(f"Command {command_id} sent successfully.")
return {
'statusCode': 200,
'body': f"Command {command_id} sent successfully."
}
except Exception as e:
error_message = f"Error restarting PM2 on instance {instance_id}: {e}"
print(error_message)
return {
'statusCode': 500,
'body': error_message
}
When i do a test this is the response
Test Event Name
test
Response
{
"statusCode": 500,
"body": "Error restarting PM2 on instance i-xxxxxxxxxxxx: An error occurred (InvalidInstanceId) when calling the SendCommand operation: Instances [[i-xxxxxxxxxxxxxxxxxxx]] not in a valid state for account xxxxxxxxxxxxx"
}
Function Logs
START RequestId: xxxxxxxxxxxxxxxxxxxxxxx Version: $LATEST
Error restarting PM2 on instance i-xxxxxxxxxxxxxxxxx: An error occurred (InvalidInstanceId) when calling the SendCommand operation: Instances [[i-070a8924bf0c0c90c]] not in a valid state for account xxxxxxxxxxxxxxxxxxx
END RequestId: xxxxxxxxxxxxxxxxxxxxx
REPORT RequestId: xxxxxxxxxxxxxxxxxxxxxxx Duration: 1753.45 ms Billed Duration: 1754 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 265.28 ms
Request ID
xxxxxxxxxxxxxxxxx