Automated project using the capabilities of AWS services such as EC2, Lambda, API Gateway, and SSM
We'll walk through the process of automating AWS services such as EC2 (Elastic Compute Cloud), Lambda, API Gateway, and SSM (Systems Manager) using IAM roles and Lambda functions. Our goal is to set up an environment where we can launch EC2 instances with specific IAM roles for SSM, execute commands on these instances using Lambda and SSM, and then expose this functionality via API Gateway.
Prerequisites
Before we begin, ensure you have:
An AWS account with appropriate permissions to create and manage EC2 instances, Lambda functions, IAM roles, and API Gateway.
AWS CLI (Command Line Interface) installed and configured on your local machine.
Step 1: Launching EC2 Instances with IAM Roles for SSM
launch ec2 instances and allow all traffic.
Modify IAM role
and then click on create IAM role the create a role ec2 service having all access of ssm service.
Step 2: Setting Up Lambda Function for SSM Integration
Create an IAM Role for Lambda:
Create a lamda function and click on configuration.
Create a new IAM role for Lambda execution just like we have done for ec2 service.
Attach ssm policies to this role.
Write Lambda Function Code:
Write Lambda function code to execute SSM commands on EC2 instances.
import boto3
def lambda_handler(event, context):
# Specify the AWS region
region = 'ap-south-1'
# Initialize the SSM client
ssm_client = boto3.client('ssm', region_name=region)
# Specify the instance IDs where you want to run the commands
instance_ids = ['i-0212892eba05ea7g0', 'i-0b5ed68eb7d0cca79']
# Specify the commands to run on the instances
commands = [
'yum install httpd -y',
'echo "Hello from AWS Lambda!" > /var/www/html/index.html',
'systemctl start httpd'
'systemctl enable httpd'
]
try:
# Send the commands to the specified instances using SSM
response = ssm_client.send_command(
Targets=[
{
'Key': 'InstanceIds',
'Values': instance_ids
}
],
DocumentName="AWS-RunShellScript",
DocumentVersion="$DEFAULT",
TimeoutSeconds=600, # Increase timeout if needed
Comment='Run HTTPD installation and setup',
Parameters={'commands': commands}
)
# Output command response details
command_id = response['Command']['CommandId']
print(f"Commands sent to instances with command ID: {command_id}")
return {
'statusCode': 200,
'body': f"Commands sent to instances with command ID: {command_id}"
}
except Exception as e:
error_message = f"Error running commands: {str(e)}"
print(error_message)
return {
'statusCode': 500,
'body': error_message
}
Step 3: Configuring API Gateway to Trigger Lambda Function
Create API Gateway Endpoint:
Navigate to API Gateway in the AWS Management Console.
Create a new API and define a resource and method (e.g., GET).
Integrate API Gateway with Lambda:
Select the method and choose Lambda Function Integration.
Choose the Lambda function created in Step 2.
Deploy API Gateway:
Deploy the API to a stage (e.g.,
prod
).Note down the API endpoint URL.
Testing the Setup
Paste the copied url from api in browser you will get this output.
you can check you server launched or not by writing this in browser http://(ip of one instances).
Conclusion
By following this guide, you've automated the process of launching EC2 instances with specific IAM roles, executing SSM commands via Lambda functions, and exposing this functionality through API Gateway. This setup allows for scalable and secure automation of infrastructure management tasks within AWS.