I Built Failover for Amazon EBS Multi-AZ Volumes Using Step Functions and Lambda

I Built Failover for Amazon EBS Multi-AZ Volumes Using Step Functions and Lambda

I created an EC2 instance with a multi-AZ root volume, which CloudFormation (CDK) doesn't support, via the CLI. I implemented FailoverVolumes, unsupported by the Step Functions SDK integration, in Lambda, and confirmed failover works from Step Functions.
2026.12.07

This page has been translated by machine translation. View original

Introduction

On November 30, 2026, Amazon EBS multi-AZ volumes were announced.

https://aws.amazon.com/about-aws/whats-new/2026/11/ebs-multi-az-volumes/

The overview of multi-AZ volumes and the create, sync, and failover operations were already covered in the following article.

https://dev.classmethod.jp/articles/amazon-ebs-multi-az-volumes/

In this article, I tested failover of an EC2 instance whose root volume is a multi-AZ volume, using the CLI and Step Functions combined with Lambda.

Test environment

  • Region: Tokyo (ap-northeast-1)
  • AZ:
    • apne1-az1: ap-northeast-1c
    • apne1-az2: ap-northeast-1d
  • VPC: default VPC
  • EC2:
    • Instance type: t3.small
    • OS: Amazon Linux 2023
    • Root volume: gp3 8 GiB
  • AWS CLI: 2.43.2
  • cdkd: 0.377.1
  • aws-cdk-lib: 2.278.0
  • Node.js: 22.23.5
  • Lambda:
    • Runtime: Python 3.13
    • boto3: 1.44.19

This is the configuration before running the failover.

Diagram of the configuration before failover. In az1 there is a stopped EC2 #1, in az2 there is a running EC2 #2, and the multi-AZ volume is syncing from az2 to az1

Creating the configuration

Create EC2 and ALB with cdkd

With cdkd, I deployed EC2 #1 (whose root volume is a single-AZ gp3), an ALB, a target group, and an IAM role. After that, I created, via the CLI, an EC2 instance with a multi-AZ root volume, which CDK and CloudFormation do not support at this time.

On EC2 #1 I run an HTTP server written only with the Python standard library (hereafter, AP). For each request, AP reads the instance-id, private-ip, and az-id from IMDSv2 and returns them. At every boot it appends one line to /var/lib/ap/boot.log on the root volume and returns the number of lines as boot-count. Whether the files on the root volume were carried over to another EC2 can be told by whether boot-count keeps increasing.

app.ts reads the environment variables VPC_ID, SUBNET_AZ1, SUBNET_AZ2, AZ1, and AZ2. The values are the default VPC ID, the subnet IDs for apne1-az1 and apne1-az2, and the name of each AZ. After setting the environment variables, I ran the following commands in the working directory containing cdk.json, package.json, and app.ts.

npm install
npx cdkd bootstrap
npx cdkd deploy --all

The following commands use AlbDns, TargetGroupArn, Instance1Id, and ApSecurityGroupId from the deploy output. To check the ALB, I use the following command.

for i in 1 2 3; do curl -s -m 5 http://<ALB の DNS 名>/; done

ALB checks from here on use the same command, and when all three results were identical I show only one line. Right after deployment, EC2 #1 responded.

{"instance-id": "i-1234567890abcdef0", "private-ip": "172.31.1.10", "az-id": "apne1-az1", "boot-count": 1}
Full text of cdk.json, package.json, and app.ts

cdk.json

{
  "app": "npx tsx app.ts"
}

package.json

{
  "name": "ebs-multi-az-failover-verify",
  "private": true,
  "type": "commonjs",
  "dependencies": {
    "@cdkd/cli": "0.377.1",
    "aws-cdk-lib": "2.278.0",
    "constructs": "10.8.1",
    "tsx": "4.23.15",
    "@types/node": "26.6.11"
  }
}

app.ts

import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets';
import * as iam from 'aws-cdk-lib/aws-iam';

// 実行時に環境変数で受け取る(デフォルト VPC と、az1 / az2 のサブネット)
const VPC_ID = process.env.VPC_ID!;
const SUBNET_AZ1 = process.env.SUBNET_AZ1!; // apne1-az1 (ap-northeast-1c)
const SUBNET_AZ2 = process.env.SUBNET_AZ2!; // apne1-az2 (ap-northeast-1d)
const AZ1 = process.env.AZ1!; // ap-northeast-1c
const AZ2 = process.env.AZ2!; // ap-northeast-1d

const AP_SERVER = `#!/usr/bin/env python3
import http.server, json, os, time, urllib.request

def imds(path):
    req = urllib.request.Request('http://169.254.169.254/latest/api/token', method='PUT',
                                 headers={'X-aws-ec2-metadata-token-ttl-seconds': '60'})
    token = urllib.request.urlopen(req, timeout=2).read().decode()
    req = urllib.request.Request('http://169.254.169.254/latest/meta-data/' + path,
                                 headers={'X-aws-ec2-metadata-token': token})
    return urllib.request.urlopen(req, timeout=2).read().decode()

LOG = '/var/lib/ap/boot.log'
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, 'a') as f:
    f.write(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) + ' ' + imds('instance-id') + '\\n')
    f.flush()
    os.fsync(f.fileno())

class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        with open(LOG) as f:
            boot_count = sum(1 for _ in f)
        body = json.dumps({
            'instance-id': imds('instance-id'),
            'private-ip': imds('local-ipv4'),
            'az-id': imds('placement/availability-zone-id'),
            'boot-count': boot_count,
        }) + '\\n'
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(body.encode())
    def log_message(self, *args):
        pass

http.server.ThreadingHTTPServer(('0.0.0.0', 80), Handler).serve_forever()
`;

const AP_UNIT = `[Unit]
Description=Sample AP
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/python3 /opt/ap/server.py
Restart=always

[Install]
WantedBy=multi-user.target
`;

// UserData は冪等にする。ルートボリュームが別の EC2 に付け替わると cloud-init が再実行されるため。
const USER_DATA = `#!/bin/bash
set -eu
mkdir -p /opt/ap /var/lib/ap
cat > /opt/ap/server.py <<'PYEOF'
${AP_SERVER}PYEOF
cat > /etc/systemd/system/ap.service <<'UNITEOF'
${AP_UNIT}UNITEOF
systemctl daemon-reload
systemctl enable --now ap.service
`;

class BaseStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const vpc = ec2.Vpc.fromVpcAttributes(this, 'Vpc', {
      vpcId: VPC_ID,
      availabilityZones: [AZ1, AZ2],
      publicSubnetIds: [SUBNET_AZ1, SUBNET_AZ2],
    });
    const subnetAz1 = ec2.Subnet.fromSubnetAttributes(this, 'SubnetAz1', {
      subnetId: SUBNET_AZ1,
      availabilityZone: AZ1,
    });

    const albSg = new ec2.SecurityGroup(this, 'AlbSg', { vpc, description: 'ALB' });
    albSg.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80));
    const apSg = new ec2.SecurityGroup(this, 'ApSg', { vpc, description: 'AP' });
    apSg.addIngressRule(albSg, ec2.Port.tcp(80));

    const role = new iam.Role(this, 'ApRole', {
      assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
      managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore')],
    });

    const instance1 = new ec2.Instance(this, 'Instance1', {
      vpc,
      vpcSubnets: { subnets: [subnetAz1] },
      instanceType: new ec2.InstanceType('t3.small'),
      machineImage: ec2.MachineImage.latestAmazonLinux2023(),
      securityGroup: apSg,
      role,
      requireImdsv2: true,
      blockDevices: [
        { deviceName: '/dev/xvda', volume: ec2.BlockDeviceVolume.ebs(8, { volumeType: ec2.EbsDeviceVolumeType.GP3 }) },
      ],
      userData: ec2.UserData.custom(USER_DATA),
    });
    cdk.Tags.of(instance1).add('Name', 'multi-az-verify-1');
    cdk.Tags.of(instance1).add('Pair', 'multi-az-verify');

    const alb = new elbv2.ApplicationLoadBalancer(this, 'Alb', {
      vpc,
      internetFacing: true,
      securityGroup: albSg,
      vpcSubnets: { subnets: [subnetAz1, ec2.Subnet.fromSubnetAttributes(this, 'SubnetAz2', { subnetId: SUBNET_AZ2, availabilityZone: AZ2 })] },
    });
    const tg = new elbv2.ApplicationTargetGroup(this, 'Tg', {
      vpc,
      port: 80,
      protocol: elbv2.ApplicationProtocol.HTTP,
      targetType: elbv2.TargetType.INSTANCE,
      deregistrationDelay: cdk.Duration.seconds(10),
      healthCheck: { path: '/', interval: cdk.Duration.seconds(5), timeout: cdk.Duration.seconds(2), healthyThresholdCount: 2, unhealthyThresholdCount: 2 },
    });
    tg.addTarget(new targets.InstanceIdTarget(instance1.instanceId, 80));
    alb.addListener('Http', { port: 80, defaultTargetGroups: [tg] });

    new cdk.CfnOutput(this, 'AlbDns', { value: alb.loadBalancerDnsName });
    new cdk.CfnOutput(this, 'TargetGroupArn', { value: tg.targetGroupArn });
    new cdk.CfnOutput(this, 'ApSecurityGroupId', { value: apSg.securityGroupId });
    new cdk.CfnOutput(this, 'Instance1Id', { value: instance1.instanceId });
  }
}

const app = new cdk.App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
new BaseStack(app, 'MultiAzVerifyBase', { env });

Launch an EC2 with a multi-AZ root from an AMI

I created an AMI from EC2 #1, which was launched with a regular volume, and from that AMI launched EC2 #2, which has a multi-AZ root volume, in a different AZ.

Create the AMI with create-image and wait until State becomes available.

aws ec2 create-image --instance-id <EC2 #1 の ID> --name multi-az-verify-ap-1206
aws ec2 describe-images --image-ids <AMI ID> --query 'Images[0].State'

I save the block device mapping that makes the root volume multi-AZ at launch from the AMI as bdm-multi-az-root.json. The standby AZ is specified by AZ ID.

[
  {
    "DeviceName": "/dev/xvda",
    "Ebs": {
      "VolumeType": "gp3",
      "DeleteOnTermination": false,
      "MultiAvailabilityZoneConfiguration": {
        "ConfigurationType": "multi-az-1",
        "StandbyAvailabilityZones": [{ "AvailabilityZoneId": "apne1-az1" }]
      }
    }
  }
]

I passed this file to --block-device-mappings and launched EC2 #2 in the apne1-az2 subnet. The AZ of the launch subnet (apne1-az2) becomes the active AZ, and apne1-az1, specified in the file, becomes the standby AZ. Because Step Functions' describeVolumes cannot get the standby AZ, I added a Pair tag so the state machine can find the EC2 instances. app.ts attaches the same tag to EC2 #1.

aws ec2 run-instances \
  --image-id <AMI ID> \
  --instance-type t3.small \
  --subnet-id <apne1-az2 のサブネット ID> \
  --security-group-ids <ApSecurityGroupId> \
  --metadata-options HttpTokens=required \
  --block-device-mappings file://bdm-multi-az-root.json \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Pair,Value=multi-az-verify}]'

Right after launch, I confirmed with describe-volumes that the root volume of EC2 #2 was multi-AZ.

aws ec2 describe-volumes --volume-ids <ボリューム ID>
"MultiAvailabilityZoneConfiguration": {
    "ConfigurationType": "multi-az-1",
    "StandbyAvailabilityZones": [
        {
            "AvailabilityZone": "ap-northeast-1c",
            "AvailabilityZoneId": "apne1-az1"
        }
    ]
},
"AvailabilityZone": "ap-northeast-1d",
"State": "in-use",
"Attachments": [
    {
        "DeleteOnTermination": false,
        "EbsCardIndex": 0,
        "AvailabilityZone": "ap-northeast-1d",
        "AvailabilityZoneId": "apne1-az2",
        "TrimState": "disabled",
        "VolumeId": "vol-1234567890abcdef0",
        "InstanceId": "i-0abcdef1234567890",
        "Device": "/dev/xvda",
        "State": "attached",
        "AttachTime": "2026-12-06T10:11:33+00:00"
    }
],

Before failover-volumes, I checked the sync state with describe-volume-status. ReplicationDataState was in-sync and FailoverReadiness was ready.

So that Lambda and the state machine can obtain the volume ID, I store it in an SSM parameter. EC2 #2 is registered as an ALB target.

aws ssm put-parameter --name /ebs-multi-az-verify/volume-id --type String --value <ボリューム ID> --overwrite
aws elbv2 register-targets --target-group-arn <TargetGroupArn> --targets Id=<EC2 #2 の ID>

After registration, when I checked with the loop set to 6 iterations, both EC2 #1 and EC2 #2 responded via the ALB. These are the first 4 lines of the output.

{"instance-id": "i-1234567890abcdef0", "private-ip": "172.31.1.10", "az-id": "apne1-az1", "boot-count": 2}
{"instance-id": "i-0abcdef1234567890", "private-ip": "172.31.2.20", "az-id": "apne1-az2", "boot-count": 2}
{"instance-id": "i-0abcdef1234567890", "private-ip": "172.31.2.20", "az-id": "apne1-az2", "boot-count": 2}
{"instance-id": "i-1234567890abcdef0", "private-ip": "172.31.1.10", "az-id": "apne1-az1", "boot-count": 2}

Finally, I stopped EC2 #1, then detached and deleted its original root volume. EC2 #1 waits in a stopped state without a root volume.

aws ec2 stop-instances --instance-ids <EC2 #1 の ID>
aws ec2 wait instance-stopped --instance-ids <EC2 #1 の ID>
aws ec2 detach-volume --volume-id <EC2 #1 のルートボリューム ID>
aws ec2 wait volume-available --volume-ids <EC2 #1 のルートボリューム ID>
aws ec2 delete-volume --volume-id <EC2 #1 のルートボリューム ID>
aws ec2 describe-instances --instance-ids <EC2 #1 の ID> --query 'Reservations[0].Instances[0].[State.Name,BlockDeviceMappings]'

BlockDeviceMappings in the last describe-instances was empty.

[
    "stopped",
    []
]

Failover with the CLI

I tried two ways of swapping the volume: method A, where no volume is attached to the standby EC2, and method B, where the volume is attached to the standby EC2 in advance. The volume ID is obtained from the SSM parameter, and between operations I wait for completion with aws ec2 wait.

Method A (nothing attached to the standby EC2)

Stop EC2 #2 and detach the volume.

aws ssm get-parameter --name /ebs-multi-az-verify/volume-id --query Parameter.Value --output text
aws ec2 stop-instances --instance-ids <EC2 #2 の ID>
aws ec2 wait instance-stopped --instance-ids <EC2 #2 の ID>
aws ec2 detach-volume --volume-id <ボリューム ID> --instance-id <EC2 #2 の ID>
aws ec2 wait volume-available --volume-ids <ボリューム ID>

Even for a volume not attached to any EC2, I could run failover-volumes by specifying --volume-id.

aws ec2 failover-volumes --volume-id <ボリューム ID> --source-active-availability-zone ap-northeast-1d

Right after, I checked with describe-volumes.

aws ec2 describe-volumes --volume-ids <ボリューム ID> \
  --query 'Volumes[0].[State,AvailabilityZone,MultiAvailabilityZoneConfiguration.StandbyAvailabilityZones[0].AvailabilityZone,Attachments]'
[
    "available",
    "ap-northeast-1c",
    "ap-northeast-1d",
    []
]

Since ap-northeast-1c became the active AZ, I attach the volume to EC2 #1 as /dev/xvda and start it.

aws ec2 attach-volume --volume-id <ボリューム ID> --instance-id <EC2 #1 の ID> --device /dev/xvda
aws ec2 wait volume-in-use --volume-ids <ボリューム ID>
aws ec2 start-instances --instance-ids <EC2 #1 の ID>
aws ec2 wait instance-running --instance-ids <EC2 #1 の ID>

The ALB returned the response from EC2 #1. boot-count increased from 2, the last value on EC2 #2, to 3. EC2 #1 booted with the files from the root volume that EC2 #2 had been using.

{"instance-id": "i-1234567890abcdef0", "private-ip": "172.31.1.10", "az-id": "apne1-az1", "boot-count": 3}

Method B (pre-attach to the standby EC2)

After method A, EC2 #2 is stopped and has no root volume. I attached the same volume to this EC2 #2 as /dev/xvda.

aws ec2 attach-volume --volume-id <ボリューム ID> --instance-id <EC2 #2 の ID> --device /dev/xvda
aws ec2 describe-volumes --volume-ids <ボリューム ID> \
  --query 'Volumes[0].[State,AvailabilityZone,MultiAvailabilityZoneConfiguration.StandbyAvailabilityZones[0].AvailabilityZone,Attachments[].[InstanceId,AvailabilityZone,State,Device]]'
[
    "in-use",
    "ap-northeast-1c",
    "ap-northeast-1d",
    [
        [
            "i-0abcdef1234567890",
            "ap-northeast-1d",
            "attached",
            "/dev/xvda"
        ],
        [
            "i-1234567890abcdef0",
            "ap-northeast-1c",
            "attached",
            "/dev/xvda"
        ]
    ]
]

Stop EC2 #1 and run failover-volumes specifying EC2 #1 with --instance-id.

aws ec2 stop-instances --instance-ids <EC2 #1 の ID>
aws ec2 wait instance-stopped --instance-ids <EC2 #1 の ID>
aws ec2 failover-volumes --instance-id <EC2 #1 の ID> --source-active-availability-zone ap-northeast-1c
aws ec2 describe-volumes --volume-ids <ボリューム ID> \
  --query 'Volumes[0].[AvailabilityZone,MultiAvailabilityZoneConfiguration.StandbyAvailabilityZones[0].AvailabilityZone,Attachments[].[InstanceId,AvailabilityZone,State]]'
[
    "ap-northeast-1d",
    "ap-northeast-1c",
    [
        [
            "i-0abcdef1234567890",
            "ap-northeast-1d",
            "attached"
        ],
        [
            "i-1234567890abcdef0",
            "ap-northeast-1c",
            "attached"
        ]
    ]
]

When I started EC2 #2 in the active AZ, the ALB returned the response from EC2 #2.

aws ec2 start-instances --instance-ids <EC2 #2 の ID>
aws ec2 wait instance-running --instance-ids <EC2 #2 の ID>
{"instance-id": "i-0abcdef1234567890", "private-ip": "172.31.2.20", "az-id": "apne1-az2", "boot-count": 4}

With method A, attaching is required after failover. With method B, the volume is already attached, so you only need to start the instance after failover.

Failback with Step Functions

I built the failback to the original active AZ (ap-northeast-1d, the EC2 #2 side) in Step Functions, following the flow of method A.

The FailoverVolumes SDK integration

The Resource for an AWS SDK integration has the form arn:aws:states:::aws-sdk:<service name>:<API name>, and the list is on the following page.

https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html

I saved a definition with just one state calling FailoverVolumes as probe.json and passed it to validate-state-machine-definition.

{"QueryLanguage":"JSONata","StartAt":"F","States":{"F":{"Type":"Task","Resource":"arn:aws:states:::aws-sdk:ec2:failoverVolumes","Arguments":{"VolumeId":"vol-0123456789abcdef0","SourceActiveAvailabilityZone":"ap-northeast-1c"},"End":true}}}
aws stepfunctions validate-state-machine-definition --definition file://probe.json --type STANDARD
    "result": "FAIL",
    "diagnostics": [
        {
            "severity": "ERROR",
            "code": "SCHEMA_VALIDATION_FAILED",
            "message": "The resource provided arn:aws:states:::aws-sdk:ec2:failoverVolumes is not recognized. The value is not a valid resource ARN, or the resource is not available in this region.",
            "location": "/States/F/Resource"
        }
    ],

At the time of testing, the FailoverVolumes SDK integration was not recognized. Stop, detach, attach, start, and getting the SSM parameter could be built with SDK integrations, so only the FailoverVolumes call was made a Lambda.

Calling FailoverVolumes with Lambda

The boto3 in the Python 3.13 base image (public.ecr.aws/lambda/python:3.13) is 1.43.127 and does not have failover_volumes. The latest boto3 at the time of testing (December 6, 2026) was 1.44.19. So I deployed a Lambda bundling the latest boto3 with cdkd. Because the CLI operations so far replaced EC2 #1's root volume with a multi-AZ volume, the app.ts stack has drifted from reality. To avoid updating that stack, I put the Lambda in a separate stack from app.ts.

Save the handler as lambda/index.py. It gets the current active AZ with describe_volumes and passes it to failover_volumes.

import os
import boto3

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

def az_of(volume_id):
    v = ec2.describe_volumes(VolumeIds=[volume_id])['Volumes'][0]
    standby = v['MultiAvailabilityZoneConfiguration']['StandbyAvailabilityZones'][0]['AvailabilityZone']
    return v['AvailabilityZone'], standby

def handler(event, context):
    # Receive VolumeId from Step Functions. When run directly, take it from the SSM parameter
    volume_id = event.get('VolumeId') or ssm.get_parameter(Name=os.environ['PARAM_NAME'])['Parameter']['Value']
    active, standby = az_of(volume_id)
    resp = ec2.failover_volumes(VolumeId=volume_id, SourceActiveAvailabilityZone=active)
    resp.pop('ResponseMetadata', None)
    after_active, after_standby = az_of(volume_id)
    return {
        'boto3': boto3.__version__,
        'volumeId': volume_id,
        'before': {'active': active, 'standby': standby},
        'after': {'active': after_active, 'standby': after_standby},
        'response': resp,
    }

Place the handler and boto3 in the lambda-pkg directory.

mkdir lambda-pkg
python3 -m pip install --target lambda-pkg boto3
cp lambda/index.py lambda-pkg/

The stack is defined in lambda-app.ts. The function name is fixed because it is used in the ARN when the state machine invokes it.

import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as lambda from 'aws-cdk-lib/aws-lambda';

const VOLUME_PARAM = '/ebs-multi-az-verify/volume-id';

class LambdaStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const fn = new lambda.Function(this, 'FailoverFn', {
      functionName: 'multi-az-verify-failover',
      runtime: lambda.Runtime.PYTHON_3_13,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda-pkg'),
      timeout: cdk.Duration.seconds(60),
      environment: { PARAM_NAME: VOLUME_PARAM },
    });
    fn.addToRolePolicy(new iam.PolicyStatement({ actions: ['ec2:DescribeVolumes'], resources: ['*'] }));
    fn.addToRolePolicy(new iam.PolicyStatement({
      actions: ['ec2:FailoverVolumes'],
      resources: [`arn:aws:ec2:${this.region}:${this.account}:volume/*`, `arn:aws:ec2:${this.region}:${this.account}:instance/*`],
    }));
    fn.addToRolePolicy(new iam.PolicyStatement({
      actions: ['ssm:GetParameter'],
      resources: [`arn:aws:ssm:${this.region}:${this.account}:parameter${VOLUME_PARAM}`],
    }));
  }
}

const app = new cdk.App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
new LambdaStack(app, 'MultiAzVerifyLambda', { env });

Specify lambda-app.ts with --app and deploy.

npx cdkd deploy --all --app "npx tsx lambda-app.ts"

After method B, I stopped EC2 #2. Both instances are stopped, and the volume is attached to both EC2 instances.

aws ec2 stop-instances --instance-ids <EC2 #2 の ID>
aws ec2 wait instance-stopped --instance-ids <EC2 #2 の ID>
aws ec2 describe-volumes --volume-ids <ボリューム ID> \
  --query 'Volumes[0].[AvailabilityZone,MultiAvailabilityZoneConfiguration.StandbyAvailabilityZones[0].AvailabilityZone,Attachments[].[InstanceId,AvailabilityZone,State]]'
[
    "ap-northeast-1d",
    "ap-northeast-1c",
    [
        [
            "i-0abcdef1234567890",
            "ap-northeast-1d",
            "attached"
        ],
        [
            "i-1234567890abcdef0",
            "ap-northeast-1c",
            "attached"
        ]
    ]
]

I invoked the Lambda with an empty event.

aws lambda invoke --function-name multi-az-verify-failover --cli-binary-format raw-in-base64-out --payload '{}' response.json

This is the content of response.json excluding the response key.

{"boto3": "1.44.19", "volumeId": "vol-1234567890abcdef0", "before": {"active": "ap-northeast-1d", "standby": "ap-northeast-1c"}, "after": {"active": "ap-northeast-1d", "standby": "ap-northeast-1c"}}

The swap was not reflected in the after value read inside the Lambda right after failover_volumes. About 3 seconds later, when I ran the same describe-volumes query, the AZs had been swapped.

[
    "ap-northeast-1c",
    "ap-northeast-1d",
    [
        [
            "i-0abcdef1234567890",
            "ap-northeast-1d",
            "attached"
        ],
        [
            "i-1234567890abcdef0",
            "ap-northeast-1c",
            "attached"
        ]
    ]
]

State machine

The state machine is written in JSONata and has 20 states. Since the FailoverVolumes SDK integration was not recognized, only the state FailoverVolume calls Lambda, and the other Tasks use SDK integrations. The Step Functions describeVolumes response does not include MultiAvailabilityZoneConfiguration, so the standby AZ cannot be read. For that reason, step 2 below uses describeInstances to decide the source and destination EC2.

  1. Get the volume ID from the SSM parameter and check the active AZ with describeVolumes
  2. Find the EC2 instances with the Pair tag via describeInstances; the one in the active AZ is the source and the other is the destination
  3. Stop the source and detach the volume
  4. Call Lambda in the state FailoverVolume
  5. Attach to the destination as /dev/xvda and start it

Completion of stop, detach, attach, and FailoverVolume is checked with Wait and Choice loops.

Save the definition as sfn/failback.asl.json. ${FailoverFnArn} in FunctionName is replaced with the Lambda ARN when failback-app.ts loads it. For the same reason as the Lambda, the IAM role and state machine are also in a separate stack in failback-app.ts.

import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
import * as fs from 'fs';

const VOLUME_PARAM = '/ebs-multi-az-verify/volume-id';

class FailbackStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const fnArn = `arn:aws:lambda:${this.region}:${this.account}:function:multi-az-verify-failover`;
    const role = new iam.Role(this, 'FailbackRole', { assumedBy: new iam.ServicePrincipal('states.amazonaws.com') });
    const arn = (type: string) => `arn:aws:ec2:${this.region}:${this.account}:${type}/*`;
    role.addToPolicy(new iam.PolicyStatement({ actions: ['ec2:DescribeInstances', 'ec2:DescribeVolumes'], resources: ['*'] }));
    role.addToPolicy(new iam.PolicyStatement({
      actions: ['ec2:StopInstances', 'ec2:StartInstances', 'ec2:AttachVolume', 'ec2:DetachVolume'],
      resources: [arn('instance'), arn('volume')],
    }));
    role.addToPolicy(new iam.PolicyStatement({
      actions: ['ssm:GetParameter'],
      resources: [`arn:aws:ssm:${this.region}:${this.account}:parameter${VOLUME_PARAM}`],
    }));
    role.addToPolicy(new iam.PolicyStatement({ actions: ['lambda:InvokeFunction'], resources: [fnArn] }));

    const definition = JSON.parse(fs.readFileSync('sfn/failback.asl.json', 'utf8').replace('${FailoverFnArn}', fnArn));
    const machine = new sfn.CfnStateMachine(this, 'Failback', {
      roleArn: role.roleArn,
      definitionString: this.toJsonString(definition),
    });
    new cdk.CfnOutput(this, 'FailbackMachineArn', { value: machine.attrArn });
  }
}

const app = new cdk.App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
new FailbackStack(app, 'MultiAzVerifyFailback', { env });
npx cdkd deploy --all --app "npx tsx failback-app.ts"

FailbackMachineArn from the deploy output is used for execution.

Full text of sfn/failback.asl.json
{
  "Comment": "multi-AZ ボリュームを反対側の AZ の EC2 へ付け替えてフェイルバックする(方式 A: デタッチ → FailoverVolumes → アタッチ)",
  "QueryLanguage": "JSONata",
  "TimeoutSeconds": 900,
  "StartAt": "GetVolumeId",
  "States": {
    "GetVolumeId": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ssm:getParameter",
      "Arguments": { "Name": "/ebs-multi-az-verify/volume-id" },
      "Assign": { "volumeId": "{% $states.result.Parameter.Value %}" },
      "Next": "DescribeVolume"
    },
    "DescribeVolume": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeVolumes",
      "Arguments": { "VolumeIds": ["{% $volumeId %}"] },
      "Assign": { "activeAz": "{% $states.result.Volumes[0].AvailabilityZone %}" },
      "Next": "FindInstances"
    },
    "FindInstances": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeInstances",
      "Arguments": {
        "Filters": [{ "Name": "tag:Pair", "Values": ["multi-az-verify"] }]
      },
      "Assign": {
        "src": "{% $states.result.Reservations.Instances[Placement.AvailabilityZone = $activeAz].InstanceId %}",
        "dst": "{% $states.result.Reservations.Instances[Placement.AvailabilityZone != $activeAz].InstanceId %}",
        "dstAz": "{% $states.result.Reservations.Instances[Placement.AvailabilityZone != $activeAz].Placement.AvailabilityZone %}"
      },
      "Next": "StopSource"
    },

    "StopSource": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:stopInstances",
      "Arguments": { "InstanceIds": ["{% $src %}"] },
      "Next": "DescribeSource"
    },
    "DescribeSource": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeInstances",
      "Arguments": { "InstanceIds": ["{% $src %}"] },
      "Assign": { "srcState": "{% $states.result.Reservations[0].Instances[0].State.Name %}" },
      "Next": "IsSourceStopped"
    },
    "IsSourceStopped": {
      "Type": "Choice",
      "Choices": [{ "Condition": "{% $srcState = 'stopped' %}", "Next": "DetachFromSource" }],
      "Default": "WaitSourceStopped"
    },
    "WaitSourceStopped": { "Type": "Wait", "Seconds": 5, "Next": "DescribeSource" },

    "DetachFromSource": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:detachVolume",
      "Arguments": { "VolumeId": "{% $volumeId %}", "InstanceId": "{% $src %}" },
      "Next": "DescribeDetach"
    },
    "DescribeDetach": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeVolumes",
      "Arguments": { "VolumeIds": ["{% $volumeId %}"] },
      "Assign": { "stillAttached": "{% $exists($states.result.Volumes[0].Attachments[InstanceId = $src]) %}" },
      "Next": "IsDetached"
    },
    "IsDetached": {
      "Type": "Choice",
      "Choices": [{ "Condition": "{% $stillAttached = false %}", "Next": "FailoverVolume" }],
      "Default": "WaitDetached"
    },
    "WaitDetached": { "Type": "Wait", "Seconds": 3, "Next": "DescribeDetach" },

    "FailoverVolume": {
      "Type": "Task",
      "Comment": "validate-state-machine-definition で ec2:failoverVolumes が認識されなかったため、この1状態だけ Lambda を使う",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Arguments": {
        "FunctionName": "${FailoverFnArn}",
        "Payload": { "VolumeId": "{% $volumeId %}" }
      },
      "Next": "DescribeFailover"
    },
    "DescribeFailover": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeVolumes",
      "Arguments": { "VolumeIds": ["{% $volumeId %}"] },
      "Assign": { "volumeAz": "{% $states.result.Volumes[0].AvailabilityZone %}" },
      "Next": "IsFailedOver"
    },
    "IsFailedOver": {
      "Type": "Choice",
      "Choices": [{ "Condition": "{% $volumeAz = $dstAz %}", "Next": "AttachToTarget" }],
      "Default": "WaitFailedOver"
    },
    "WaitFailedOver": { "Type": "Wait", "Seconds": 3, "Next": "DescribeFailover" },

    "AttachToTarget": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:attachVolume",
      "Arguments": { "VolumeId": "{% $volumeId %}", "InstanceId": "{% $dst %}", "Device": "/dev/xvda" },
      "Next": "DescribeAttach"
    },
    "DescribeAttach": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:describeVolumes",
      "Arguments": { "VolumeIds": ["{% $volumeId %}"] },
      "Assign": { "attached": "{% $exists($states.result.Volumes[0].Attachments[InstanceId = $dst and State = 'attached']) %}" },
      "Next": "IsAttached"
    },
    "IsAttached": {
      "Type": "Choice",
      "Choices": [{ "Condition": "{% $attached = true %}", "Next": "StartTarget" }],
      "Default": "WaitAttached"
    },
    "WaitAttached": { "Type": "Wait", "Seconds": 3, "Next": "DescribeAttach" },

    "StartTarget": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:ec2:startInstances",
      "Arguments": { "InstanceIds": ["{% $dst %}"] },
      "Output": {
        "volumeId": "{% $volumeId %}",
        "from": "{% $src %}",
        "to": "{% $dst %}",
        "activeAzBefore": "{% $activeAz %}",
        "activeAzAfter": "{% $dstAz %}"
      },
      "End": true
    }
  }
}

Running the state machine

Execution starts from a state where nothing is attached to the destination EC2 #2. After the Lambda run, the volume is attached to both EC2 instances, so I detached the volume from EC2 #2 and started EC2 #1.

aws ec2 detach-volume --volume-id <ボリューム ID> --instance-id <EC2 #2 の ID>
aws ec2 start-instances --instance-ids <EC2 #1 の ID>
aws ec2 wait instance-running --instance-ids <EC2 #1 の ID>
aws ec2 describe-volumes --volume-ids <ボリューム ID> \
  --query 'Volumes[0].[AvailabilityZone,MultiAvailabilityZoneConfiguration.StandbyAvailabilityZones[0].AvailabilityZone,Attachments[].[InstanceId,AvailabilityZone,State]]'
[
    "ap-northeast-1c",
    "ap-northeast-1d",
    [
        [
            "i-1234567890abcdef0",
            "ap-northeast-1c",
            "attached"
        ]
    ]
]

The ALB returned the response from EC2 #1.

{"instance-id": "i-1234567890abcdef0", "private-ip": "172.31.1.10", "az-id": "apne1-az1", "boot-count": 5}

I ran the state machine.

aws stepfunctions start-execution --state-machine-arn <FailbackMachineArn> --input '{}'
aws stepfunctions describe-execution --execution-arn <実行の ARN>
    "status": "SUCCEEDED",
    "startDate": "2026-12-06T19:25:21.528000+09:00",
    "stopDate": "2026-12-06T19:25:47.296000+09:00",
    "input": "{}",
    "inputDetails": {
        "included": true
    },
    "output": "{\"volumeId\":\"vol-1234567890abcdef0\",\"from\":\"i-1234567890abcdef0\",\"to\":\"i-0abcdef1234567890\",\"activeAzBefore\":\"ap-northeast-1c\",\"activeAzAfter\":\"ap-northeast-1d\"}",

The execution reached SUCCEEDED in 25.8 seconds. The state machine finishes at the point StartInstances is called and does not wait for the EC2 to finish starting. In the execution history, DescribeFailover right after FailoverVolume returned the old AZ, and the next call after a 3-second Wait returned the swapped AZ. About 43 seconds after the execution ended, I checked with describe-volumes and the ALB.

[
    "ap-northeast-1d",
    "ap-northeast-1c",
    [
        [
            "i-0abcdef1234567890",
            "ap-northeast-1d",
            "attached"
        ]
    ]
]
{"instance-id": "i-0abcdef1234567890", "private-ip": "172.31.2.20", "az-id": "apne1-az2", "boot-count": 6}

Summary

Using Step Functions and Lambda, I was able to implement failover of an EC2 instance whose root is a multi-AZ volume.

This Step Functions workflow assumes manual switching. To automate failover that takes over the same volume, you would additionally need to implement an EC2 application health check or an SSM Run Command health check, plus a mechanism to avoid infinite loops.

https://dev.classmethod.jp/articles/ec2-application-status-check-stepfunctions-two-stage-recovery/

This time, the Step Functions SDK integration and CloudFormation (CDK) did not support multi-AZ volumes, so some parts had to be operated with Lambda and the CLI. According to an announcement in September 2026, Step Functions SDK integrations will automatically add integrations for new services and features within a few weeks of release. CloudFormation and Cloud Control API were also announced in November 2026 to keep up with new services faster.

https://aws.amazon.com/jp/about-aws/whats-new/2026/06/aws-step-functions-integrations/
https://dev.classmethod.jp/articles/cloudformation-cloudcontrol-ec2-snapshot/

Once these are supported, I would like to try a failover-capable EC2 configuration with IaC again.

Share this article

AWSのお困り事はクラスメソッドへ