T-SQL: Only run SQL agent job on primary node

In a SQL Always On setup, the SQL agent jobs are not synced between the different nodes. This means you need to manually create them on the other nodes. For read-write jobs, you can only run them on the active node of course. You should modify the SQL agent job a little bit in order to check if the database has the primary role, and only execute the code if that’s the case. The code below can be used for this.

If sys.fn_hadr_is_primary_replica ( 'MY_DB' ) <> 1  
BEGIN 
    -- This is not the primary replica, exit without error. 
	 print 'Secondary node'
END 
-- This is the primary replica, continue to run the job... 
else
begin
  --YOURACTIONS HERE
end