Early chapter preview of ‘Inside OMS’ version 2

There have been many inquiries into if the band would be getting back together for a second version of the very popular “Inside the Microsoft Operations Management Suite“. Version 2 is 16 chapters of the latest and greatest of Microsoft OMS…and it’s coming soon.

  • When? I am happy to report we are well into the authoring process and looking to release version 2 around the end of April 2017.
  • Cost? As with the first release, we will deliver a book well worth paying for…except it will again be free!

While we are only a little over a month from completion, we wanted to take a moment to give you  a sneak peak at a couple of the chapters of what is to come.

The “Inside OMS” Team

I am also happy to introduce that the entire author team are all back for v2:

  • Tao Yang, MVP
  • Stanislav Zhelyazkov, MVP
  • Anders Bengtsson, Principal PFE
  • Pete Zerger, CISSP, MVP

OMS has grown considerably since our first release, and to ensure we meet our quality bar as quickly as possible, we are joined by four technical reviewers and an editor! Joining us in the tech reviewer role are some very talented folks, including:

  • Damian Flynn, MVP
  • Kevin Greene, MVP
  • Lee Berg, MVP
  • Steve Buchannan, MVP

Early Chapter Preview

To hold you over until the final release, we are going to share three chapters early…one at a time. Your first taste is a major update, driven by awesome Aussie, Tao Yang. Below, you will find a draft preview of:

Chapter 6: Extending OMS Using Log Search

This chapter covers key topics within OMS Log Analytics, including:

  • Saved Searches
  • OMS Computer Groups
  • Custom Fields
  • Custom Logs
  • Power BI

I’ve reviewed it myself, and I know you will appreciate the more than 70 pages of in-depth guidance in this chapter alone!

Get the preview. You can download the preview release of chapter 6 HERE.

Two more preview chapters will be coming your way in the next week(ish). Stay tuned!

Remoting in Azure Automation Runbooks (SQL DB Creation sample)

I find that using PowerShell remoting in my Azure automation runbooks is sometimes more convenient, as it eliminates the need to install and update additional PowerShell modules on my OMS hybrid runbook worker. For future reference, I wanted to capture an example of a simple approach to PowerShell remoting I find intuitive.

The activities in this relatively simple example of remoting in an Azure Automation runbook include the following:

  • Retrieves user and password info from Azure automation variables, then creates a PsCredential object
  • Remotes from the worker where it is run (the HRW in my case) to a SQL 2014 or 2016 server. (The name of the server and SQL instance are supplied in the $RemoteComputer and $SQLInstance parameters of the runbook)
  • Loads the SQL PowerShell module
  • Creates the SQL database with the default settings, named per the $DatabaseName runbook parameter
  • This sample also includes a trace log to demonstrate where the code executes (on the remote SQL server)
PARAM(

$RemoteComputer,
$SqlInstance,
$DatabaseName

)

# Retrieve admin user and password, create credential object
$strScriptUser = Get-AutomationVariable -Name 'ContosoAdminUser'
$strPass = Get-AutomationVariable -Name 'ContosoAdminPassword'
$PSS = ConvertTo-SecureString $strPass -AsPlainText -Force
$cred = new-object system.management.automation.PSCredential $strScriptUser,$PSS

#Invoke script block on the remote SQL server
Invoke-Command -Computername $RemoteComputer -Credential $cred -ScriptBlock {

# Import SQL Server Module called SQLPS
Import-Module SQLPS -DisableNameChecking

# Simple log to prove we are remoting
# Logs to c:\Windows\Temp\remoting.txt
$CurrDate = Get-Date
$message = "We remoted to $env:ComputerName on $CurrDate"
$file = "c:\Windows\Temp\remoting.txt"
$Message | Add-Content -Path $file

# Your SQL Server Instance Name
$SqlInst = "$using:SqlInstance"
$Srvr = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $SqlInst

# Database PSDB with default settings
# By assuming that this database does not yet exist in current instance
$DBName = "$using:DatabaseName"
$db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database($Srvr, $DBName)
$db.Create()

}

Azure Automation Runbook to Add Computer to ConfigMgr Collection

Below for reference a quick PowerShell sample for adding a computer to a device collection in System Center Configuration Manager (ConfigMgr) via Azure Automation runook, designed for use on an OMS Hybrid Runbook Worker. It uses WMI, and so does not require the ConfigMgr PowerShell cmdlets. This also means it works for ConfigMgr 2012 and 2016.

It was used as an example in my talk “Evolving your automation strategy with OMS” at MS Ignite 2016. You can get this and the other sample from that session from my Git repo at https://github.com/pzerger/Ignite2016. The runbook is pretty well commented, but post questions beneath this post if anything is unclear.

Param(
[Parameter(Mandatory=$true)][PSCredential]$SCCMCred,
[Parameter(Mandatory=$true)][string]$CollectionName,
[Parameter(Mandatory=$true)][string]$ComputerName
)
#Retrieve SCCM site server name from Azure Automation variable
$SiteServer = Get-AutomationVariable SCCMSiteServer
Write-Verbose "SCCM Site Server: '$SiteServer'"
Write-Verbose "Connecting to SCCM Site server using user name '$($SCCMCred.UserName)'."

#Query site server WMI to get site code and SMS provider computer name
$ProviderLocation = Get-WmiObject -Namespace "Root\SMS" `
-Query "Select * from SMS_ProviderLocation" -Credential $SCCMCred -ComputerName $SiteServer
$SiteCode = $ProviderLocation.SiteCode
$SMSProvider = $ProviderLocation.Machine
Write-Verbose "SCCM Site Code: '$SiteCode'."
Write-Verbose "SMS Provider computer name: '$SMSProvider'."

#Get the collection WMI object
$Collection = Get-WmiObject -Namespace "Root\SMS\Site_$SiteCOde" `
-Query "Select * from SMS_Collection Where Name = '$CollectionName'" -Credential $SCCMCred -ComputerName $SMSProvider
If ($Collection){
$CollectionID = $Collection.CollectionID
Write-Verbose "collection '$CollectionName' ID is: '$CollectionID'"
} else {
throw "Unable to find collection with name '$CollectionName'. Unable to continue"
Exit -1
}

#Get the computer resource
$Resource = Get-WmiObject -ComputerName $SMSProvider -Namespace "Root\SMS\Site_$SiteCode" `
-Class "SMS_R_System" -Filter "Name = '$ComputerName'" -Credential $SCCMCred | select name,resourceid
If ($Resource){
$ResourceID = $Resource.resourceid
Write-Verbose "Resource ID for computer '$ComputerName' is: '$ResourceID'"
} else {
throw "Unable to find computer resource for '$ComputerName'. Unable to continue."
Exit -1
}

#Create static membership rule for collection
Write-Verbose "Adding computer '$ComputerName' to collection '$CollectionName' by creating a new static membership rule."
$ruleClass = Get-WmiObject -List -ComputerName "$SMSProvider" `
-Namespace "Root\SMS\Site_$Sitecode" -Credential $SCCMCred -class "SMS_CollectionRuleDirect"
$newRule = $ruleClass.CreateInstance()
$newRule.RuleName = $($Resource.name)
$newRule.ResourceClassName = "SMS_R_System"
$newRule.ResourceID = $($Resource.resourceid)
$AddResult = ($Collection.AddMembershipRule($newRule)).ReturnValue

If ($AddResult -eq 0)
{
Write-Output "Collection `"$CollectionName`" direct membership rule successfully created for computer `"$ComputerName`", requesting refresh now."
$RefreshResult = ($Collection.RequestRefresh()).ReturnValue
If ($RefreshResult -eq 0)
{
Write-Output "Collection refresh successfully requested for `"$CollectionName`"."
} else {
Write-Error "Failed to request collection refresh for `"$CollectionName`"."
}
} else {
Write-Error "Failed to add computer '$ComputerName' as a direct member for collection `"$CollectionName`"."
}

Questions or comments? Use the comments section below.

TIP: Keep your Azure Automation runbooks healthy across PowerShell module updates

Here’s a quick tip that may help you ensure you’re protect yourself from a problem that happens occasionally.

Problem: I had a runbook that was broken when the PowerShell modules in the store were updated.

Solution: What can you do to prevent this problem? One thing you can do to protect yourself against breaking changes in new versions of PowerShell moduels is to configure your runbook to run on a schedule. Once schedule is created, that runbook will always run with the modules that were in the store at the time of the schedule creation.

Get a deep dive on Azure Automation in our comprehensive book on the Microsoft Operations Management Suite (OMS), which is available free on the TechNet Gallery or if you prefer, for a small price in paperback and Kindle formats on Amazon.com.

Launch an OMS Automation Runbook on a Hybrid Worker from Orchestrator

While the Operations Management Suite (OMS) and Azure Automation are the future of process automation, there are still many customers still using System Center Orchestrator (SCO). In fact, when polling audiences I have spoken to in the last six months, they are still the majority. For customers taking their first step into hybrid cloud automation, often OMS Automation and the Hybrid Runbook Worker are that first step (OMS enables the Hybrid Runbook Worker capability for Azure Automation).

A few users have asked how to trigger Azure Automation runbooks from Orchestrator, so I thought it was time to write up a quick how-to on the easy way to meet the need. While webhooks are a great tool, only people with the URL can use it, and passing that URL around to multiple teams via e-mail and the like may be less desirable than simply letting authorized teams in your org use their Azure credentials with delegated permissions. So we will look at triggering the runbook directly in this installment.

If you want to launch an Azure Automation runbook on a Hybrid Runbook Worker from System Center Orchestrator, here is the easy way complete the task in three steps, including a parameterized PowerShell script to use in your first runbook.

Step 1: Configure Orchestrator to use the latest version of PowerShell

By default, Orchestrator wants to use an ancient version of PowerShell (v2), where you cannot successfully load the Azure PowerShell module. While you could result to more complex PowerShell scripts to work around this, MS has provided an unadvertised registry key in System Center Orchestrator that you can use to work around this. This eliminates the need for any complexity in your PowerShell script.

1. Use regedit to navigate to the following key on your runbook servers: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework

2. Add a new DWORD entry and value of: OnlyUseLatestCLR = 1

From this point on, Orchestrator will call the latest version of PowerShell. You should have PowerShell v5 if you are working with Azure Automation and OMS. I am using PowerShell 5, Azure SDK 2.9 and latest version of Azure Automation PowerShell, dated 3/30/2016.

DISCLAIMER: I have not heard from MS that this breaks the support agreement. After all, they are the ones who put the registry key there! I do know there are at least a few companies using this in production today. If concerned, always check with Microsoft directly.

Step 2: Add credentials as variables

In figure 1, you will see I have added Azure logon credentials as variables in Orchestrator. Make sure to add your password as an encrypted variable, so it is not visible to others, as shown in the image below. Also, make sure to use credentials from your Azure AD instance. Authentication with a Microsoft (Live) account via Azure PowerShell will fail.

SCO variables

Figure 1. Azure subscription username and password

Step 3: Add sample script in SCO

Here is the sample script, which you will add to a Run .Net Script activity in Orchestrator, as pictured below. Notice in the images below I have also replaced the hard-coded values of the variables for Azure user and password, as well as the Hybrid Worker Group with the appropriate script variables and parameters. I have also replaced the one parameter of a simple ‘Hello World’ Azure Automation runbook (the ‘Message’ parameter), which accepts the message of your choice and logs it to a HelloWorld.txt file on the Hybrid Worker where it runs. There are several ‘Hello World’ examples for Azure Automation available (such as this from TechNet Gallery), so grab one for testing.

TIP: By making Hybrid Worker Group a parameter in your SCO runbook, you can effectively trigger an Azure Automation runbook on hybrid workers in any datacenter in the world from a single Orchestrator instance! You will see how this is done in figures 3 and 4 below.

SCO Runbok

Figure 2. Sample SCO runbook for calling our Azure Automation runbook on a hybrid worker.

Here is a simple PowerShell script you can use in Orchestrator to trigger a runbook in your Azure Automation account. Make sure to update the value of the -AutomationAccountName in the last line of the script as well!

# Import Azure Modules
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Automation\AzureRM.Automation.psd"

# Authenticate with Azure AD credentials
$MyUserName=’username@yourdomain.onmicrosoft.com’
$MyClearTextPassword=’YourPassword’

# Hybrid Worker Pool
$HRWPool = 'ConfigMgrPool'
$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force

$cred=New-object System.Management.Automation.PSCredential $MyUserName,$SecurePassword

Login-AzureRmAccount -Credential $cred

#Runbook parameters
$params = @{"Message"="Hello Azure Community!";}

Start-AzureRmAutomationRunbook –AutomationAccountName "contoso-testrba" –Name "Hello-World" `
-ResourceGroupName 'Default-Networking' –Parameters $params -RunOn 'ConfigMgrPool'

Notice I have replaced the values of the aforementioned hard-coded parameters, as shown in figure 4 below.

SCO Runbook Params

Figure 3. SCO Runbook Parameters

Paramized_SCO_Runbook

Figure 4. Parameterized PowerShell script in Orchestrator (Run .NET Script activity)

Step 4: Test Your SCO Runbook

To test my configuration, I’ll use the Orchestrator Runbook Tester. Once I see success reported in the Runbook Tester, I will then check Azure Automation and the HelloWorld.txt on the Hybrid Runbook Worker as an initial end-to-end validation my solution is working as intended.

Trigger Runbook

 Figure 5. Testing the runbook from the Orchestrator Runbook Tester

About 3 minutes after I started the job, I see a completed message in the Jobs area of my Azure Automation subscription, as well as an entry in HelloWorld.txt from my own Hello World runbook I use for testing.
Runbook Results

Figure 6. Runbook successfully triggered in Azure Automation and run on Hybrid Worker

That’s it for this installment. Let me know if you struggle with any of the above or have questions. Good luck!

5 TIPS FOR MODERNIZING YOUR PROCESS AUTOMATION STRATEGY

Don’t get me wrong, I love System Center Orchestrator (as you will see here AND here), but it is important to know when it is time to move on. Well my friends, it’s time. Some months ago now, Microsoft publicly announced that their investment in new features Orchestrator had come to an end, and that a cloud-first strategy would be the norm. The Microsoft Operations Management Suite (OMS), together with Azure Automation, is actually the bridge for organizations wishing to modernize their automation strategy,..even organizations not quite ready to go “all-in” with Microsoft Azure.

In this article, I will share five tips to help optimize your journey in modernizing your process automation strategy.

Tip #1: Don’t make big investments in legacy tools

Since Orchestrator is a legacy component, it is probably best not to rush into costly investments in Orchestrator-based solutions that you will only have to rewrite later. However, I am not saying not to use Orchestrator at all. If you find a runbook for free (or cheap) you can download that solves a problem, go ahead! If the development cycle is fairly short, no problem! However, think twice before spending tens of thousands of dollars on Orchestrator-based development or solutions.

“How would you suggest I move forward” you ask? Read on.

Tip #2: Don’t count on the Orchestrator Migration Toolkit to handle everything

The System Center Orchestrator Orchestrator Migration Toolkit will convert some of your runbooks, as well as your custom activities developed with the Orchestrator Integration Toolkit (OIT) to an Azure Automation / Service Management Automation (SMA) friendly format. It also provides a converted set of (most of) the standard activities from Orchestrator.  However, there are some caveats:

  • Some activities cannot be converted. For example, the Map Published Data activity, used heavily by runbook authors everywhere, cannot be converted for Azure Automation and SMA at present.
  • Activities in integration packs not created with the OIT cannot be converted.

What’s more, you may have created custom logging, checkpointing and other workarounds in your Orchestrator runbooks that are native features of Azure Automation, which you will need to write out of converted runbooks. The bottom line here is that at least some runbook redesign and rework is going to be necessary on the road to a simplified, modern process automation strategy. Embrace this reality and use it as a learning opportunity.

Tip #3: Use hybrid to take your first step…

If your organization is not yet in the cloud, walking in the door and singing the praises of an “all-in cloud strategy” may not be the best approach. Your message may not be well-received by the cloud doubters and cloud fearful in your ranks. Some of these concerns may be well-founded and may take time to overcome. This is where OMS can help, by giving you a fantastic compromise…the Hybrid Runbook Worker. Without rehashing everything explained in the hyperlinked article, the key point here is that linking OMS to an Azure Automation subscription enables you to execute Azure Automation runbooks on a server enabled as a Hybrid Runbook Worker inside your datacenter with no additional outside-in firewall ports required!

This is an olive branch with another bonus. With Hybrid Runbook Workers enabled throughout your data centers, you can Azure Automation as your centralized, simplified, global back-end orchestration infrastructure. An Orchestrator instance per-datacenter, and the headaches that come with keeping them all in sync in terms of patches, runbooks and security, are a thing of the past.

Tip #4: Don’t build what Microsoft is going to build for you

This tip is an easy one to follow. Never spend a lot of time and money building or buying a solution Microsoft promises to build for you. Watch the product roadmap for OMS, which includes a long list of Microsoft’s planned feature releases that may eliminate your need to build certain types of automation. The current public roadmap includes a host of great features, including solutions focusing on

  • Office 365
  • Patch Management
  • Remote OS Management
  • Containers
  • Network Performance and Analytics
  • Configuration Management Database

That is just the tip of the iceberg. Since OMS Is cloud-based platform, features come on a rapid release cycle…at a cloud cadence. Talk to your MS account team and focus on closing the gaps MS is not already working to close for you. This likely means you will be able to focus on more organizationally-specific, high ROI scenarios the business side of your org care about.

Talk to your Microsoft account rep for the latest OMS feature roadmap.

Tip #5: Start with a “quick win”

One important point I used to stress with Orchestrator was the need to “start small”, and the same is true with OMS and Azure Automation. To introduce your organization to hybrid automation with OMS and Azure Automation with the Hybrid Runbook Worker (and to ensure they love it), start with a manageable scenario. Find an automation need that you can develop and demonstrate in a proof-of-concept in a short time (nor more than one or two days) to get your colleagues and management stakeholders acquainted…and on board.

Before you start, look at what is already available from the community. There are lots of runbook samples out there demonstrating common scenarios like group maintenance mode in System Center Operations Manager, Active Directory user onboarding, as well as adding computers to collections in System Center Configuration Manager (SCCM). Since Azure Automation supports PowerShell, a freely available PowerShell script may help jumpstart your efforts!

Next Steps

Your first step is to get in the game. Sign up for the free tier of OMS, which includes 500 automation minutes per month. Sign up for a free Azure trial, or sign up for the pay-as-you go option to limit your spend. Watch some of OMS and Azure Automation videos on the MS Channel 9 website. Download some of the many sample runbooks shared in those sessions.

Good luck!

Free E-book: Inside the Microsoft Operations Management Suite

Tao (@MrTaoYang), Stan (@StanZhelyazkov), Anders (http://contoso.se)  and I have been working on a project for the last few weeks. We wanted to bring a learning resource for the MS Operations Management Suite to the community that is complete, comprehensive, concise…and free (as in beer). While we finish final editing passes over the next couple of weeks, we wanted to share an early copy of the book so you can start digging in while we finish our work!

Description: This preview release of “Inside the Microsoft Operations Management Suite” is an end-to-end deep dive into the full range of Microsoft OMS features and functionality, complete with downloadable sample scripts (on Github). The chapter list in this edition is shown below:

  • Chapter 1: Introduction and Onboarding
  • Chapter 2: Searching and Presenting OMS Data
  • Chapter 3: Alert Management
  • Chapter 4: Configuration Assessment and Change Tracking
  • Chapter 5: Working with Performance Data
  • Chapter 6: Process Automation and Desired State Configuration
  • Chapter 7: Backup and Disaster Recovery
  • Chapter 8: Security Configuration and Event Analysis
  • Chapter 9: Analyzing Network Data
  • Chapter 10: Accessing OMS Data Programmatically
  • Chapter 11: Custom MP Authoring
  • Chapter 12: Cross Platform Management and Automation

This early edition is being shared with the community while final edits are being completed. Please send questions, comments or errata you find to insidemscloud@outlook.com.

You can download for free from the TechNet Gallery at:
https://gallery.technet.microsoft.com/Inside-the-Operations-2928e342 

 

Centralized Logging Strategy for Azure Automation Hybrid Worker with OMS

Many System Center Orchestrator administrators longed for centralized logging of Orchestrator runbook events and results. With no native centralized logging facility, many administrators used a simple SQL database as a centralized logging repository. While not ideal, this method is functional for a single data center.

Think about the challenges of implementing this strategy on a global basis. You would need either have to configure your Orchestrator runbook servers to log events to a SQL instance in a remote data center, or perhaps configure SQL replication to centralize the events after they were logged locally.

In this article, we will look at establishing a centralized runbook progress and result logging strategy for the Azure Automation Hybrid Runbook Worker using the Microsoft Operations Management Suite (OMS) that is quick, easy and searchable…no SQL database required.

In this post:

  • Hybrid Runbook Worker job logging in the Azure Portal
  • Native Logging on the Hybrid Worker
  • Why custom central logging for the Hybrid Worker?
  • Basic Custom Logging Implementation for Hybrid Worker
  • Logging runbooks events with a child runbook

Let us get down to business.

Hybrid Runbook Worker job logging in the Azure Portal

Enter the Azure Automation Hybrid Runbook Worker (hybrid worker) role, which enables Azure Automation customers to execute (run) runbooks on designated servers in their data centers around the world. The back-end infrastructure is Microsoft Azure, so implementing a global automation infrastructure is much less work than with Orchestrator.

However, the desire for detailed logging of activities on the hybrid runbook worker remains. Certainly the Jobs log (shown below) in Azure Automation shows results, inputs and outputs of runbook jobs. However, it does not provide detailed progress logging of your choosing at key points along the way.

Jobs_Log

With that in mind, the desire / need for centralized progress logging at our discretion remains.

Native runbook event logging on the Hybrid Worker

One bit of good news is that the hybrid worker includes some native logging to the Windows Event Log. You can find the log in the Windows Event Viewer under Applications and Services Logs > Microsoft-Automation > Operational.

More good news. You can easily add this log for collection by OMS in the Settings area on the Data tab. In the ‘Collect events from the following event logs’ window, type “Microsoft-Automation/Operational” and click on the plus sign (+) to add the log for collection. Then check the boxes for all three event levels.

HybWrk_Log_Collection

However, the bad news is, once this data arrives in our OMS subscription, you can see the formatting of the details in this log is less than ideal. Using the search interface, you can retrieve the contents of this log with the following query:

Type=Event EventLog=”Microsoft-Automation/Operational”

The result reveals that in the ParameterXml within the event lies the job status, but only the value (Succeeded, Failed, etc.) rather than a well-formatted name value pair we could use to extract the result into a custom field for better search. As a result, this native logging is not as useful as it could be, but can still serve to reduce the need for automation admins to use the Azure portal.

Moreover, this still does not address our need for ad-hoc progress logging hosted in a central repository.

Why custom central logging for the Hybrid Worker?

Even with the aforementioned logging, the need to log events within a runbook at key junctures remains, and this is where logging to the Windows Event Log with a custom source, with an event description detailing runbook progress or results, with output collected and forwarded to OMS. This gives us central logging without the need for a SQL database.

You can log this data to any local Windows Event Log, even the System log. One approach might be to use a couple of custom sources, such as one for logging runbook progress messages and another reporting the runbook result, both in an easily searchable format in OMS once the data has been collected and uploaded.

Basic Custom Logging Implementation for Hybrid Worker

I will describe a couple of simple approaches you could take for custom logging locally on the hybrid worker.

First, in order to write messages with a custom Windows event log source, the providers must exist. You can create custom event sources with the New-EventLog cmdlet. If you wanted, you could simply create these providers each time you deploy a new hybrid worker.

For runbook progress messages, I will write to the System event log with a source of OMSAutomation-Status. To create this new provider, simply run the following one-liner on the hybrid worker.

New-EventLog -LogName System -Source OMSAutomation-Status

For the final runbook result message, I will again write to the System log with a source of OMSAutomation-Result. To create this new provider, simply run the following one-liner on the hybrid worker.

New-EventLog -LogName System -Source OMSAutomation-Result

This approach ensures I can quickly and easily search runbook messages by event source. Then, any time you want to log a status message within your runbook, you would simply add a Write-EventLog message at the appropriate point in your runbook. Since the System log is already being collected in OMS, you do not have to configure any additional log collection in OMS.

Let’s assume that every time a runbook begins I log a message in the following format from within my PowerShell runbook on hybrid workers:

Write-EventLog -EventId 1 -LogName System -Message "Runbook $RBName is now beginning" -Source OMSAutomation-Status

Then in OMS I can find every message showing a runbook beginning with the following wildcard search:

Type=Event EventLog=System Source=OMSAutomation-Status “*now beginning “

Add | measure count() by Source and you can get a count of how many runbooks have run on hybrid workers.

Type=Event EventLog=System Source=OMSAutomation-Status “*now beginning ” | measure count() by Source

Add the computer name to filter results to a specific hybrid worker, as shown here

Type=Event EventLog=System Source=OMSAutomation-Status “*now beginning ” Computer=”VMBR01.contoso.corp” | measure count() by Source

If I wanted to find ever event where a specific runbook ran, I would simply expand the search based on my message syntax, for example.

Type=Event EventLog=System Source=OMSAutomation-Status “Runbook Hello-World is now beginning”

And finally, a search for all successful completions of a specific runbook

Type=Event EventLog=System Source=OMSAutomation-Result “Runbook Hello-World completed successfully” Computer=”VMBR01.contoso.corp” Source=OMSAutomation-Result

or any runbook, as pictured below

Type=Event EventLog=System Source=OMSAutomation-Result “*successfully” Computer=”VMBR01.contoso.corp” Source=OMSAutomation-Result

JobResult

As you can see, logging inline from within your runbook is simple, quick, easy and searchable in OMS!

Logging runbooks events with a child runbook

We could take what some might deem a slightly more elegant approach and instead call a child runbook to log the event. One advantage of this method is that we can accept the event source as an input, and check that the source exists before attempting to write the event. This means there would be no need to create the custom event sources manually. On the downside, this approach might mean slightly longer execution time, resulting in billing for a few more runbook minutes per month versus the simple inline method described above.

Here is a simple, generic and effective Windows event logging script borrowed from my friend Tao Yang. This script accepts event log name, ID, source, type and message as parameters. Before attempting to log the event, it checks for your event source on the hybrid worker. If the source does not exist, it creates the new source, then logs the event.

Param (
 [Parameter(Mandatory=$true)][string]$EventLog,
 [parameter(Mandatory=$true)][int]$EventID,
 [Parameter(Mandatory=$true)][string]$EventSource,
 [Parameter(Mandatory=$true)][string]$EntryType,
 [Parameter(Mandatory=$true)][string]$Message
)

$ExistingEventSource = Get-Eventlog -LogName $EventLog -Source $EventSource -ErrorAction SilentlyContinue
If (!$ExistingEventSource)
{
 #The event source does not exist, create it now
 New-EventLog -LogName $EventLog -Source $EventSource
}
Write-EventLog -LogName $EventLog -source $EventSource -EventId $EventID -EntryType $EntryType -Message $Message

Here is a sample usage of this runbook you can past into your Azure Automation runbooks destined for hybrid workers. This assumes you have added the above sample runbook to your Azure Automation subscription with the name Write-WindowsEvent.

.\Write-WindowsEvent.ps1 -Message 'Test message' -EntryType 'Information' -EventLog 'System' -EventSource OMSAutomation -EventID 50001

Conclusion

As you can see, Azure Automation, the new hybrid worker and OMS open the door to easy and flexible implementation of a global, hybrid runbook automation infrastructure that transcends the limitations of System Center Orchestrator. Get started with your free subscription to OMS at http://microsoft.com/oms.

How to launch an Azure Automation runbook on a Hybrid Worker via PowerShell

With the update in Azure PowerShell 1.0, quite a lot has changed. Working with Azure has been divided into cmdlets for working with Azure 1.0 (Azure Service Management) and Azure 2.0 (Azure Resource Manager). With the GA release of the new Azure portal (https://portal.azure.com) that was called “the preview portal” forever, has arrived. In short, the PowerShell cmdlets for working with Azure Resource Manager include an “Rm” after the “Azure”, such as in New-AzureRmVm, the cmdlet for creating a new VM in Azure IaaS v2…aka Azure Resource Manager.

Azure Automation, when connected to your Operations Management Suite (OMS) subscription, eanbles you to tap into a new Azure Automation feature called a Hybrid Runbook Worker. This allows you to run runbooks on machines located in your data center in order to manage local resources. The runbooks are stored and managed in Azure Automation and then delivered to one or more on-premises machines where they are run.

If you are unfamiliar with any of the above concepts, you can click on the links and read more. If you are familiar and just want to know what the PowerShell is you need to call an Azure Automation runbook and run it on a Hybrid Worker, you will find the script and some explanation below.

Prerequisites

You will need the following in before you get started

  • The latest Azure PowerShell module, which you can install using the Web Platform Installer or the PowerShell Gallery, on the system where you will run the script
  • An Azure AD user with appropriate rights from your Azure subscription. You cannot use a Microsoft (Live) account when authenticating to your Azure subscription.

I am working on a Windows Server 2012 R2 system. I also have the production preview of the Windows Management Framework 5 installed, though this is not required.

Sample Script

In this sample, we will assume you are working with your default Azure subscription. We will build on this example to cover working with multiple Azure subscriptions in a future post.

# Import Azure Modules
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Automation\AzureRM.Automation.psd1"

# Authenticate with Azure AD credentials
$MyUserName=’username@yourdomain.onmicrosoft.com’
$MyClearTextPassword=’YourPassword’

$SecurePassword=Convertto-SecureString –String $MyClearTextPassword –AsPlainText –force

$cred=New-object System.Management.Automation.PSCredential $MyUserName,$SecurePassword

Login-AzureRmAccount -Credential $cred

#Runbook parameters
$params = @{"Message"="Hello Azure Community!";}

Start-AzureRmAutomationRunbook –AutomationAccountName "contoso-testrba" –Name "Hello-World" `
-ResourceGroupName 'Default-Networking' –Parameters $params -RunOn 'ConfigMgrPool'

A little explanation…

A couple of key areas of the script that deserve explanation.

Authentication
On lines 5 through 13, you will see how we handle credentials. You will need to replace the user name and password with your Azure AD user. In this case, I have hard-coded the credentials so we can riff on this in some other contexts in my next post. If you intend to call this script right out of PowerShell, you may want to prompt for the password each time. You can do that by replacing the code on line 7 above with the following:

$MyClearTextPassword = Read-host "Enter your password:" -AsSecureString

Runbook Name and Parameters

  • The runbook parameters are presented on line 16 in name / value pairs, separated by semicolons (a hash table). In this case, I am launching a runbook named “Hello-World” that has one parameter called “Message”, which accepts a text string. You can see this pictured in the image below. If you have a runbook with multiple parameters, simply provide additional name / value pairs separated by semicolons.

AA_HybridWorker

  • On line 18, notice the -AutomationAccountName parameter where you specify the name of the Azure Automation account associated with this runbook, as well as the -Name parameter where you specify the name of the runbook.
  • On line 19, you will need to update the -ResourceGroupName parameter with the name of the Azure resource group containing the Azure Automation account.
  • Finally, the name of your Azure Automation Hybrid Worker group is specified in the -RunOn parameter. If you want to know where to find your available Hybrid Worker groups, you can see the GUI version of this in the image above from the Azure portal.

Once you execute the runbook, the output if it runs successfully will be roughly as follows:

AA_HybridWorker2

In the Azure portal, go to the Jobs area of your Azure Automation account where you can see detailed job results:

AA_HybridWorker3

In our next installment, we will do something interesting with this script you can use in your environment…today!

Simple Self-Service App Deployment with ConfigMgr, SCOrch and SCSM

At a recent meeting of the Houston Area Systems Management User Group, I presented a strategy for delivering effective self-service application deployment that would be achievable for System Center 2012 Configuration Manager (ConfigMgr) admins could potentially implement. By intention, the solution does not require custom management pack authoring, extending Service Manager (SCSM) classes or custom PowerShell. However, it is flexible and leverages the rich capabilities of SCSM for publishing a Service Catalog. This way, any ConfigMgr admin with basic Orchestrator (SCOrch) skills who can install a basic SCSM deployment (a Management Server, database and portal server) can configure ITIL friendly self-service with System Center 2012, complete with approval routing and documentation of the request in a proper service request.

By request, I am posting the sample runbooks here for the community members.

There is a variation of my approach HERE, but in this sample I have eliminated the need for custom PowerShell script, thereby further simplifying the solution.

NOTE: You do not have to replace your service desk solution to leverage System Center for self-service. The service requests created here can pretty easily be exported with a bit of PowerShell and imported into your target ITSM system of choice.

Solution Components

Components in the solution as demonstrated were:

  • ConfigMgr 2012 R2
  • SCSM 2012 R2
  • Orchestrator 2012 R2
  • Cireson Portal (optional) – This component is 100% optional, though it reduces the required server count by 1, eliminates the need for SharePoint and provides a self-service experience across mobile devices and is much more responsive than the native portal.

What I demonstrated used User Collections in ConfigMgr.  You could tweak the solution to use computer-based collections instead.

High-level Steps

The following are the high-level

  1. Configure deployments in SCCM
  2. Import runbook in SCO
  3. Connect SCSM to SCO and ConfigMgr
  4. Select the software to make available
  5. Configure the Offering in SCSM (For SCSM newbies, see “Automation and Self-Service with SCSM” on MVA)
  6. Publish to the Service Catalog

Sample Runbook #1

In this example, we used to retrieve the user and application (app) object. The app object is represented in the SCSM database by the Package class, which is populated by the ConfigMgr Connector in SCSM, which brings over the applications you have created in ConfigMgr When you look at the last two activities, you will notice that the runbook assumes that the ConfigMgr application (represented by the Package class in SCSM) and ConfigMgr collection have the same name.

I am not going to walk through the detailed configuration steps of either sample, as you can simply download both sample runbooks, import and see for yourself.

AppDeploy

Sample Runbook #2

I was asked if it would possible to extend the solution to allow use of existing packages. The short answer is yes, by simply adding a Map Published Data activity in which you can map the name of your application in ConfigMgr to the name of the collection to populate with the account of the user requesting the software.

AppDeploy_CustomColl
Here is a shot of the properties of the Map Published Data activity in the sample runbook.

Map_Published_Data

Download Runbook Samples

The runbook samples are available in a new GIT repository I setup to store community samples in a single, centralized repository. Both sample runbooks can be found at the URL below.

https://github.com/pzerger/CommunitySamples/tree/master/Runbooks/SCO