Lambda-Driven Continuous Network Path Validation Across AWS Accounts

Lambda-Driven Continuous Network Path Validation Across AWS Accounts

Introduction

Ensuring secure and reliable connectivity between AWS resources across different accounts is a common challenge in multi-account environments. AWS Reachability Analyzer helps you validate network paths between resources like EC2 instances, ENIs, and databases. However, manual validation is time-consuming and error-prone.

This article presents a fully automated, scalable solution to perform periodic cross-account network path validation using AWS Reachability Analyzer, Lambda, CloudFormation, and SNS for alerting. You will learn how to deploy the solution with complete CloudFormation templates and step-by-step instructions.

In today’s multi-account AWS environments, ensuring secure and consistent connectivity between resources across accounts is both critical and complex. You may have:

  • A Load balancer in central egress/ ingress account.
  • Backend services or databases in a dev account.
  • Connectivity managed via VPC peering, Transit Gateway, or PrivateLink.

But how do you automatically validate that network paths are intact and secure—especially after config drift, team changes, or new deployments?

Enter AWS Reachability Analyzer + Lambda Automation.

In this article, I’ll show you how to:

  • Use AWS Reachability Analyzer for cross-account network validation.
  • Automate periodic checks using Lambda + EventBridge.
  • Get notified of any issues via SNS.
  • Deploy everything using CloudFormation — no third-party tools required.


Why Automate Cross-Account Network Validation?

  • Multi-account AWS environments are common for security, billing, and compliance.
  • Network configurations evolve rapidly; manual checks can miss connectivity issues.
  • Automated validation helps detect network misconfigurations and drifts early.
  • Alerts enable proactive remediation before applications experience failures.


Key Components

Article content

Architecture Overview

Article content

How it works:

  • The target/member accounts host AWS resources (EC2, RDS, ENIs).
  • An IAM role with the AWSServiceRoleForReachabilityAnalyzerCrossAccountResourceAccess managed policy is deployed in each member account to grant Reachability Analyzer permission to inspect.
  • The delegated admin/management account runs a Lambda function daily:
  • SNS triggers notifications via email, Slack, or other channels.

Article content

Deployment Prerequisites

  • AWS CLI configured with appropriate permissions.
  • AWS accounts: one delegated admin (or management) account, and one or more member (target) accounts.
  • AWS CloudFormation support.
  • Python 3.11 supported for Lambda runtime.


Step 1: Deploy IAM Role in Member Accounts

Create the IAM role in each member (target) account to enable cross-account reachability analysis.

Save the following as reachability-role.yaml

AWSTemplateFormatVersion: '2010-09-09'
Description: IAM Role for AWS Reachability Analyzer cross-account analysis (deploy in member accounts)

Resources:
  ReachabilityAnalyzerCrossAccountRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: AWSServiceRoleForReachabilityAnalyzerCrossAccountResourceAccess
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: reachabilityanalyzer.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSReachabilityAnalyzerServiceRolePolicy
      Path: /
        

Deploy with AWS CLI in each member account:

aws cloudformation deploy \
  --template-file reachability-role.yaml \
  --stack-name ReachabilityAnalyzerRoleStack
        

Step 2: Deploy Lambda Automation in Delegated Admin Account

This stack deploys the Lambda function, SNS topic, EventBridge rule (for scheduling), and necessary IAM roles.

Save the following as reachability-lambda-stack.yaml

AWSTemplateFormatVersion: '2010-09-09'
Description: Daily AWS Reachability Analyzer using Lambda and EventBridge

Parameters:
  SourceResourceARN:
    Type: String
    Description: ARN of the source EC2 or ENI (e.g., from Dev account)
  DestinationResourceARN:
    Type: String
    Description: ARN of the destination resource (e.g., RDS in Prod account)
  DestinationPort:
    Type: Number
    Description: Port to check (e.g., 443 or 3306)
  Protocol:
    Type: String
    Default: TCP
    AllowedValues:
      - TCP
      - UDP
    Description: Protocol for the reachability check

Resources:

  ReachabilityAlertTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: ReachabilityAlertsTopic

  ReachabilityLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: ReachabilityLambdaExecutionRole
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: AllowReachabilityAnalysisAndSNS
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:CreateNetworkInsightsPath
                  - ec2:StartNetworkInsightsAnalysis
                  - ec2:DescribeNetworkInsightsAnalyses
                  - ec2:DeleteNetworkInsightsPath
                  - ec2:DeleteNetworkInsightsAnalysis
                Resource: "*"
              - Effect: Allow
                Action:
                  - sns:Publish
                Resource: "*"
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: "*"

  ReachabilityLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: ReachabilityAnalyzerLambda
      Runtime: python3.11
      Role: !GetAtt ReachabilityLambdaRole.Arn
      Handler: index.lambda_handler
      Timeout: 60
      Environment:
        Variables:
          SNS_TOPIC_ARN: !Ref ReachabilityAlertTopic
          SOURCE_RESOURCE_ARN: !Ref SourceResourceARN
          DEST_RESOURCE_ARN: !Ref DestinationResourceARN
          DEST_PORT: !Ref DestinationPort
          PROTOCOL: !Ref Protocol
      Code:
        ZipFile: |
          import boto3, os, time, json

          ec2 = boto3.client('ec2')
          sns = boto3.client('sns')

          def lambda_handler(event, context):
              src = os.environ['SOURCE_RESOURCE_ARN']
              dst = os.environ['DEST_RESOURCE_ARN']
              port = int(os.environ['DEST_PORT'])
              protocol = os.environ['PROTOCOL']
              sns_topic = os.environ['SNS_TOPIC_ARN']

              try:
                  # Create network insights path
                  path = ec2.create_network_insights_path(
                      Source=src,
                      Destination=dst,
                      Protocol=protocol,
                      DestinationPort=port
                  )
                  path_id = path['NetworkInsightsPath']['NetworkInsightsPathId']

                  # Start analysis
                  analysis = ec2.start_network_insights_analysis(
                      NetworkInsightsPathId=path_id
                  )
                  analysis_id = analysis['NetworkInsightsAnalysis']['NetworkInsightsAnalysisId']

                  time.sleep(10)  # wait for analysis to complete

                  result = ec2.describe_network_insights_analyses(
                      NetworkInsightsAnalysisIds=[analysis_id]
                  )
                  reachable = result['NetworkInsightsAnalyses'][0]['NetworkPathFound']

                  if not reachable:
                      reasons = result['NetworkInsightsAnalyses'][0].get('Explanations', [])
                      sns.publish(
                          TopicArn=sns_topic,
                          Subject="Reachability FAILED",
                          Message=f"Path unreachable. Reasons:\n{json.dumps(reasons, indent=2)}"
                      )

                  # Cleanup
                  ec2.delete_network_insights_analysis(NetworkInsightsAnalysisId=analysis_id)
                  ec2.delete_network_insights_path(NetworkInsightsPathId=path_id)

              except Exception as e:
                  sns.publish(
                      TopicArn=sns_topic,
                      Subject="Reachability Lambda Error",
                      Message=str(e)
                  )
                  raise

  ScheduleRule:
    Type: AWS::Events::Rule
    Properties:
      Name: DailyReachabilityCheck
      ScheduleExpression: rate(1 day)
      State: ENABLED
      Targets:
        - Arn: !GetAtt ReachabilityLambdaFunction.Arn
          Id: LambdaTarget

  LambdaInvokePermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !Ref ReachabilityLambdaFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt ScheduleRule.Arn
        

Deploy the Lambda stack with parameters

aws cloudformation deploy \
  --template-file reachability-lambda-stack.yaml \
  --stack-name ReachabilityAnalyzerAutomationStack \
  --parameter-overrides \
    SourceResourceARN=arn:aws:ec2:us-east-1:111111111111:instance/i-0123456789abcdef0 \
    DestinationResourceARN=arn:aws:rds:us-east-1:222222222222:db:mydbinstance \
    DestinationPort=3306 \
    Protocol=TCP
        

  • Replace SourceResourceARN and DestinationResourceARN with your actual ARNs.
  • This deploys the scheduled Lambda to validate connectivity daily.


Step 3: Subscribe to Alerts

  • In the delegated admin account, find the SNS topic ReachabilityAlertsTopic.
  • Add email, Slack webhook, or other subscription endpoints.
  • Confirm subscriptions to start receiving alerts on connectivity issues.


Validation and Monitoring

  • Lambda logs can be found in CloudWatch Logs group /aws/lambda/ReachabilityAnalyzerLambda.
  • SNS notifications alert you instantly on failures or errors.
  • Adjust the EventBridge rule schedule as needed.


Conclusion

By deploying this solution, your organization gains:

  • Automated daily verification of cross-account network paths.
  • Immediate alerting on any connectivity problems.
  • Better visibility and compliance over multi-account network configurations.

This IaC-driven approach reduces manual overhead and enhances your security posture.


Bonus: Next Steps

  • Extend Lambda to validate multiple paths by iterating over input arrays.
  • Integrate SNS with ticketing or chat ops tools for streamlined incident response.
  • Use AWS Network Access Analyzer alongside Reachability Analyzer for policy-level checks.

--Written by Alok Saraswat

--Reference Amazon Web Services (AWS)

To view or add a comment, sign in

More articles by Alok Saraswat

Explore content categories