Skip to main content

Elastic Jobs & Azure Automation

Since Azure SQL Database doesn't have SQL Agent, Microsoft provides two cloud-native automation services: Elastic Jobs (for T-SQL across databases) and Azure Automation (for PowerShell/Python runbooks).

Elastic Jobs — SQL Agent for Azure SQL Database

Elastic Jobs let you run T-SQL scripts across one or more Azure SQL databases on a schedule — the PaaS equivalent of SQL Agent.

Architecture

ComponentWhat It Is
Job AgentAzure resource that hosts and executes jobs (requires a dedicated "job database")
Job DatabaseAn Azure SQL DB that stores job definitions, history, and state
Target GroupWhich databases to run against (single DB, elastic pool, shard map, or list)
JobContainer with steps (T-SQL only)
Job CredentialDatabase-scoped credential for authentication

When to Use Elastic Jobs

ScenarioElastic Jobs?
Run T-SQL across multiple Azure SQL DBs✅ Best choice
Index maintenance across tenant databases
Schema changes across all databases
PowerShell automation❌ Use Azure Automation
Cross-service orchestration❌ Use Logic Apps
Single database scheduled T-SQL✅ (simpler alternatives exist)
🎯 Exam Focus

DP-300 key fact: Elastic Jobs require a dedicated Azure SQL Database as the job database. This is an additional cost. The job agent is a separate Azure resource that you deploy alongside it.

Target Group Types

Target TypeDescription
Single DatabaseOne specific database
Elastic PoolAll databases in a pool
Shard MapAll shards in a shard map
Database ListCustom list of databases across servers
Server (all DBs)All user databases on a logical server

Elastic Jobs setup — enable order

Stand up an Elastic Job
1
Provision job database
Azure SQL DB (S1+ recommended)
Holds metadata + history tables
2
Create Elastic Job Agent
Bind to the job DB
One agent per region/scope
3
Create credentials
Master + scoped credential in job DB
Or use the agent managed identity (recommended)
4
Define target group + members
sp_add_target_group + sp_add_target_group_member
Single DB / pool / shard map / server
5
Create job + steps + schedule
sp_add_job, sp_add_jobstep, then enable
T-SQL only (one statement per step)
Common ordering trap

The job agent identity (or scoped credential) needs db_owner on every target database before steps run — otherwise jobs report Login failed. With managed identity: also create the MI as a contained Entra user in each target DB. Skipping this is the #1 reason "the job runs but does nothing."

Authentication options for the job agent — what each one buys you

Auth methodConditional Access (location-based)Password rotation neededGranular Entra RBACRecommended for elastic jobs?
SQL login (master + DB-scoped credential)❌ Not subject to CA✅ You own it❌ DB-scoped only❌ Legacy only
Database-scoped credential with SQL login
System-assigned managed identity on the job agent❌ Azure-managedDefault choice
User-assigned managed identity on the job agent❌ Azure-managed✅ (re-usable across agents)✅ When sharing across agents
🎯 Exam Focus

Conditional Access trap: Only managed identities (system- or user-assigned) honor Microsoft Entra location-based Conditional Access policies. SQL logins and database-scoped credentials with SQL auth bypass CA entirely — choosing them when the requirement is "block sign-ins from outside the corporate network" is the wrong answer.

Elastic Jobs vs SQL Agent

FeatureSQL AgentElastic Jobs
PlatformVM + MIAzure SQL DB
Step typesT-SQL, PS, SSIS, CmdExecT-SQL only
Multi-databaseMulti-server adminTarget groups
SchedulingBuilt-in schedulerBuilt-in scheduler
CostIncludedJob agent + job DB cost
NotificationsDatabase Mail + operatorsAzure Monitor alerts
HistorymsdbJob database

Azure Automation — PowerShell/Python in the Cloud

Azure Automation runs PowerShell or Python scripts (runbooks) on a schedule or on-demand — no VM required.

Key Concepts

ComponentWhat It Does
Automation AccountContainer for runbooks, schedules, credentials
RunbookPowerShell or Python script
ScheduleWhen the runbook runs
Managed IdentityAuthentication to Azure resources (no passwords)
Hybrid Runbook WorkerRun runbooks on-premises or on specific VMs
WebhookHTTP endpoint to trigger runbooks externally

Common DBA Runbooks

Runbook PurposeWhat It Does
Scale up/downChange Azure SQL vCores on schedule (scale up for batch, down at night)
Pause ServerlessForce auto-pause of serverless databases during off-hours
Index maintenanceRun Ola Hallengren scripts across multiple databases
Backup to BlobCopy backups to secondary storage
Alert responseAuto-remediate when an alert fires
Compliance checkVerify security settings across databases
🎯 Exam Focus

Azure Automation uses Managed Identity for authentication — no stored passwords or connection strings. Always use System Assigned Managed Identity and grant it the minimum required Azure RBAC role (e.g., SQL DB Contributor for scaling operations).

Azure Automation vs Elastic Jobs

AspectElastic JobsAzure Automation
Best forT-SQL across DBsPowerShell/Python automation
Script typesT-SQL onlyPowerShell, Python
Azure resource mgmt✅ (scale, configure, deploy)
Cross-service✅ (any Azure resource)
CostJob agent + DBPer-minute execution
AuthenticationDB credentialManaged Identity
On-prem support✅ (Hybrid Worker)
🏢 Real-World DBA Note

Common pattern: Use Elastic Jobs for database-level T-SQL automation (index maintenance, schema sync) and Azure Automation for infrastructure-level PowerShell automation (scaling, alerting, compliance). They complement each other — they're not competitors.

Azure Logic Apps — Visual Workflow Automation

Logic Apps provide visual, low-code workflow automation with 400+ connectors:

Use CaseWhy Logic Apps
Email on job failureConnect SQL → Office 365 → send email
Approval workflowsSchema change requires manager approval
Multi-service orchestrationSQL → Event Hub → Function → Teams
Scheduled data syncTimer → query SQL → post to API

Logic Apps vs Azure Automation

AspectLogic AppsAzure Automation
StyleVisual designer (low-code)Script (code-first)
Best forWorkflow orchestrationScript execution
Connectors400+ built-inManual REST/SDK calls
CostPer-actionPer-minute
Complex logicClunky for complex codeNatural for scripts

Azure Functions — Timer-Triggered Automation

For developers who prefer code, Azure Functions with a Timer Trigger replace cron jobs:

FeatureDetail
LanguagesC#, Python, Java, JavaScript, PowerShell
TriggerCRON expression (e.g., 0 */5 * * * * for every 5 min)
ScalingAuto-scales (or Consumption plan = pay-per-execution)
Best forCustom automation logic that doesn't fit Automation Runbooks

Anti-Patterns

  • "Use Elastic Jobs to send email." No email step type. Surface failure via Azure Monitor metric alert → Action Group instead.
  • "Spin up an Elastic Job Agent for one job." The Job Agent + dedicated Job DB carry a fixed monthly cost (S1 ≈ $20). Single-DB / single-job? Use a stored proc + Azure Automation runbook on schedule.
  • "Run long T-SQL jobs in Azure Automation." Runbook execution is capped (3 hours fair-share, 9 hours hard limit on Hybrid Worker). A 6-hour CHECKDB will get killed mid-run. Use SQL Agent on MI/VM, or Elastic Jobs with appropriate timeouts.
  • "Hardcode SQL credentials in the runbook script." Use Azure Automation managed identity + Connect-AzAccount -Identity. Never store SQL passwords in code or even Automation variables — use Key Vault secrets pulled at runtime.
  • "Functions Timer Trigger because we already use Functions." Consumption-plan Functions cold-start (~1–3 s), have 5–10 min execution timeout, and bill per-execution. For 5-minute polls of 100 DBs that's ~9000 invocations/day = surprise bill.
  • "Logic Apps for nightly index rebuild." Logic Apps charges per action. A loop over 200 tables = 200+ actions/night. Native SQL Agent (MI) or Elastic Jobs do this for free.
⚠️ Watch Out

Azure Automation has a 500 free runtime minutes per subscription per month. Any runbook polling more than every ~3 minutes burns the free quota in days. Prefer schedule-driven or webhook-driven runbooks over poll loops.


Migration Between Automation Hosts

From → ToPathCost
SQL Agent (MI) → Elastic JobsConvert each step to T-SQL only; create Job DB + AgentRewrite cost; gain cross-DB targeting at scale
SQL Agent → Azure AutomationWrap T-SQL in PowerShell with Invoke-Sqlcmd; managed identityAuth + retry logic to add; gain cross-service orchestration
Windows Task Scheduler → Azure AutomationPort PowerShell as-is into runbook; Hybrid Worker if on-prem depsHybrid Worker = a VM + agent; otherwise free for first 500 min
Cron (Linux) → Azure Functions Timer TriggerRewrite as function; pin runtime versionCold-start risk; switch to Premium plan if predictable
Azure Automation → GitHub Actions / Azure DevOps PipelinesMove runbook to YAML pipeline; use OIDC for authGain CI/CD ergonomics; lose webhook/watcher patterns
Logic Apps for DB ops → Functions or AutomationRewrite workflow as codeCuts per-action billing; loses visual designer
Elastic Jobs → Azure Automation runbook fanning outPowerShell loop over server list; managed identityRemoves Job DB cost; gains scripting flexibility

Most-expensive moves: SQL Agent → Elastic Jobs (T-SQL-only rewrite) and on-prem scheduler → Hybrid Worker (infra).


Real Scenarios

  1. Azure SQL DB SaaS, per-tenant index maintenance across 500 DBsElastic Jobs targeting tenant group, T-SQL only. Driver: only PaaS-native option. Trade-off: extra S0 ≈ $15/mo for the Job control DB.
  2. MI hosting ERP, nightly CHECKDB + index rebuild + stats updateSQL Agent on MI (not Elastic Jobs). Driver: native, free, T-SQL-rich. Trade-off: per-MI scope.
  3. Cross-cloud sync: AWS S3 → Azure Blob → SQL DB ingestAzure Data Factory pipeline + stored proc activity. Driver: built-in connectors + retry. Trade-off: ADF pricing model (per-pipeline-run + per-activity).
  4. Daily failover-test runbook across 200 SQL VMsAzure Automation runbook + managed identity, Hybrid Worker for on-prem ones. Driver: cross-resource, scheduled centrally. Trade-off: Hybrid Worker = an agent on a Windows VM you maintain.
  5. One-off batch: anonymize PII in 50 dev DBsAzure Function with Timer or HTTP trigger, Premium plan to avoid timeout. Driver: code flexibility, can call internal APIs. Trade-off: Premium plan cost; could have been a Runbook for less.

Flashcards

What is required to use Elastic Jobs?
Click to reveal answer
A dedicated Azure SQL Database as the 'job database' plus a Job Agent resource. Both have separate costs.
1 / 5

Quiz

Q1/5
0 correct
You need to run an index maintenance T-SQL script across 50 databases in an Azure SQL Elastic Pool every weekend. What should you use?