Skip to content

Instantly share code, notes, and snippets.

@soham2008xyz
Last active July 2, 2024 07:05
Show Gist options
  • Save soham2008xyz/1a49e29910513d05976abbb5a32661f8 to your computer and use it in GitHub Desktop.
Save soham2008xyz/1a49e29910513d05976abbb5a32661f8 to your computer and use it in GitHub Desktop.
AWS Lambda function to check if PHP-FPM is running and restart it, if not running
import boto3
import os
import logging
import time
# Setup logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
elasticbeanstalk = boto3.client('elasticbeanstalk')
ec2 = boto3.client('ec2')
ssm = boto3.client('ssm')
# Environment and instance details
ENVIRONMENT_NAME = os.environ['ENVIRONMENT_NAME']
RETRY_COUNT = 10
RETRY_DELAY = 5 # seconds
def check_php_fpm(instance_id):
"""Checks if php-fpm is running on the instance."""
try:
command = "sudo systemctl is-active php-fpm"
response = ssm.send_command(
InstanceIds=[instance_id],
DocumentName="AWS-RunShellScript",
Parameters={"commands": [command]},
)
command_id = response['Command']['CommandId']
# Retry mechanism to check the command status
for _ in range(RETRY_COUNT):
time.sleep(RETRY_DELAY)
try:
output = ssm.get_command_invocation(
CommandId=command_id,
InstanceId=instance_id,
)
if output['Status'] in ['Success', 'Failed', 'Cancelled', 'TimedOut']:
break
except ssm.exceptions.InvocationDoesNotExist:
logger.warning(f"Invocation does not exist for instance {instance_id}, retrying...")
logger.info(f"Instance {instance_id} php-fpm status: {output['StandardOutputContent'].strip()}")
return output['StandardOutputContent'].strip() == 'active'
except ssm.exceptions.InvalidInstanceId as e:
logger.error(f"Invalid instance ID: {instance_id}. Error: {str(e)}")
return False
except Exception as e:
logger.error(f"Error checking php-fpm status on instance {instance_id}. Error: {str(e)}")
return False
def restart_app_servers():
"""Restarts all instances in the Elastic Beanstalk environment."""
try:
response = elasticbeanstalk.restart_app_server(
EnvironmentName=ENVIRONMENT_NAME
)
logger.info(f"Restarted app servers in environment {ENVIRONMENT_NAME}")
return response
except Exception as e:
logger.error(f"Error restarting app servers in environment {ENVIRONMENT_NAME}. Error: {str(e)}")
return None
def lambda_handler(event, context):
try:
response = elasticbeanstalk.describe_environment_resources(
EnvironmentName=ENVIRONMENT_NAME
)
instances = response['EnvironmentResources']['Instances']
for instance in instances:
instance_id = instance['Id']
if not check_php_fpm(instance_id):
restart_app_servers()
break
return {
'statusCode': 200,
'body': 'Checked php-fpm and restarted app servers if necessary.'
}
except Exception as e:
logger.error(f"Error in lambda_handler. Error: {str(e)}")
return {
'statusCode': 500,
'body': 'Error in lambda_handler.'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment