Use CLI to configure active geo-replication for a single database in Azure SQL Database

This Azure CLI script example configures active geo-replication for a single database and fails it over to a secondary replica of the database.

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0 or later. Run az --version to find the version. If you need to install or upgrade, see Install the Azure CLI.

Sample script

Sign in to Azure

If you don't have an Azure subscription, create a free account before you begin.

$subscription = "<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

Run the script

location="East US"


secondaryLocation="West US"


echo "Using resource group $resource with login: $login, password: $password..."

echo "Creating $resource and $secondaryResource..."
az group create --name $resource --location "$location"
az group create --name $secondaryResource --location "$secondaryLocation"

echo "Creating $server in $location and $secondaryServer in $secondaryLocation..."
az sql server create --name $server --resource-group $resource --location "$location" --admin-user $login --admin-password $password
az sql server create --name $secondaryServer --resource-group $secondaryResource --location "$secondaryLocation" --admin-user $login --admin-password $password

echo "Creating $database on $server..."
az sql db create --name $database --resource-group $resource --server $server --service-objective S0

echo "Establishing geo-replication on $database..."
az sql db replica create --name $database --partner-server $secondaryServer --resource-group $resource --server $server --partner-resource-group $secondaryResource
az sql db replica list-links --name $database --resource-group $resource --server $server

echo "Initiating failover..."
az sql db replica set-primary --name $database --resource-group $secondaryResource --server $secondaryServer

echo "Monitoring health of $database..."
az sql db replica list-links --name $database --resource-group $secondaryResource --server $secondaryServer

echo "Removing replication link after failover..."
az sql db replica delete-link --resource-group $secondaryResource --server $secondaryServer --name $database --partner-server $server --yes 

Clean up deployment

Use the following command to remove the resource group and all resources associated with it.

az group delete --name $resource

Sample reference

This script uses the following commands. Each command in the table links to command specific documentation.

Command Description
az sql db replica Database replica commands.

Next steps

For more information on the Azure CLI, see Azure CLI documentation.

Additional SQL Database CLI script samples can be found in the Azure SQL Database documentation.