In this post, we’ll look at Contained Availability Groups in SQL Server.
Contained Availability Groups look to solve a long-standing issue in SQL Server HA/DR solutions, which is that most of them (Mirroring / Log Shipping / Availability Groups) work at the database level but there can be and often are server-level objects on which that database depends. Classic examples of such server-level dependencies are (but not limited to) logins and agent jobs. These server-level objects need to exist on all the HA/DR nodes as well as requiring careful management (matching SIDs and passwords for logins) and careful configuration (agent jobs that only run when the node is primary etc).
In the case of SQL Server logins, these exist in the master database, which is responsible for all server-level configuration and metadata. In the case of agent jobs, these are stored in the msdb system database, which is responsible for everything SQL Server Agent related (as well as storing backup history, database mail configuration etc). As both of these system databases do not get replicated in HADR scenarios, there is the need for manual synchronisation of objects.
Both instances we will work with in this demo are on SQL Server 2022 Developer Edition and so benefit from Enterprise Edition features. Contained Availability Groups are an Enterprise Edition feature.
Enter Contained Availability Groups
The difference with Contained Availability Groups as opposed to regular Availability Groups is that they include their own independent copy of both the master and msdb databases as part of the availability group and these databases remain synchronised between the two replicas, therefore all the previously manual steps of keeping jobs and logins in line are taken care of for us.
Creating a Contained Availability Group
Here’s how we create a Contained Availability Group using the New Availability Group wizard.
On the very first page we now have an option to check whether the Availability Group is a Contained Availability Group, so we’ll tick that. The sub-option of reuse system database is in case we are setting up a Contained Availability Group that we have set up in the past and we want to reuse the contained system databases the previous AG used. In this example, we’ll ignore the reuse option:

Now we can add the two WideWorldImporters databases:

Once we click Next, we can connect to the two replicas:

I’ll leave the next few tabs as default and jump to the listener tab:

Next up, let’s choose auto seeding as the data synchronisation option:

Now the Availability Group is set up. If we connect to both instances, we can see the contained system databases have been created and they appear like any other normal user database:

They also show up as Availability Group databases:

Testing It Out – Jobs
Now we’ve set up our Contained Availability Group, let’s test out some of the features. Firstly, we’ll create an agent job on SQL01, which is our primary replica. The job will run every minute and populate a simple table in the WideWorldImporters database. The table we are populating is created with the command below:
USE WideWorldImporters;
CREATE TABLE dbo.Ag_Test
(
Id INT IDENTITY(1,1),
MyMessage NVARCHAR(200),
MyTimeStamp DATETIME2
);
Our job will run the following command to insert into the table:
INSERT INTO dbo.Ag_Test VALUES ('Hello From SQL01 Agent',GETDATE());
We can create the job from the SSMS GUI:

Let’s set the job to run every minute:

Finally, let’s add the job logic to populate the table:

As expected, we can now see the job under the SQL01 instance:

After a few minutes, we can verify that the job is inserting data into the table:
USE WideWorldImporters;
SELECT * FROM dbo.Ag_Test ORDER BY Id;

As expected, we can see the job is populating the table at the turn of the minute.
Let’s fail over and see what happens. To do so, we run the following command on the replica we want to be the primary, in our case, SQL02:
ALTER AVAILABILITY GROUP WWIAG_Contained FAILOVER;
Now we’ve failed over, let’s see what happens with our job.
We have failed over and despite having a Contained Availability Group, the job is not populating the table and is now failing.

Here’s the catch – that SQL Server Agent node in the SQL01 object explorer still refers to the instance-level agent and any jobs created using that are created in the msdb database rather than the Availability Group’s msdb database. We can verify this by running the following on SQL01:
USE [msdb];
SELECT 1 AS ExistsInmsdb FROM dbo.sysjobs WHERE name = 'Populate AG Table';
USE [WWIAG_Contained_msdb];
SELECT 1 AS ExistsInContainedmsdb FROM dbo.sysjobs WHERE name = 'Populate AG Table';

So now we know that, let’s try and create the job in the Contained Availability Group msdb database rather than the main instance-level one.
As we know we have no GUI at our disposal, we’ll script out the job we created and target the resulting create commands at the Contained Availability Group’s msdb database (as an aside, is there anyone who creates agent jobs by hand via T-SQL!?)
If we script out the job, the resultant script is targeting msdb via the USE at the top and the three-part named stored procedures so we’ll need to do a find and replace, changing msdb to WWIAG_Contained_msdb. I’ll also change the job name and the text in the job step to help us identify which job has run the insert statement. We can run the below on SQL02, which is the current node, since we failed over.
Below is the T-SQL for the job from the scripted out job, after making the modifications mentioned above:
USE [WWIAG_Contained_msdb]
GO
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
IF NOT EXISTS (SELECT name FROM WWIAG_Contained_msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_add_job @job_name=N'Populate AG Table_TSQLCreated',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'DUALCORE\DualCoreDBA', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Insert',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'TSQL',
@command=N'INSERT INTO dbo.Ag_Test VALUES (''Hello From SQL01 Agent'',GETDATE());',
@database_name=N'WideWorldImporters',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'Every Minute',
@enabled=1,
@freq_type=4,
@freq_interval=1,
@freq_subday_type=4,
@freq_subday_interval=1,
@freq_relative_interval=0,
@freq_recurrence_factor=0,
@active_start_date=20260803,
@active_end_date=99991231,
@active_start_time=0,
@active_end_time=235959,
@schedule_uid=N'c0975364-e340-4494-9a5e-28b3673d75db'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = WWIAG_Contained_msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO
This time, we get an error:
Msg 14234, Level 16, State 1, Procedure sp_verify_subsystem, Line 28 [Batch Start Line 2]
The specified ‘@subsystem’ is invalid (valid values are returned by sp_enum_sqlagent_subsystems).
which is weird, because the following statement returns, amongst other results, the subsystem we are using (T-SQL).
EXEC WWIAG_Contained_msdb.dbo.sp_enum_sqlagent_subsystems;

Doing It Properly
At this point we’ve seen that we can’t create the job via the agent GUI and have it be part of the Contained Availability Group because the GUI represents the agent on the instance to which we are connected. We also can’t create the job via T-SQL against the contained msdb because we get an error regarding the subsystem.
The correct way to create the job is to connect to the AG via the listener, rather than directly connecting to any of the replicas.
Once connected, we can see that the agent contains no jobs, which reflects the fact we could see no records in [WWIAG_Contained_msdb].dbo.sysjobs.

We can now either create the job via the GUI in the listener object explorer (or via T-SQL if we wish), though note we can’t script out the job to T-SQL from this GUI.
I’ve changed the job name so again we can differentiate from the one we created directly against the SQL01 instance. Also note, the server we are connected to on the connection details – it’s the primary replica, SQL02:

Again, for differentiation, I’ve used slightly different text:
INSERT INTO dbo.Ag_Test VALUES ('Hello From AG Agent',GETDATE());

After clicking OK, we can see the job in the listener connection but not the SQL02 connection to which the listener is pointing:

As an aside, when creating the job against the listener using T-SQL, we can target either msdb or the contained msdb with a USE at the top and / or three-part naming, though the job always gets created in the AG’s msdb database and appears in the listener connection.
The job on the listener succeeds, while the job on SQL01 continues to fail:

We can verify the records appear in our table by running the following command against the listener connection or SQL02:
USE [WideWorldImporters];
SELECT * FROM dbo.Ag_Test ORDER BY Id;

Happy Days!
A Skeleton in the Closet
As we failed over to SQL02, let’s fail back to our primary, SQL01 by executing the following:
ALTER AVAILABILITY GROUP [WWIAG_Contained] FAILOVER;
and after a minute or so, check our table again:
USE [WideWorldImporters];
SELECT * FROM dbo.Ag_Test ORDER BY Id;

See how we are getting two records at the turn of the minute now? That’s because we have a version of the job running on the listener’s agent and one on SQL01’s agent.
With this in mind, be careful to only create the jobs against the listener, otherwise you could get some unintended results such as those above, from having duplicate jobs!
Contained System Databases on the Listener
Note that when we connect to the Contained Availability Group via the listener, the contained databases don’t show in the user database list and that is because they are presented to the user as the plain old msdb and master system databases:

We can prove this by creating an object in WWIAG_Contained_msdb on the primary node (now SQL01) and we will see that object appear in msdb on the listener connection so running the following on SQL01 will create a user table:
USE [WWIAG_Contained_msdb];
CREATE TABLE dbo.CreatedInContainedMSDB
(
a INT
);
and when connected to our listener, this shows us that the two databases are one and the same:
USE [WWIAG_Contained_msdb];
SELECT * FROM sys.tables WHERE name = 'CreatedInContainedMSDB';
USE [msdb];
SELECT * FROM sys.tables WHERE name = 'CreatedInContainedMSDB';

Testing It Out – Logins
Now that we know how jobs work, we can get an understanding of how logins will work in Contained Availability Groups. I won’t go into as much detail for the sake of not wanting to rehash the above again, but very briefly, we can prove logins work in the same way.
On SQL01, create a login in the master database and the contained master database:
USE master;
CREATE LOGIN SQL01Login WITH PASSWORD = 'My5tr0ngp455w0rd_';
USE WideWorldImporters;
CREATE USER SQL01Login FOR LOGIN SQL01Login;
USE WWIAG_Contained_master;
CREATE LOGIN SQL01Login_Contained WITH PASSWORD = 'My5tr0ngp455w0rd_';
USE WideWorldImporters;
CREATE USER SQL01Login_Contained FOR LOGIN SQL01Login_Contained;
Against the listener, create a login in the master database (we can’t create one in the _Contained master database because as we saw earlier, when connecting to the listener, we can’t explicitly connect to the _Contained database):
USE WideWorldImporters;
CREATE LOGIN ListenerLogin WITH PASSWORD = 'My5tr0ngp455w0rd_';
CREATE USER ListenerLogin FOR LOGIN ListenerLogin;
On SQL01, we can verify that both logins we created were just against the instance master database (because when connected directly to a replica the create login command creates the login against the instance master database, regardless of what msdb database context we are in) we can also see that the Contained master database just returns the same logins as the instance master database:
SELECT * FROM master.sys.sql_logins WHERE name IN ('SQL01Login','SQL01Login_Contained','ListenerLogin');
SELECT * FROM WWIAG_Contained_master.sys.sql_logins WHERE name IN ('SQL01Login','SQL01Login_Contained','ListenerLogin');

Whereas on the listener, we can see that everything we did against SQL01, regardless of which master database, is nowhere to be seen and all we can see is the login that was created by the CREATE LOGIN command run against the listener:
SELECT * FROM master.sys.sql_logins WHERE name IN ('SQL01Login','SQL01Login_Contained','ListenerLogin');

This is also reflected within the object explorer:

And sure enough, if we try to connect to the listener with the login we created on SQL01, it has no knowledge of its existence:


Conclusion
We’ve looked at what contained databases are and what the problem is that they solve. We also looked at a few pitfalls and learned that all server-level objects should be administered via the listener connection when working with Contained Availability Groups or we get some unexpected behaviour.
