Lesson 1 of 2 Automation with AWS Lambda and AWS Step Functions

Developing Operational Automation with AWS Lambda

AWS Lambda is the most common way to run custom automation on AWS: a small function that runs when an event occurs, calls AWS APIs and exits. This lesson explains how to design Lambda-based automation for operations tasks, including event sources and invocation types, AWS SDK usage across accounts and Regions, error handling and retries, concurrency control and the practices that make automation idempotent and observable.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the event sources and invocation types used for operational automation.
  • Explain how automation functions use the AWS SDK safely, including pagination, retries and cross-account roles.
  • Explain asynchronous retries, destinations, dead-letter queues and event age limits.
  • Explain how reserved concurrency, timeouts and idempotency protect automation and the systems it changes.

Why Lambda for Automation

Operational automation reacts to something: a resource was created, an alarm fired, a schedule arrived or a file landed. Lambda runs code only when such an event occurs, scales automatically and charges only for execution time, so there is no server to keep running for occasional tasks. A function has an execution role that limits what it can do, logs to CloudWatch Logs automatically and can run for up to 15 minutes with up to 10,240 MB of memory. Tasks that take longer, or need many coordinated steps, are better orchestrated by Step Functions, described in the next lesson.

Event Sources and Invocation Types

How a function is invoked determines how errors and retries behave, so it is the first design decision. There are three invocation models.

Synchronous
The caller waits for the result, as with API Gateway, a Lambda invoke action in CodePipeline or an SDK call with RequestResponse. The caller handles errors and retries.
Asynchronous
The event is queued by Lambda and the caller does not wait, as with EventBridge rules, EventBridge Scheduler, Amazon SNS, Amazon S3 event notifications and CloudWatch alarm actions. Lambda handles retries.
Event source mapping (poll-based)
Lambda polls a queue or stream, such as Amazon SQS, Kinesis Data Streams or DynamoDB Streams, and invokes the function with batches. Retry behaviour depends on the source.

Most operational automation is asynchronous. Typical triggers include EventBridge rules matching service events (an instance state change, a GuardDuty finding, a CodePipeline failure), EventBridge Scheduler for periodic jobs such as nightly clean-up, CloudWatch alarm actions that invoke a function directly, SNS topics fed by alarms, and S3 event notifications for files such as logs or reports.

Using the AWS SDK Safely

Automation functions call AWS APIs through the SDK included in the runtime, such as Boto3 for Python. Several practices avoid common faults.

  • Pagination: list operations return pages. Using paginators ensures that all resources are processed, not just the first page of results, a frequent bug in clean-up scripts.
  • Throttling and retries: AWS APIs throttle bursts of calls. SDKs retry with exponential backoff; configuring the adaptive or standard retry mode and limiting concurrency prevents automation from failing, or from throttling other users of the same API.
  • Clients outside the handler: creating SDK clients during initialisation reuses connections across invocations of the same execution environment.
  • Cross-account operations: the function assumes a role in each target account with STS and creates clients from the temporary credentials. The execution role needs sts:AssumeRole on those roles, and each target role trusts the function's role.
  • Multi-Region operations: create a client per Region and process Regions explicitly; a client created without a Region uses the function's own Region.
  • Least privilege: grant only the actions and resources the automation needs, for example ec2:StopInstances conditioned on a tag, rather than broad administrator access.
import boto3

sts = boto3.client("sts")

def session_for(account_id, region):
    creds = sts.assume_role(RoleArn=f"arn:aws:iam::{account_id}:role/OpsAutomationRole",
                            RoleSessionName="unused-volume-cleanup")["Credentials"]
    return boto3.Session(aws_access_key_id=creds["AccessKeyId"], aws_secret_access_key=creds["SecretAccessKey"],
                         aws_session_token=creds["SessionToken"], region_name=region)

def handler(event, context):
    for account_id in event["accounts"]:
        ec2 = session_for(account_id, event["region"]).client("ec2")
        for page in ec2.get_paginator("describe_volumes").paginate(
                Filters=[{"Name": "status", "Values": ["available"]}]):
            for volume in page["Volumes"]:
                tags = {t["Key"]: t["Value"] for t in volume.get("Tags", [])}
                if tags.get("Retain") != "true":
                    ec2.create_tags(Resources=[volume["VolumeId"]], Tags=[{"Key": "PendingDeletion", "Value": "true"}])

Error Handling for Asynchronous Invocations

When an asynchronously invoked function fails, Lambda retries it twice by default, with delays between attempts, so an event can be processed up to three times. Events also wait in Lambda's internal queue if the function is throttled, for up to six hours by default. Both settings are configurable: maximum retry attempts (0 to 2) and maximum event age (60 seconds to 6 hours).

Events that still fail must not disappear silently. Destinations send the invocation record, including the event and the error, to an SQS queue, SNS topic, Lambda function, EventBridge bus or S3 bucket for failures (and optionally successes). A dead-letter queue (an SQS queue or SNS topic configured on the function) receives only the failed event payload; destinations are newer and carry more detail. A CloudWatch alarm on the destination queue's depth or on the function's Errors and DeadLetterErrors metrics alerts operators.

For SQS event source mappings, a failed batch returns to the queue after the visibility timeout and is retried until the queue's redrive policy moves it to the queue's own dead-letter queue. Reporting partial batch failures lets the function retry only the failed messages. For streams, failures block the shard until they succeed or expire, unless bisecting batches, a maximum retry count and an on-failure destination are configured.

InvocationWho retriesWhere failed events go
SynchronousThe callerReturned to the caller
AsynchronousLambda: up to 2 retries, events up to 6 hours oldOn-failure destination or function DLQ
SQS event source mappingSQS redelivery after the visibility timeoutThe source queue's dead-letter queue
Kinesis or DynamoDB streamLambda until success, expiry or the retry limitOn-failure destination (SQS, SNS, S3)

The following diagram follows an event that keeps failing.

Error handling for asynchronous Lambda invocations. Events wait in Lambda's internal queue, for up to the maximum event age (six hours by default) if the function is throttled. A failed invocation is retried up to twice by default, so an event can be processed three times, which is why the function must be idempotent. An event that still fails, or expires, goes to an on-failure destination or a dead-letter queue, where an alarm on the queue depth alerts operators.
Failed events must go somewhere observable.
Fill in the value

Asynchronous Lambda limits

Exam skills 2.3.2 · 5.1.2

Recall the defaults that govern asynchronous Lambda invocations.

Log in to try this activity Interactive activities are free with an account.

Concurrency, Timeouts and Idempotency

Automation must not overwhelm the systems it changes. Reserved concurrency limits a function to a maximum number of concurrent executions and also guarantees it that capacity from the account's pool. Setting reserved concurrency to a small number for a remediation function ensures that a flood of events, for example thousands of findings after enabling a new standard, is processed gradually rather than in a burst of API calls. Setting it to zero disables the function immediately, which is a useful emergency stop. Provisioned concurrency, by contrast, pre-initialises environments to reduce start-up latency, which automation rarely needs.

The timeout should be longer than the worst-case run time but not the maximum by default, so that a hung call fails quickly and is retried. Because asynchronous events can be delivered more than once, functions must be idempotent: running twice with the same event must have the same effect as running once. Techniques include checking the current state before acting (stop an instance only if it is running), using client tokens on API calls that support them, and recording processed event IDs in a DynamoDB table with a conditional write, which Powertools for AWS Lambda provides as an idempotency utility.

Powertools for AWS Lambda also provides structured logging, custom metrics in the CloudWatch embedded metric format and tracing, which make automation observable. Every action an automation takes should be logged with the triggering event's ID, so its effects can be audited alongside CloudTrail.

Scenario questions

Automate without harm

Exam skills 2.3.2

Practise concurrency and idempotency for automation functions.

Log in to try this activity Interactive activities are free with an account.
Worked example

Quarantining a Compromised Instance

When Amazon GuardDuty reports a high-severity finding for an EC2 instance, the security team wants the instance isolated within a minute, its volumes snapshotted for forensics and the team notified, without terminating it.

  1. Trigger

    An EventBridge rule matches GuardDuty findings with severity of 7 or higher and a resource type of Instance, and invokes a Lambda function asynchronously.

  2. Act

    The function replaces the instance's security groups with an isolation group that has no rules, snapshots each attached volume, tags the instance and publishes a summary to SNS.

  3. Be safe

    The function checks whether the instance is already isolated before acting, so retries are harmless, and its role allows ec2:ModifyInstanceAttribute and ec2:CreateSnapshot only.

  4. Handle failure

    An on-failure destination sends failed events to an SQS queue with an alarm on its depth, and maximum event age is set to one hour.

Check yourself

A clean-up function triggered by EventBridge occasionally deletes the same resource twice and logs an error the second time. Why, and how should it be designed?

Show answer

Asynchronous invocations can be retried or delivered more than once. The function should be idempotent, for example by checking that the resource still exists or treating NotFound as success.

Exam Tips

Remember for the exam

  • EventBridge, SNS, S3 notifications and alarm actions invoke Lambda asynchronously: up to two retries and a maximum event age of six hours by default; use on-failure destinations or a DLQ.
  • Use paginators, SDK retry modes and assumed roles per account; create clients outside the handler.
  • Reserved concurrency limits the rate of automation (and zero disables the function); provisioned concurrency only reduces cold starts.
  • Make automation idempotent because events can be delivered more than once.
  • Lambda runs for at most 15 minutes; use Step Functions for longer or multi-step workflows.