Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 39 additions & 21 deletions samples/manage/azure-automation-automated-export/AutoExport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ Add-Type -TypeDefinition @"
$databaseServerPairs =
@([pscustomobject]@{serverName="SAMPLESERVER1";databaseName="SAMPLEDATABASE1"},
[pscustomobject]@{serverName="SAMPLESERVER1";databaseName="SAMPLEDATABASE2"},
[pscustomobject]@{serverName="SAMPLESERVER2";databaseName="SAMPLEDATABASE3"});
[pscustomobject]@{serverName="SAMPLESERVER2";databaseName="SAMPLEDATABASE3"}
);

$serverCred = Get-AutomationPSCredential -Name 'NAMEOFSERVERCREDENTIAL1';
# The Credentials for the database servers
$serverCred1 = Get-AutomationPSCredential -Name 'NAMEOFSERVERCREDENTIAL1';
$serverCred2 = Get-AutomationPSCredential -Name 'NAMEOFSERVERCREDENTIAL2';
$serverCredentialsDictionary = @{'SAMPLESERVER1'=$serverCred;'SAMPLESERVER2'=$serverCred2}
$serverCredentialsDictionary = @{
'SAMPLESERVER1'=$serverCred1;
'SAMPLESERVER2'=$serverCred2;
}

# The number of databases you want to have running at the same time.
$batchingLimit = 10;
Expand All @@ -31,11 +36,12 @@ $retryLimit = 5;
# The number of minutes you want to wait for an operation to finish before you fail.
$waitInMinutes = 30;

# Connection Asset Name for Authenticating (Keep as AzureClassicRunAsConnection if you created the default RunAs accounts)
$connectionAssetName = "AzureClassicRunAsConnection";

$storageKeyVariableName = "STORAGEKEYVARIABLENAME";
$storageAccountName = "STORAGEACCOUNTNAME";
$automationCertificateName = "CERTIFICATENAME";
$subId = "00000000-0000-0000-0000-000000000000";
$subName = "SUBSCRIPTIONNAME";
$storageContainerName = "STORAGECONTAINERNAME";

function LogMessage($message)
{
Expand Down Expand Up @@ -133,21 +139,19 @@ function CheckCopy($dbObj)
# This function starts the export. If there is an error, we set the state to ToDrop. Otherwise, we set the state to Exporting.
function StartExport($dbObj)
{
# Setup the server connection that the storage account is on.
$serverManageUrl = "https://autoexportserver.database.windows.net";
# Get the current time to use as a unique identifier for the blob name.
$currentTime = Get-Date -format "_yyyy-MM-dd_HH:mm.ss";
$blobName = $dbObj.DatabaseName + "_ExportBlob" + $currentTime;
# Use the stored credential to create a server credential to use to login to the server.
$servercredential = $global:serverCredentialsDictionary[$dbObj.ServerName];
$serverCredential = $global:serverCredentialsDictionary[$dbObj.ServerName];
# Set up a SQL connection context to use when exporting.
$ctx = New-AzureSqlDatabaseServerContext -ServerName $dbObj.ServerName -Credential $servercredential;
$ctx = New-AzureSqlDatabaseServerContext -ServerName $dbObj.ServerName -Credential $serverCredential;
# Get the storage key to setup the storage context.
$storageKey = Get-AutomationVariable -Name $global:storageKeyVariableName;
# Get the storage context.
$stgctx = New-AzureStorageContext -StorageAccountName $global:storageAccountName -StorageAccountKey $storageKey;
# Start the export. If there is an error, stop the export and set the state to ToDrop.
$dbObj.Export = Start-AzureSqlDatabaseExport -SqlConnectionContext $ctx -StorageContext $stgctx -StorageContainerName autoexportcontainer -DatabaseName $dbObj.DatabaseCopyName -BlobName $blobName;
$dbObj.Export = Start-AzureSqlDatabaseExport -SqlConnectionContext $ctx -StorageContext $stgctx -StorageContainerName $global:storageContainerName -DatabaseName $dbObj.DatabaseCopyName -BlobName $blobName;
# $? is true if the last command succeeded and false if the last command failed. If it is false, go to the ToDrop state.
if (-not $? -and $global:retryLimit -ile $dbObj.RetryCount)
{
Expand All @@ -166,7 +170,7 @@ function StartExport($dbObj)
}
# Set the state to Exporting.
$dbObj.DatabaseState = ([DatabaseState]::Exporting);
LogMessage ("Exporting " + $dbObj.DatabaseCopyName);
LogMessage ("Exporting " + $dbObj.DatabaseCopyName + " with RequestID: " + $dbObj.Export.RequestGuid);
$dbObj.OperationStartTime = Get-Date;
}

Expand All @@ -187,7 +191,7 @@ function CheckExport($dbObj)
{
# If the status is "Failed" and we have more retries left, try to export the database copy again.
LogMessage ("The last export failed on database " + $dbObj.DatabaseName + ", going back to ToExport state to try again");
LogMessage $check
LogMessage $check.ErrorMessage
$dbObj.DatabaseState = ([DatabaseState]::ToExport);
$dbObj.RetryCount++;
return;
Expand Down Expand Up @@ -224,7 +228,7 @@ function ExportProcess
$dbsToCopy = $global:dbs | Where-Object DatabaseState -eq ([DatabaseState]::ToCopy);
for($i = 0; $i -lt $dbsToCopy.Count; $i++)
{
LogMessage $dbsToCopy[$i];
LogMessage "Database Name: $($dbsToCopy[$i].DatabaseName) State: $($dbsToCopy[$i].DatabaseState) Retry Count: $($dbsToCopy[$i].RetryCount)";
StartCopy($dbsToCopy[$i]);
}

Expand All @@ -239,7 +243,7 @@ function ExportProcess
$dbsToExport = $global:dbs | Where-Object DatabaseState -eq ([DatabaseState]::ToExport);
for($i = 0; $i -lt $dbsToExport.Count; $i++)
{
LogMessage $dbsToExport[$i];
LogMessage "Database Name: $($dbsToExport[$i].DatabaseName) State: $($dbsToExport[$i].DatabaseState) Retry Count: $($dbsToExport[$i].RetryCount)";
StartExport($dbsToExport[$i]);
}

Expand All @@ -254,7 +258,7 @@ function ExportProcess
$dbsToDrop = $global:dbs | Where-Object DatabaseState -eq ([DatabaseState]::ToDrop);
for($i = 0; $i -lt $dbsToDrop.Count; $i++)
{
LogMessage $dbsToDrop[$i];
LogMessage "Database Name: $($dbsToDrop[$i].DatabaseName) State: $($dbsToDrop[$i].DatabaseState) Retry Count: $($dbsToDrop[$i].RetryCount)";
StartDrop($dbsToDrop[$i]);
}

Expand All @@ -266,11 +270,25 @@ function ExportProcess
}
}

# Get the certificate to authenticate the subscription
$cert = Get-AutomationCertificate -Name $global:automationCertificateName;
# Set the subscription to use
Set-AzureSubscription -SubscriptionName $global:subName -Certificate $cert -SubscriptionId $global:subID;
Select-AzureSubscription -Current $global:subName;
# Authenticate to Azure with certificate
Write-Verbose "Get connection asset: $connectionAssetName" -Verbose;
$automationConnection = Get-AutomationConnection -Name $connectionAssetName;
if ($automationConnection -eq $null)
{
throw "Could not retrieve connection asset: $connectionAssetName. Assure that this asset exists in the Automation account.";
}

$certificateAssetName = $automationConnection.CertificateAssetName;
Write-Verbose "Getting the certificate: $certificateAssetName" -Verbose;
$automationCertificate = Get-AutomationCertificate -Name $certificateAssetName;
if ($automationCertificate -eq $null)
{
throw "Could not retrieve certificate asset: $certificateAssetName. Assure that this asset exists in the Automation account.";
}

Write-Verbose "Authenticating to Azure with certificate." -Verbose;
Set-AzureSubscription -SubscriptionName $automationConnection.SubscriptionName -SubscriptionId $automationConnection.SubscriptionID -Certificate $automationCertificate;
Select-AzureSubscription -SubscriptionId $automationConnection.SubscriptionID;

$currentIndex = 0;
for($currentRun = 0; $currentRun -lt ([math]::Ceiling($databaseServerPairs.Length/$batchingLimit)); $currentRun++)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
# The storage key for the storage account you are using.
$storageKey = Get-AutomationVariable -Name "STORAGEKEYVARIABLENAME";
# The name of the storage container you are using.
$storageContainer = "STORAGECONTAINERNAME";
# Set up the storage context for the storage account.
$context = New-AzureStorageContext -StorageAccountName "STORAGEACCOUNTNAME" -StorageAccountKey $storageKey
# Get all of the blobs in the storage account.
$blobs = Get-AzureStorageBlob -Container $storageContainer -Context $context
#Azure Automation String Variable name for your Storage Account Key
$storageKeyVariableName = "STORAGEKEYVARIABLENAME";
#Name of your Storage Account
$storageAccountName = "STORAGEACCOUNTNAME";
#Name of your Storage Container
$storageContainerName = "STORAGECONTAINERNAME";
# Set the number of days that you want the blob to be stored for.
$retentionInDays = 30


# Get the storage key
$storageKey = Get-AutomationVariable -Name $storageKeyVariableName;
# Set up the storage context for the storage account.
$context = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageKey
# Get all of the blobs in the storage account.
$blobs = Get-AzureStorageBlob -Container $storageContainerName -Context $context


foreach($blob in $blobs)
{
# Get the current time to compare to the time that the blob was created.
Expand Down
76 changes: 45 additions & 31 deletions samples/manage/azure-automation-automated-export/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,23 @@ author: trgrie-msft

Provides the scripts and lists the steps to set up automatically exporting your databases to Azure Storage with Azure Automation.

## Azure Automation Set Up

1. Create and uploade the certificates that you will use to authenticate your connection to azure.
- Run powershell as admin.
- Run the New-SelfSignedCertificate command: New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName <certificateName>
- Create a corresponding pfx certificate by taking the thumbprint of the newly created certificate and running these commands:
- $CertPassword = ConvertTo-SecureString -String <YourPassword> -Force -AsPlainText
- Export-PfxCertificate -Cert cert:\localmachine\my\<thumbprint> -FilePath <PathAndFileName>.pfx -Password $CertPassword
- Upload the .cer file to your subscription [here][https://manage.windowsazure.com/]
- Upload the .pfx file to the certificates under Assets in the automation account that you want to use on Azure. You will use the password you gave in the previous step to authenticate it.
2. Create new a new credentials asset to authenticate your server with.
- Under assets, click on Credentials, and then click on Add a credential.
- Name the credential and give the username and password that you will be logging into the server with.
3. Create a new variable asset to pass the storage key of the Azure storage account you will be using.
- Under assets, click on variables and then Add a variable.
- Give the value of the storage key and you can make it encrypted so that only Azure Automation can read the variable and it won't show the key in plaintext if someone looks at the variable.
4. Set Up Log Analytics (OMS) and Alerts
- If you don't have Log Analytics set up on your Azure account, follow [these][https://azure.microsoft.com/en-us/documentation/articles/automation-manage-send-joblogs-log-analytics/] instructions for setting it up.
## Prerequisite Set Up

1. Create and set up your Azure Automation Account
- Create an Azure Automation Account by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-sec-configure-azure-runas-account).
2. Add Azure Automation Credential assets for your SQL Azure servers
- Create your Automation Credential for each of your SQL Azure servers you intend to export by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-credentials#creating-a-new-credential-asset).
3. Create the Azure Storage Account to hold your bacpac files
- Create the Storage Account by [following the instructions here](https://docs.microsoft.com/en-us/azure/storage/storage-create-storage-account#create-a-storage-account).
- Create the Blob Storage Container
- Go to your Storage Account
- Click the Blobs tile
- Click the Add Container button
- Name the container, keep the access type as Private, and click the Create button
- Copy your Storage Account access keys by [following the instructions here](https://docs.microsoft.com/en-us/azure/storage/storage-create-storage-account#view-and-copy-storage-access-keys).
- Create an Azure Automation string Variable asset for your Storage Account access key by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-variables#creating-an-automation-variable).
4. Set Up Log Analytics (OMS) and Alerts (optional for alerting)
- If you don't have Log Analytics set up on your Azure account, [follow these](https://docs.microsoft.com/en-us/azure/automation/automation-manage-send-joblogs-log-analytics) instructions for setting it up.
5. Set Up Log Analytics Alerts
- To send yourself an email if an error occurs or one of the jobs fails, you need to set up alerts.
- Select your log analytics account that you want to use in the azure portal and click on the OMS Portal box under Management.
Expand All @@ -36,18 +35,33 @@ Provides the scripts and lists the steps to set up automatically exporting your

## Script Set Up

Save the AutoExport.ps1 and AutoExportBlobRetention.ps1 files locally to make these edits

1. In the AutoExport.ps1 script, here are the values that need to be modified:
- $databaseServerPairs: This is where you put in the names of the databases you want to export along with the name of the server they are on.
- $serverCredentialsDictionary: If you are backing up from multiple servers, you can setup all of the credentials here and look them up by the server’s name later.
- $batchingLimit: This tells the script how many databases can be worked on at the same time (basically, the maximum number of database copies that there will be at once).
- $retryLimit: This tells the script how many times it can retry an operation.
- $waitTimeInMinutes: This tells the script how long it can wait for an operation to complete before it fails.
- $storageKeyVariableName: This is the AutomationAccount you created the StorageKey variable under (probably the same one you are running the RunBook under) and -Name is the name of the variable.
- $storageAccountName: This is the name of the storage account you are exporting to.
- $automationCertificateName for Get-AutomationCertificate: This is the name of the certificate you setup to authenticate with Azure.
- $subId: The ID of the subscription you are using. This will be used to tell Azure Automation which subscription to use.
- $subName: The name of the subscription you are using. This will be used to tell Azure Automation which subscription to use.
- **$databaseServerPairs:** This is where you put in the names of the databases you want to export along with the name of the server they are on.
Add them in the format: `[pscustomobject]@{serverName="SAMPLESERVER1";databaseName="SAMPLEDATABASE1"}` make sure to comma separate the items
- **$serverCredentialsDictionary:** If you are backing up from multiple servers, you can setup all of the credentials here and look them up by the server’s name later.
Add a $serverCred variable in the format `$serverCred1 = Get-AutomationPSCredential -Name 'NAMEOFSERVERCREDENTIAL1';` for each Azure Automation Credential you created. Increment the variable name (eg. $serverCred2 $serverCred3) for each one.
Add the $serverCreds to the dictionary in the format `'SAMPLESERVERNAME1'=$serverCred1;`
- **$batchingLimit:** This tells the script how many databases can be worked on at the same time (basically, the maximum number of database copies that there will be at once).
- **$retryLimit:** This tells the script how many times it can retry an operation.
- **$waitTimeInMinutes:** This tells the script how long it can wait for an operation to complete before it fails.
- **$storageKeyVariableName:** This is the Azure Automation string Variable name you created to store your Storage Key.
- **$storageAccountName:** This is the name of the storage account you are exporting to.
- **$connectionAssetName:** Connection Asset Name for Authenticating (Keep as AzureClassicRunAsConnection if you created the default RunAs accounts)
2. In AutoExportBlobRetention, here are the values that need to be modified:
- -Name for Get-AzureAutomationVariable: This is the AutomationAccount you created the StorageKey variable under (probably the same one you are running the RunBook under) and -Name is the name of the variable.
- $storageContainer: This is the name of the storage container where you will be monitoring the exported blobs.
- $retentionInDays: This is how many days you want to keep the exported blobs stored for before deleting.
- **$storageKeyVariableName:** This is the Azure Automation string Variable name you created to store your Storage Key.
- **$storageAccountName:** This is the name of your Storage Account you exported your bacpacs to.
- **$storageContainerName:** This is the name of the storage container where you will be monitoring the exported blobs.
- **retentionInDays:** This is how many days you want to keep the exported blobs stored for before deleting.

## Adding the Script to Azure Automation

1. Import the scripts as Azure Automation Runbooks
- Create runbooks from the scripts you editted above by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-creating-importing-runbook#to-import-a-runbook-from-a-file-with-the-azure-portal) for both scripts.
- [Make sure to publish the runbook.](https://docs.microsoft.com/en-us/azure/automation/automation-creating-importing-runbook#to-publish-a-runbook-using-the-azure-portal)
2. Add a schedule for your Automated Export runbook
- Create a recurring schedule by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-schedules#to-create-a-new-schedule-in-the-azure-portal).
- Link the schedule(s) you created to the runbooks by [following the instructions here](https://docs.microsoft.com/en-us/azure/automation/automation-schedules#to-link-a-schedule-to-a-runbook-with-the-azure-portal).

You should now be all set up for Automated Exports into blob storage of your selected SQL Azure databases.