Exploring AWS Lambda: A Practical Guide to Automating EC2 Instance Management

Exploring AWS Lambda: A Practical Guide to Automating EC2 Instance Management

Introduction

Embark on a hands-on journey into the realm of AWS Lambda with this engaging activity. In this lab, we'll delve into the creation of an AWS Lambda function and the orchestration of automated tasks through Amazon EventBridge. Our primary focus will be on developing a Lambda function that leverages an AWS Identity and Access Management (IAM) role, enabling it to autonomously halt a running Amazon Elastic Compute Cloud (Amazon EC2) instance within your AWS account.

Lab Overview

Dive into the intricacies of AWS Lambda as we guide you through the process of crafting a Lambda function tailored for EC2 instance management. This comprehensive lab will walk you through each step, ensuring a thorough understanding of the concepts and practical application.

Architectural Diagram

Visualize the architecture of your AWS environment as we break down the components involved in this activity. Explore the seamless integration of AWS Lambda, Amazon EventBridge, IAM roles, and EC2 instances in a clear and concise diagram. Gain insights into the flow of events and understand how each element plays a crucial role in the automation process.

Key Highlights:

  1. IAM Role Configuration: Delve into the nuances of setting up an IAM role, granting the Lambda function the necessary permissions to interact with and control EC2 instances within your AWS account.

  2. Lambda Function Creation: Learn the essentials of creating a Lambda function optimized for the task at hand. Understand the configuration settings and parameters that contribute to its effectiveness.

  3. Event-Driven Automation: Explore the power of Amazon EventBridge in orchestrating events and triggering Lambda functions. Witness how this event-driven architecture ensures precise and timely execution of tasks.

  4. EC2 Instance Management: Witness the real-world application of your Lambda function as it seamlessly stops a running Amazon EC2 instance. Understand the impact of automation on resource optimization and operational efficiency.

Conclusion

By the end of this activity, you'll not only have a functional AWS Lambda setup but also a deeper understanding of the interconnected AWS services. Uncover the potential of serverless computing, event-driven architectures, and IAM roles as you take a hands-on approach to AWS Lambda in the context of EC2 instance management.

Task 1: IAM Role Configuration

  • Open the AWS Management Console and navigate to the IAM service.

  • In the left navigation pane, click on "Roles."

  • Click the "Create role" button.

  • For the "Select type of trusted entity" step, choose "AWS service."

  • In the "Choose the service that will use this role" section, select "Lambda" as the use case.

  • Click "Next: Permissions."

  • In the "Attach permissions policies" step, click on "Attach policies directly."

  • Search for and select the policies "AmazonEC2FullAccess" and "AWSLambdaBasicExecutionRole." The former provides EC2 management permissions, while the latter provides basic Lambda execution permissions.

  • Click "Next: Tags" (optional), add tags if needed, and then click "Next: Review."

  • Provide a meaningful name such as "myStopinatorRole" for the role in the "Role name" field.

  • Add a description if desired.

  • Click "Create role."

Task 2: Create a Lambda function

  1. In the search box to the right of Services, search for and choose Lambda to open the AWS Lambda console.

  2. Choose Create a function.

  3. In the Create function screen, configure these settings:

    • Choose Author from scratch

    • Function name: myStopinator

    • Runtime: Python 3.11

    • Choose Change default execution role

    • Execution role: Use an existing role

    • Existing role: From the dropdown list, choose myStopinatorRole

  4. Choose Create function.

Task 3: Configure the trigger

In this task, you will configure a scheduled event to trigger the Lambda function by setting an Amazon EventBridge event as the event source (or trigger). The Lambda function can be configured to operate much like a cron job on a Linux server, or a scheduled task on a Microsoft Windows server. However, you do not need to have a server running to host it.

  1. Choose Add trigger.

  2. Choose the Select a trigger dropdown menu, and select EventBridge (CloudWatch Events).

  3. For the rule, choose Create a new rule and configure these settings:

    • Rule name: everyMinute

    • Rule type: Schedule expression

    • Schedule expression: rate(1 minute)

Note: A more realistic, schedule-based stopinator Lambda function would probably be triggered by using a cron expression instead of a rate expression. However, for the purposes of this activity, using a rate expression ensures that the Lambda function will be triggered soon enough that you can see the results.

  1. Choose Add.

Task 4: Configure the Lambda function

In this task, you will paste a few lines of code to update two values in the function code. You do not need to write code to complete this task.

  1. Below the Function overview pane, choose Code, and then choose lambda_function.py to display and edit the Lambda function code.

  2. In the Code source pane, delete the existing code. Copy the following code, and paste it in the box:

     import boto3
     region = '<REPLACE_WITH_REGION>'
     instances = ['<REPLACE_WITH_INSTANCE_ID>']
     ec2 = boto3.client('ec2', region_name=region)
    
     def lambda_handler(event, context):
         ec2.stop_instances(InstanceIds=instances)
         print('stopped your instances: ' + str(instances))
    

    Note: After pasting the code into the Code source box, review line 5. If a period (.) was added, delete it.

  3. Replace the <REPLACE_WITH_REGION> placeholder with the actual Region that you are using. To do this:

    Choose on the region on the top right corner and use the region code. For example, the region code for US East (N. Virginia) is us-east-1.

    Important: Keep the single quotation marks (' ') around the Region in your code. For example, for the N. Virginia, it would be 'us-east-1'

  4. Challenge section: Verify that an EC2 instance named instance1 is running in your account, and copy the instance1**instance ID**.

    You are encouraged to figure out how to do this task without specific step-by-step guidance. However, if you need detailed guidance, select this text to reveal detailed steps:
    Open another browser tab and go to https://console.aws.amazon.com/ec2. Choose Instances. Note that an EC2 instance named instance1 exists, and that it is in a running state. From the Details tab of instance1, copy the instance ID (it will start with i-) Note: Leave this browser tab open. You will return to it in a moment.
  5. Return to the AWS Lambda console browser tab, and replace <REPLACE_WITH_INSTANCE_ID> with the actual instance ID that you just copied.

    Important: Keep the single quotation marks (' ') around the instance ID in your code.

    Your code should now look similar to the following example. However, you might have a different value for the Region, and you will have a different value for the instance ID:

  6. Choose the File menu and Save the changes. Then, in the Code source box, choose Deploy.

    Your Lambda function is now fully configured. It should attempt to stop your instance every minute.

  7. Choose Monitor (the tab near the top of the page).

    Note that one of the charts shows you how many times your function has been invoked. There is also a chart that shows the error count and the success rate as a percentage.

Task 5: Verify that the Lambda function worked

  1. Return to the Amazon EC2 console browser tab and see if your instance was stopped.

    Tip: You can choose the refresh icon or refresh the browser page to see the change in state more quickly.

  2. Try starting the instance again. What do you think will happen?

    Choose here to reveal the answer.
    The instance will be stopped again within 1 minute.

Congratulations! You have completed the activity.