top of page

Azure SQL Databases Maintenance Using Azure Automation and PowerShell


ree

Author: Eric Rouach, Madeira Data Solutions

Date: March 2022


The following guide describes how to execute and schedule any T-SQL command for Each Azure SQL database inside a given Azure SQL Server.


Pre-requisites:

· an existing Azure subscription

· an existing Azure SQL Server and Azure SQL Database(s)


Let’s begin!


In your Microsoft Azure subscription, create a new Automation Account:


ree

Select your subscription, an existing Resource group (or create a new one if needed), Automation account name and Region. Then, click Review + Create:



ree

You should be directed to the resource’s deployment screen. Once completed, click Go to resource:



ree

This will direct you to your Automation account’s home page.

For future use in our PowerShell script and since we do not want our Server’s credentials to appear in clear text, our next step will the creation of a credential within the Automation account. This will hold the credentials (username and password) that we’d use for connecting to our SQL Server target.


From the leftmost pane, select Credentials, then Add a credential:


ree

Give your credential a meaningful name and enter the credentials. Then click Create:



ree

Next, you must add the SqlServer module. From the leftmost pane, select Modules and click Add a module:


Select the following options:



ree

From the gallery, choose the SqlServer module:



ree

Click Select, then add the Runtime version, and click Import:



ree

The import process may take a few minutes.



You now need to create a new Runbook. From the leftmost pane, select Runbooks, then Create a new Runbook:




ree

At the Runbook creation page, fill the fields as suggested below and click Create. The description field is optional.



ree

You will be directed to the Runbook edit page.



Copy and paste the PowerShell code into the code canvas, from the latest version in our Madeira Toolbox:



ree

You may notice that the Azure SQL Server’s credentials are called in the PowerShell script using the Get-AutomationPSCredential CMDLET.


You may also notice that the table creation command is called using a URI from GitHub which contains the T-SQL command. You may replace the second $Query variable with a T-SQL command.


Click Save and Publish.



ree

You will be directed to the Runbook’s main page where you should check if it works as expected by running it manually. Click the Start button:



ree

In this use-case, your test table should be created in all Azure SQL Databases.


All that’s left to do is creating a schedule for your Runbook. From the Runbook’s main page, click on Link to schedule:



ree

Then, choose the Schedule option and add a schedule:



ree

Simply fill the fields and create the schedule.

That’s it! You’re done!



Comments


STAY IN TOUCH

Get New posts delivered straight to your inbox

Thank you for subscribing!

bottom of page