How to use Azure Automation with ConfigMgr

167_00

Many of us have at least at some point had to automate something. Automation to me, is a wide subject and there are many methods available to automate a task. In the past, we’ve leveraged software like Orchestrator, Task Scheduler together with scripts and what not to perform some kind of task over and over again. In the world we live in today, everything is about automation. What about automation with ConfigMgr? How can that be accomplished you may ask. Simple, you identify a common task that you have to do from time to time, over and over again, and you build a solution that will carry out that task for you. Now that may have sounded extremely vague, but it’s really not. Think of the reference image creation process that everyone (at least for now) are dealing with. You may have thought that it would be nice if you could simply import the newly created WIM file directly into ConfigMgr.

In this blog post I will go through the required steps and basic setup to get you started with Azure Automation. We’ll create an Azure Automation runbook and have that import a device into ConfigMgr by giving it a few necessary parameters. About the automated task that I talked about earlier, I’ll cover that in a later post since that requires a bit more fiddling since, as of writing, you cannot execute an Azure Automation runbook that has a webhook attached and run it on a hybrid worker. There’s also a limitation with running PowerShell scripts in the current version of Windows PE 10 that will cause unexpected errors.

Think about what you could possibly automate with this service when an API is available for Microsoft Intune, I’m so excited about this and can’t wait to start digging into that. But for now we’ll have to make do with ConfigMgr, which is not so bad either to be frank.

That was a lot of new words, let’s get started before we fall asleep.

Overview

  • What you’ll need to get started
  • Create an Automation Account
  • Create an Operational Insight workspace
  • Manage your Operational Insight workspace
  • Add an Asset
  • Create a Runbook
  • Execute the Runbook

What you’ll need to get started

One obvious thing that you need to have in place in order to use Azure Automation is a valid subscription for Azure. Other than that you’re all set. Although, since we’re talking about automation, a good skill set when it comes to PowerShell is more or less a requirement. Previously, if you’ve played around with Azure Automation before, you know that you only had an option to create a Runbook based upon PowerShell Workflow. Recently, in fact very recently, you now also have the possibility of running PowerShell scripts. Since I’m not very experienced with Workflows in PowerShell, this blog post will only cover Runbooks based on PowerShell scripts in Azure Automation.

During this post, you’ll notice that I switch between the old Azure portal and the new. That’s simply because Microsoft has not incorporated all the pieces that’s required to setup Azure Automation in the new portal as of writing.

Create an Automation Account

Before we jump into all the fun stuff, I mean scripting, we need to setup a few things to enable Azure Automation. First off we create what Microsoft refers to as a Automation Account. Within this Automation Account, you’ll find your Runbooks, Assets etc.

1. Log on to portal.azure.com, browse to Automation Accounts and click Add. If you can’t see the Automation Accounts meny, click on Browse at the bottom and scroll down to Automation Accounts. I suggest that you click the small favorite button, in the shape of a star, so you’ll get quick access to it in the future.
167_18
2. Name the Automation Account, select a region near you and click Create.
167_19
3. Click on the Refresh button to see your newly created Automation Account and then click on your Automation Account.
167_20
4. Click on the Key button.
167_21
5. Copy the Primary Access Key and URL and save it for later use when we’re going to setup the hybrid worker for this Automation Account.
167_22
Now that we have our Automation Account setup, we can move on to the next step which is to create an Operational Insight workspace.

Create an Operational Insight workspace

Operational Insights is a part of the Microsoft Operations Management Suite (OMS), which is a Software-as-a-Service in Azure. It consists of several functions (or solutions), but in our case we’re only interested in the Automation function. I do recommend though that you check out the other functions in OMS, since it has a great value for organizations.

1. Login to manage.windowsazure.com, scroll down in the left menu, click on Operational Insights and click Create a workspace.
167_1
2. Name the workspace accordingly, select a Tier, location and click on Create Workspace.
167_2
3. Select your newly created Operational Insights workspace.
167_3
4. Click on Manage. You’ll now be directed to the Microsoft Operations Management Suite portal.
167_4
5. Click on the Getting started tile.
167_5
6. Deselect all of the solutions except for Automation and click Add selected Solutions.
167_6
With our Automation solution added, the next step would be to configure a data source. This is our hybrid worker that we’ll install on on-prem server that we have running in our environment. It’s important to know that the hybrid worker is an agent that connects to the OMS service, and it does so by establishing a tunnel from inside your network. That literally means that you won’t have to open any incoming traffic in your firewall, which is a huge plus in my opinion.

Manage your Operational Insight workspace

Before you go ahead and follow the steps below, take a minute and identify a server where you’re able to install the hybrid worker agent. I don’t have any good suggestions, other than it should perhaps not be any critical application server or like wise in your environment. Installing a dedicated server just for the purpose of hosting the hybrid worker is in my opinion not necessary.

1. Click on step 2 in the Getting started panel.
167_7
2. Choose the desired platform for the hybrid worker agent and download the software. Also make a note of the Workspace ID and the Primary Key. We’ll use these two strings during the installation of the hybrid worker agent in order to connect it to our instance of OMS.
167_8
3. Once you’ve downloaded the setup file for the hybrid worker, launch it.
167_9
4. Click Next on the welcome page.
167_10
5. Agree to the license terms.
167_11
6. Select the default installation path, or alter it. I suggest that you leave the default in order to follow along for this demonstration. We’ll import a PowerShell module at a later stage, where we need to know the installation path. Click Next.
167_12
7. Select Connect the agent to Microsoft Azure Operational Insights and click Next.
167_13
8. Now’s the time to enter the Workspace ID and Primary Key (referenced as Workspace Key in the agent setup) that we made a note of earlier from the page where we downloaded the agent. Click Next.
167_14
9. If the Workspace ID and Primary Key was entered correctly, you’ll be presented with the page as shown below. I’ve sometimes found that there might be a slight delay of a couple of minutes even, before the agent is able to recognize the Workspace ID and Primary Key. If you’re experience issues where the wizard complains about the specified input, wait a couple of minutes and try again, it should work better after that. Click Install.
167_15
10. Once the installation has finished, click Finish.
167_16
11. We now have to load a PowerShell module that came with the agent installation. This module will assist in registering the hybrid worker. Open an elevated PowerShell console and run the following command:

Import-Module "C:\Program Files\Microsoft Monitoring Agent\Agent\AzureAutomation\7.2.7037.0\HybridRegistration\HybridRegistration.psd1"

167_17
12. Next up is to add a hybrid worker by running a cmdlet called Add-HybridRunbookWorker in the PowerShell module that we just imported. Remember when I asked you to take a note of the Primary Access Key and URL in the Manage Keys section on your Automation Account? This is where we’ll be using those. In the command below, the Endpoint parameter reference to the URL and the Token parameter reference Primary Access Key. You’ll also need to specify a name for the hybrid worker. The name parameter allows you to group multiple workers into a collection. If the name exists it will add a worker to the group, otherwise a new group will be created automatically. Run the following command where you add token and endpoint:

Add-HybridRunbookWorker -Name "ConfigMgrAutomation" -Endpoint 'URL' -Token 'Primary_Access_Key'

167_23
13. Once the command has successfully completed, your hybrid worker is now installed and registered. If you go back to the OMS portal and refresh the current page, the Getting started panel will now show that step 1 and step 2 has completed successfully. We do not need to add any logs.
167_24
14. Go to the Azure portal under your Automation Account and refresh that as well. You’ll now see the hybrid worker showing up under the Hybrid Worker Groups tile.
167_25
With our hybrid worker setup, let’s continue.

Add an Asset

So far so good, we’ve now completed all the necessary steps in order to setup Azure Automation. What we could do now is to simply create a Runbook and start playing around. But since this post is about using Azure Automation together with ConfigMgr, there’s one thing that we need to do first. If you’ve ever done any scripting against the SMS Provider, or used the PowerShell module for ConfigMgr, you’re probably familiar with that you need to authenticate yourself. Meaning that you have to run your script as an user with the proper permissions. For us to do so with Azure Automation, we need to create a so called Asset. An Asset in your Automation Account can be several things, like a certificate, a schedule, module, variable but also a credential. In this scenario, we’ll need to authenticate ourselves in the PowerShell script that we’ll use in the Runbook that we’re about to create, and to do so, we need to add a credential Asset. In this demonstration, I’ll add an Asset for my Full Administrator account in ConfigMgr called CONTOSO\Administrator.

It’s important to know that the hybrid worker is running in the SYSTEM context of the server that you installed it on. You could simply just give the computer account of the server hosting the hybrid worker, full administrator access to ConfigMgr. In some organizations, that might not be a align with internal policies, but if it does, I’d highly recommend it as you’ll be able to run your code simply as is, without leveraging the Invoke-Command cmdlet that you’ll see me doing later on.

1. Go to your Automation Account in the Azure portal and select Assets.
167_26
2. Click on the Credentials tile.
167_27
3. Click on Add a credential.
167_28
4. Specify a name for the Asset credential. It’s important that you specify a name that you’ll remember, as we’ll reference this later when we create the Runbook and add out script. Make sure that you also specify the NETBIOS name of your domain, e.g. CONTOSO, in the User name field. Click Create.
167_29
5. The Asset credential has now been added and we’re ready to start creating our Runbook.
167_30

Create a Runbook

It’s now time for the fun part, creating a Runbook and add some code into it. When you create a Runbook in Azure Automation for ConfigMgr, you may think that you could simply just start writing your code, and hope that it executes correctly. I talked about it earlier in this blog post, that the hybrid worker is running in the SYSTEM context on the server hosting the agent. This means that you’d either have to add the computer account to ConfigMgr giving it proper permissions to perform the tasks at hand, or you’ll have to authenticate with your Asset credential that we’ve recently just created. In this blog post, I’ll leverage my Asset credential, and wrap my code in a script block that will run remotely on the ConfigMgr site server under the credentials specified in the Asset credential.

Below is the code that I’m going to use in order to import a device into ConfigMgr. Save the code for usage later.

param(
    [parameter(Mandatory=$true, HelpMessage="Site server where the SMS Provider is installed")]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Connection -ComputerName $_ -Count 1 -Quiet})]
    [string]$SiteServer,
    [parameter(Mandatory=$true)]
    [string]$DeviceName,
    [parameter(Mandatory=$true)]
    [ValidatePattern('^([0-9a-fA-F]{2}[:]{0,1}){5}[0-9a-fA-F]{2}$')]
    [string]$MACAddress,
    [parameter(Mandatory=$false)]
    [string]$CollectionName
)
# Get credential
$Credential = Get-AutomationPSCredential -Name 'FullAdministrator'

# Determine SiteCode from WMI on remote Site server
$SiteCodeScriptBlock = {
	param($SiteServer)
    $SiteCodeObjects = Get-WmiObject -Namespace "root\SMS" -Class SMS_ProviderLocation -ComputerName $SiteServer -ErrorAction Stop
    foreach ($SiteCodeObject in $SiteCodeObjects) {
        if ($SiteCodeObject.ProviderForLocalSite -eq $true) {
			[PSCustomObject]@{
            	SiteCode = $SiteCodeObject.SiteCode
			}
        }
    }
}
$SiteCodeCommand = Invoke-Command -ComputerName $SiteServer -ScriptBlock $SiteCodeScriptBlock -Credential $Credential -ArgumentList $SiteServer
$SiteCode = $SiteCodeCommand.SiteCode

# Import device
$ImportScriptBlock = {
	param($SiteServer, $SiteCode, $DeviceName, $MACAddress)
	$WMIConnection = ([WMIClass]"\\$($SiteServer)\root\SMS\site_$($SiteCode):SMS_Site")
    $NewEntry = $WMIConnection.psbase.GetMethodParameters("ImportMachineEntry")
    $NewEntry.MACAddress = $MACAddress
    $NewEntry.NetbiosName = $DeviceName
    $NewEntry.OverwriteExistingRecord = $true
    $WMIConnection.psbase.InvokeMethod("ImportMachineEntry", $NewEntry, $null)
}
Invoke-Command -ComputerName $SiteServer -ScriptBlock $ImportScriptBlock -Credential $Credential -ArgumentList @($SiteServer, $SiteCode, $DeviceName, $MACAddress)

With the code saved, let’s create a Runbook.

1. Go to your Automation Account in the Azure portal and click on Runbooks.
167_31
2. Click on Add a runbook.
167_32
3. Select Create a new runbook.
167_33
4. Give the runbook a name, e.g. ImportCMDevice, select Runbook type as PowerShell and click Create.
167_34
5. Click on the Edit button.
167_35
6. Select the code field and paste in the PowerShell code from earlier.
167_36
7. It’s important that you on line 15 in the script, enter the name of the Asset credential created earlier. If you fail to do so, nothing will happen and you’ll not be able to import a device into ConfigMgr. When you’ve made sure that you’re using the correct Asset credential, click on Save and then on Publish.
167_37
8. In the Publish Runbook popup, click Yes.
167_38

Execute the Runbook

It’s finally time to execute the Runbook and see some automation magic occur. Isn’t it exciting?

1. With the Runbook opened, click on Start.
167_39
2. Specify the required parameters. Be adviced, you should of course enter Primary Site server where the SMS Provider is installed in your environment.

SiteServer: CM01.contoso.com
DeviceName: CLTEST001
MACAddress: 00:00:00:11:00:00

You may notice that there’s a CollectionName parameter available. Unfortunately the script won’t recognize that and you won’t have to specify any input (it’s not a mandatory parameter), but I added it for you to figure out on your own how to amend the script so that it will import the device into a specific collection. Make sure that you select to run the Runbook on your hybrid worker, and that the group you created earlier is selected. Click OK.

167_40
3. The Runbook will now be queued, and in a moment start to execute.
167_41
4. Allow for some time to go by while the Runbook is being executed.
167_42
5. Once the Runbook has executed and successfully completed, you’ll see the job summary displaying Completed.
167_43

Results

With the Runbook successfully executed, let’s see if there’s a new device in the ConfigMgr console called CLTEST001.

167_44

There it is! You’ve successfully leverage the power of Azure Automation to import a device into your ConfigMgr environment. Now if that’s not cool, I don’t know what is.

In an attempt to summarize this whole post, I hope that you’ll come to the same conclusion as I have, that being that Azure Automation is extremely powerful and can easily be used to perform automated tasks in a ConfigMgr environment.

5 Comments

  1. DexterPOSH

    Great post Nickolaj,

    I am gonna circle back to this one for reference soon, when I run a runbook on Hybrid worker role for some ConfigMgr stuff.

    ~Dex~

    Reply
    1. NickolajNickolaj (Post author)

      Thanks! Looking forward to read it 🙂

      Regards,
      Nickolaj

      Reply
  2. Prajwal Desai

    This is a great post. Keep it up Nickolaj !!!

    Reply
    1. NickolajNickolaj (Post author)

      Thank you Prajwal!

      Reply
  3. P951

    Wow, this is great info, if only I had found it before I started doing the same thing in Azure Automation, would have saved me tons of time…..

    PS. You can specify the credential asset as a [PSCredential] parameter and pass the asset name when calling the runbook.

    Then you don’t have to use Get-AutomationPSCredential and save a line of code and makes it easy to specify another credential if needed 🙂

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *