Scaling Azure VM with Azure Automation, with help of Azure SQL

Posted: 8th September 2014 by Anders Bengtsson in Azure, Scripts

I am running a number of virtual machines in Microsoft Azure, some of them just a couple of hours and some I keep running 24/7. Often I don’t need them during the night, but some I still want to keep online to make sure database sync jobs runs. Previous I have been using a couple of different Powershell scripts that start and stop virtual machines, but now I have built a new solution, and want to share the idea with you. This new solution involves two components, except the virtual machines, it includes Azure Automation and Azure SQL. Azure Automation (current in preview) is an automation engine that you can buy as a service in Microsoft Azure. If you have been working with Service Management Automation (SMA) you will recognize the feature. You author runbooks in PowerShell workflow and execute them in Microsoft Azure, same way as with SMA, just that you don’t have to handle the SMA infrastructure. Azure SQL is another cool cloud service, a relational database-as-a-service.

Figur 1 Azure Automation

Figur 2 Azure SQL Database

In Azure Automation I have created two runbooks (VM-MorningStart and VM-EveningStop). One that runs every morning and one that runs every evening. These runbooks read configuration from the Azure SQL database about how the virtual machines should be configured during night and day. Azure Automation have a feature, schedule, which can trigger these runbooks once every day, shown in figure 3.

Figur 3 Schedule to invoke runbook

Both runbooks are built the same way. They check in the database for servers and then compare the current settings with the settings in the database. The database has one column for day time server settings and one for Night time server settings. If the current setting is not according to the database the virtual machine is shutdown, re-configured and restarted again. I use Azure AD to connect to the Azure subscription according to this blog post, and I use SQL authentication to logon to the SQL server. If a virtual machine is set to size 0 in the database it seems the machine should be turned of during the Night.

workflow VM-EveningStop
{
### SETUP AZURE CONNECTION
###
$Cred = Get-AutomationPSCredential -Name 'azureautomation@domainnameAD.onmicrosoft.com'
Add-AzureAccount -Credential $cred
### Connect to SQL
InlineScript {
$UserName = "azuresqluser"
$UserPassword = Get-AutomationVariable -Name 'Azure SQL user password'
$Servername = "sqlservername.database.windows.net"
$Database = "GoodNightServers"
$MasterDatabaseConnection = New-Object System.Data.SqlClient.SqlConnection
$MasterDatabaseConnection.ConnectionString = "Server = $ServerName; Database = $Database; User ID = $UserName; Password = $UserPassword;"
$MasterDatabaseConnection.Open();
$MasterDatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
$MasterDatabaseCommand.Connection = $MasterDatabaseConnection
$MasterDatabaseCommand.CommandText = "SELECT * FROM Servers"
$MasterDbResult = $MasterDatabaseCommand.ExecuteReader()
#
if ($MasterDbResult.HasRows)
{
while($MasterDbResult.Read())
{
Select-AzureSubscription -SubscriptionName "Windows Azure MSDN - Visual Studio Ultimate"
$AzureVM = Get-AzureVM | Where-Object {$_.InstanceName -eq $MasterDbResult[1]}
Get-AzureVM -ServiceName $AzureVM.ServiceName | Stop-AzureVM -Force
#
If ($MasterDbResult[2] -eq "0") {
}
Else {
Get-AzureVM -ServiceName $AzureVM.ServiceName | Set-AzureVMSize $MasterDbResult[2] | Update-AzureVM
Get-AzureVM -ServiceName $AzureVM.ServiceName | Start-AzureVM
}
}
}
}
}

The database is designed according to this figure (click to make it larger)

AzureSQL

Summary: Azure automation run one runbook in the morning to start up and scale up virtual machines, and one runbook in the evening to scale down and shut down virtual machines. All Configuration is stored in a Azure SQL database.

Note that this is provided “AS-IS” with no warranties at all. This is not a production ready management pack or solution for your production environment, just a idea and an example.

From time to time there is a need to list all instances of a specific activity type in Orchestrator. For example it is not recommended to have any send platform event activities in production, instead we can use a SQL database for logging. There are two ways to investigate if there are any send platform events in the environment, review each runbook or ask the database. In this blog post I will show you how to list all instances of a specific activity type.

The first thing we need to do is to find the uniqueID for the type of activity in the OBJECTTYPES table. The following question will give us all info about the Send Platform Event, but you can query for any kind of activity.

select * from OBJECTTYPES where name = ‘Send Platform Event’


The OBJECTTYPE table will give us the uniqueID for the activity type, in this example 87E28B20-3E83-45E0-985A-FEEA6CE09084. The table will also tell us where to look for configuration data for these activities, in the PrimaryDataTables and SecondaryDataTables. If we want to list all Send Platform Events activities we have we can run the following query. The “AND (Deleted = ‘0’) part will make sure we only list activities that are not marked as deleted.

select * from OBJECTS where (ObjectType = ’87E28B20-3E83-45E0-985A-FEEA6CE09084′) AND (Deleted = ‘0’)

If we now want to add on in which runbook we are using them we can join the ParentID from the OBJECTS table with the uniqueID in the POLICIES table, like the following query. The Objects table will give us general information about each activity.

SELECT OBJECTS.Name AS [Activity Name], POLICIES.Name AS [Runbook Name] FROM OBJECTS INNER JOIN POLICIES
ON
OBJECTS.ParentID = POLICIES.UniqueID
WHERE (OBJECTS.ObjectType = ’87E28B20-3E83-45E0-985A-FEEA6CE09084′) AND (OBJECTS.Deleted = ‘0’)



We now see activity names and runbook names. But what if we also want to include configuration of the Send Platform Event activity? Then we need to join the table seen in the first query, the PrimaryDataTable for the Send Platform Event activity type, example query

SELECT OBJECTS.Name AS [Activity Name], POLICIES.Name AS [Runbook Name], TASK_SENDOPALISEVENT.EventType, TASK_SENDOPALISEVENT.EventSummary, TASK_SENDOPALISEVENT.EventDetails FROM OBJECTS
INNER JOIN
POLICIES ON OBJECTS.ParentID = POLICIES.UniqueID INNER JOIN TASK_SENDOPALISEVENT ON OBJECTS.UniqueID = TASK_SENDOPALISEVENT.UniqueID WHERE (OBJECTS.ObjectType = ’87E28B20-3E83-45E0-985A-FEEA6CE09084′) AND (OBJECTS.Deleted = ‘0’)

AS you can see some EventDetails and EventSummary includes a GUID. When we configure a Send Platform Event activity to publish data from the data bus we see the uniqueID of the activity in the text. As we can see in the figure many of my Send Platform Events will use data from the data bus.

Earlier this week I needed to add a runbook activity to a Service Request depending on the result from a review activity. I have written about adding activities to a service request from a runbook before, here. The difference is that this time I needed to add a runbook activity and that is a bit more complicated than adding for example a review activity or manual activity.

To add a runbook activity you need two activities, first one that gets the runbook (System Center Orchestrator Runbook Item) you want to use, the second activity creates a new related runbook activity (Runbook Automation Activity) to the service request. In this example I will add a Runbook Automation Activity that runs a runbook named “12.4 Build new VM”.

For the Create Related RB activity there are more to configure compared with the “Get RB Item” activity.

  • Source Object Guid. This is the SC Object GUID from a Get Object activity that gets the Service Request that we want to add a Runbook Automation Activity to.
  • Sequence ID. This field configure where, compared with already existing activities in the Service Request, this new activity will be added. The first activity in a Service Request has sequence ID 0, the second 1 and so on. In my service request I have one review activity and then a runbook activity. This new runbook activity will be added after both of them, sequence ID 2 in other words.
  • ID. This is the id of the new runbook activity. {0} will give it next free serial number from Service Manager, “RB” is added to make sure it is named not just a number but also RB in front of the number.
  • Is Ready For Automation is set to TRUE. This will allow the Runbook Activity to be triggered when the Service Request is created and the Runbook Activity becomes In Progress.
  • Title. Title of the runbook Runbook Automation Activity, for example “Build new VM”
  • Runbook Identifier. This is the ID of the runbook you want to run, you get the ID from the previous Get RB Item activity.
  • Template Identifier. This is a bit more complicated to find, this is the Name of the template you have built for the Runbook Automation Activity in Service Manager. If you start Service Manager Shell (Service Manager PowerShell) you can run “Get-SCSMObjectTemplate | ft Name, DisplayName” and you will find the value you need. Most likely your template name starts with Template.
  • Status. Status of the new activity, configure it to Pending
  • Property Mapping. This is parameters that we pass to the new Runbook Automation Activity.
    • <NAME> is the name of the input parameter in the runbook, the parameter set in in the Initialize Data activity
    • <ID> is the ID of the parameter in Orchestrator. Each parameter has a unique ID. You can list get the connection between parameter, activity and runbook with the following SQL query. In my example query I ask for all input parameters named “SR”.

      SELECT OBJECTS.Name AS [Activity Name], POLICIES.Name AS [Runbook Name], CUSTOM_START_PARAMETERS.UniqueID AS [Parameter ID], CUSTOM_START_PARAMETERS.Value AS [Parameter Name] FROM CUSTOM_START_PARAMETERS INNER JOIN OBJECTS ON CUSTOM_START_PARAMETERS.ParentID = OBJECTS.UniqueID INNER JOIN POLICIES ON OBJECTS.ParentID = POLICIES.UniqueID WHERE (CUSTOM_START_PARAMETERS.Value = ‘SR’)

    • <VALUE> the value I pass to the new runbook is the Runbook Automation Activity ID. Based on that ID you can find the for example related service request
    • <RunbookID> is the ID of the Runbook Item. You can get it from the Get Runbook activity or you can use Service Manager Shell to get it. To get it with Service Manager Shell run “Get-scsmclass –name Microsoft.SystemCenter.Orchestrator.RunbookItem | get-scsmclassinstance | where-object {$_.Name –like “*12.4*”} | ft Name, Id
      In this example I ask for a runbook activity that I know is named something with 12.4.

 

Those two activities is the two activities you need to add a Runbook Automation Activity. I notice that it works better if you also mark the current runbook as completed, from the runbook itself instead of from Service Manager. When adding activities in general I have notice that mark the current runbook as completed makes the service request process work better.

In the runbook you invoke you will get the Runbook Automation Activity SC GUID as input parameter. From there you can use a Get Relationship activity to find the related Service Request.


 

Once you have the Service Request you can read for example all use input data, in my example settings for a new virtual machine. User Input, everything the user has input in for example the self-service portal when submitting the service request, is stored in XML format. For example

To get only “Stockholm” you can use a Query XML activity

 

 

Summary: In this blog post we have looked at how we can use a Runbook Automation Activity in a Service Request to add another Runbook Automation Activity. We have also looked at how to pass data to the new runbook. This scenario is useful if you for example want to add activities based on the answer from a review activity.

Runbook PID

Posted: 28th May 2014 by Anders Bengtsson in Orchestrator

Yesterday I was investigating runbooks consuming much memory. We had a number of runbooks running Powershell scripts and we could see that the Runbook server was almost out of memory. When looking in Task Manager we saw a lot of PolicyModule.exe processes, some using a lot of memory, but we had no mapping between running runbooks and running PolicyModule.exe process. We needed to figure out which script/runbook is consuming all the memory.

This can be done in a couple of different ways. One way is to publish Runbook Process ID for any activity in a runbook. To use Runbook Process ID you need to enable “Show common Published Data” in the Published Data dialog box. The published data will show you the PID for the PolicyModule.exe process.

Another way to get the PID is to look in the Orchestrator database. The following SQL query will show you runbook name, start and stop time and process ID.

SELECT POLICYINSTANCES.TimeStarted, POLICYINSTANCES.TimeEnded, POLICYINSTANCES.ProcessID, POLICYINSTANCES.SeqNumber, POLICIES.Name
FROM POLICYINSTANCES INNER JOIN POLICIES ON POLICYINSTANCES.PolicyID = POLICIES.UniqueID
ORDER BY POLICYINSTANCES.TimeStarted DESC


When playing with Windows Azure Pack I received this error. When searching on the Internet the solution is to add the user to the local “MgmtSvc Operators” security group. That is a bit difficult, as Microsoft removed that group in Update 1. Instead you should use PowerShell “Add-MgmtSvcAdminUser” to assign users permissions. When I ran get-MgmtSvcAdminUser I had the WAP server local administrator’s group member of the WAP Admin role, and my user was member of that local administrator group. Normally a member of a group has all permissions that the group has, but not in this case, instead I needed to add my user account direct to the admin role. Thanks to the oracle Patrik Sundqvist who enlighten me about that. I ran the following PowerShell line and then it worked

Add-MgmtSvcAdminUser –ConnectionString ‘Server=SCDB01;Initial Catalog=Microsoft.MgmtSvc.Store;Trusted_Connection=True;’ –principal ‘demo\anders.bengtsson’

SCDB01 is the database server hosting the Microsoft.MgmtSvc.Store database. DEMO is the domain name.

I have been preparing our TechEd session last weeks. During this I have solved a number of challenges in Windows Azure Pack. In this post I will share challenges and solutions.

Challenge 01 – Unexpected error

This occurred when a tenant tries to deploy an instance of a VM role from the tenant portal. I started to verify the following settings on both the template VHDX file and the gallery item

  • Operating System, for example Windows Server 2012 R2 Standard
  • Family name, for example Windows Server 2012 R2 Standard
  • Tags, for example Windows
  • Version. Remember that version must be in format X.X.X.X for example 1.0.0.0

The solution was that the Library share where the VHDX file was stored was not set as a Read-Only share for the cloud. Once added the Library share to the cloud as Read-Only library share it worked to deploy VM Role instances.

Challenge 02 – …not allowed by any capability profile supported by the cloud

The cloud, Contoso Cloud for developers, had Hyper-V as capacity profile selected. But for VM Roles you cannot use a capability profile, because the VM Role model does not have a property in which to express a capability profile (because it is designed to be consistent with Azure and Azure has no notion of capability profiles). The solution was to uncheck Hyper-V Capacity on my target cloud. Update KB 2936967 removes the requirement for Hyper-V Capability Profile on the VMM Cloud. With this update it is a bit easier to handle clouds used for both VM templates and VM roles.

Challenge 03 – Product key in a VM Role resource definition

There is no option to set Windows product key when configure a resource definition. An easy way to solve it is to use the set-scvirtualharddisk cmdlet to set the product key on the virtual hard disk in VMM.

Challenge 04 – Windows Could not apply unattend settings during pass [specialize]

I connected to the Hyper-V host, opened Hyper-V managed and looked at the floppy disk that was connected to the VM. I open the floppy disk file and read the XML. There was a part about joining the domain. As DHCP configure wrong DNS that was the problem, the VM could not join the domain and hang during installation. I re-configured in VM Role Authoring Tool, imported the new gallery item, marked it as public, added it to the plan, re-login the tenant and re-deployed. Then it worked.

Challenge 05 – Error 31356

Error (31356)
Unable to find the referenced Resource Extension, containing Name=Contoso_FileSrv_ResourceExtension Publisher=Contoso and Version=4.0.0.0.
Recommended Action:
Try the operation again after fixing the Resource Definition or importing the Resource Extension.

Solution was to remove the item from the plan and save the plan. I waited until the plan was synchronized again and then re-added the item to the plan again. The root cause was that I re-import the resource extension to VMM after importing the resource definition to Windows Azure Pack portal and adding it to a plan.

Challenge 06 – Plan syncing hang

Plan remain in syncing state till all subscriptions belong to plan get synced. You can see this update happening in admin portal by going to subscriptions tab inside that plan. You will see some subscriptions which are already synced (i.e. in active Or Out-Of-Sync state) and some currently syncing (i.e. in Syncing…. State).  Once all subscriptions belong to plan get synced then plan will stop syncing. In my case the solution was to apply VMM update 1, including the scripts. I read some threads about people who had seen this issue when they had forget about the scripts in update 1.

Challenge 07 – Error (22663)

The BITS client job failed to succeed for C:\ProgramData\VirtualMachineManagerData\TempResources\3e23bd43fad847e995279686e8547841\ConfigurationFile.ini resource with the following error: The server name or address could not be resolved

Error context: The error occurred while the remote file was being processed.

Error code: -2147012889

This I solved by unchecking the VM network from the Library. If you uncheck the network, VMM will try to transfer file with ISO instead of BITS/network. Else it will try to use BITS/network for some basic configuration file. In my sandbox new VMs don’t have working IP settings, therefor any kind of network communication fails. With this setting it works anyway, as VMM will use an ISO instead.

Challenge 08 – Error (22743)

The host agent on the host hyper119.contoso.local for virtual machine MyMachine001 is not up to date and cannot provision the physical resources required for the servicing operation.
Recommended Action
Ensure the virtual machine has network connectivity to the library servers, or that the host agent is up to date, and then retry the operation.

This I solved by update to 2012 R2 Update 1 on VMM server, ran Update 1 SQL script and updated all Hyper-V host agent to Update 1.

 

 

 

 

 

System Center Universe (SCU) 2014 Europe

Posted: 3rd May 2014 by Anders Bengtsson in Microsoft Event

Are you missing MMS? Missing a System Center event? Guess what! There is a “new” event for you, and it is both in the US, online and in Europe! System Center Universe is a community conference that is focused on systems management and virtualization topics such as cloud, datacenter and modern workplace management with Microsoft System Center, Microsoft Hyper-V and Microsoft Azure. The event is in Basel-Switzerland at September 17-19.

I will deliver two sessions at System Center Universe 2014 Europe together with Pete Zerger

  • Advanced Orchestrator Runbook Authoring and Management
  • Optimize Azure Virtual Machines for Performance and Availability: Step-by-Step

See you in Switzerland!

 

In Orchestrator we often use a monitoring activity in the beginning of a runbook, for example monitor Service Manager for new incidents. In SMA we do this a bit different which I will explain in this blog post. Remember that you can connect Orchestrator and SMA together as shown in this blog post http://contoso.se/blog/?p=3857 , and get the best of both of them.

In general we need to write a runbook (Powershell workflow script) that runs every X minute and checks “a source” and then performs some “action”, as shown in figure 1. We could do this in one runbook but it might be a better idea to split it up, so we can re-use and share code in other scenarios.

Figure 1

In the following example, shown in figure 2, we monitor Service Manager for new incident that don’t have a support group configured, we do this every 10 minute and if we find a incident that don’t have support group set, we update it. The “SCSM_Search_IR” runbook pass the found incident ID and new support group to the “SCSM_Update_IR” runbook.

Figure 2

We build the “Monitor” runbook with input parameters for “Search” runbook and interval, so the same “Monitor” runbook can be used in multiple scenarios. The “Action” runbook have input parameters for the incident to update and support group to set, so we can reuse the runbook in other scenarios were we need to set support group for an incident. We can start the “Monitor” runbook multiple times, for example if we need to monitor Service Manager for incident with specific state every five minutes we can start a new instance of the “Monitor” runbook. If the action is to update the incident with new support group we can reuse the current “Action” runbook, just need to write a new “Search” runbook. This example is shown in figure 3.

Figure 3

 

Let’s look at runbook examples.

The “Monitor” runbook

This is the “Monitor” runbook that runs based on an interval and starts a “Search” runbook.
workflow blog_monitor {
param (
# Mandatory parameter of type INT, number of seconds between loops
[parameter(Mandatory=$true)]
[int]$Interval,
# Mandatory parameter of type String, name of search runbook
[parameter(Mandatory=$true)]
[string]$SearchRunbook
)

$WAP = Get-AutomationVariable -Name ‘SMA-WebServiceEndpoint’
while($true)
{
start-sleep -s $Interval
Start-SmaRunbook -Name $SearchRunbook -WebServiceEndpoint $WAP
}
}

The “Search” Runbook

This is the “Search” runbook. It search for incidents created since last run with blank support group setting. The runbook use a variable (blog_search_SCSM) to keep track of processed incidents. If it finds an incident it starts the “SCSM_SetTier” runbook and pass the incident ID and new support group (tier).

workflow blog_search_SCSM
{
$SCSMServer = Get-AutomationVariable -Name 'Service Manager server'
$fromdate = Get-AutomationVariable -Name 'blog_search_SCSM'
$wap = Get-AutomationVariable -Name 'SMA-WebServiceEndpoint'
inlinescript {
$class = Get-SCSMClass -computername $using:SCSMServer -Name System.Workitem.Incident$
$incidents = Get-SCSMObject –Class $class –filter "CreatedDate > $using:fromdate" -computername $using:SCSMServer | where{$_.tierqueue -eq $null}
ForEach ($incident in $incidents) {
Start-SmaRunbook -Name scsm_set_tier -Parameters @{"IRid"=$incident.ID; "Tier"="Tier 1"} -WebServiceEndpoint $using:wap
}
}
$fromdate = get-date -format G
Set-AutomationVariable -Name 'blog_search_SCSM' -Value $fromdate
}

The “Action” runbook

This is the runbook that sets support group for an incident
workflow scsm_set_tier
{
param (
# Mandatory parameter of type String, id of Incident
[parameter(Mandatory=$true)]
[string]$IRid,
# Mandatory parameter of type String, name of new support group
[parameter(Mandatory=$true)]
[string]$Tier
)
$SCSMServer = Get-AutomationVariable -Name 'Service Manager server'
inlinescript {
$class = Get-SCSMClass -computername $using:SCSMServer -Name System.Workitem.Incident$
$incident = Get-SCSMObject –Class $class –filter "ID -eq $using:IRid" -computername $using:SCSMServer
$incident | Set-SCSMObject -ComputerName $using:SCSMServer -Property tierqueue -Value "$using:Tier"
}
}

Test it

To start these runbooks start the “Monitor” runbook and fill in the parameters. After a while we can see the different runbooks are running or has ran

 

These examples are written in a very “raw” format, to show clean examples. It is a good idea to add for example error handling, logging and parameter validation. In some scenarios it can also be an idea to combine some of the runbooks. When you use a variable for “checkpoint” it is important to understand that only one instance of the runbook can be running. In this scenario it is not an issue as we will only have one runbook running looking for new incidents without support group.

Note that this is provided “AS-IS” with no warranties at all. This is not a production ready solution, just an idea and an example.

Building a SMA activity for Service Manager

Posted: 26th February 2014 by Anders Bengtsson in SMA, System Center Service Manager

Service Manager and Orchestrator are well connected with a connector. It is easy to use Orchestrator runbooks as activities in for example change requests and service requests. When SMA was released as part of Orchestrator 2012 R2 a number of customers asked how to use SMA runbooks as activities in Service Manager. Some runbooks running in (classical) Orchestrator would fit better in SMA, for example long running jobs that can benefit from check pointing and also jobs that need to scale large.

In this blog post I will show you a way to quickly create an activity for Service Manager to start a specific runbook. The example will trigger a SMA runbook from Service Manager through the SMA web service. SMA will then execute the runbook and update the Service Manager SMA activity, mark it as completed. In this example we will invoke a SMA runbook that build new VMs in Windows Azure. We could build a new VM with the Windows Azure integration pack in Orchestrator runbook designer too, but it is handy to use Powershell in this scenario and if we want to build multiple VMs at the same time SMA can use parallel execute to save some time.

These are the steps we need to take

  1. Install SMA powershell module on the Service Manger management server running workflows
  2. Install SMLets on the Service Manger management server running workflows
  3. Create a new activity that starts a SMA runbook in a new management pack
  4. Import the management
  5. Use the new activity in any work item

SMLets is a PowerShell module built by the community. It can be used to automate common tasks in Service Manager. You can download SMLets here. The SMA PowerShell module can be found on the Orchestrator 2012 R2 installation media.

Building the SMA activity

First step is to build the SMA activity. We can use the Service Manager Authoring Tool for that.

  1. Start the Service Manager Authoring Tool
  2. Service Manager Authoring Tool, click File and select New
  3. New Management Pack, input the name for the new management pack, for example Contoso.SMA. Click Save
  4. In the Management Pack Explorer, right-click Classes and select Create Other Class
  5. Base Class, select Activity and click OK
  6. Create Class, input Contoso.SMA.DeployVM, click Create
  7. In the class properties list, delete the default property named Proerty_XX

    We will create two new properties on the new class, on for virtual machine name (VMName) and one for virtual machine size (VMSize). We will configure the VMSize property with data type List. In Service Manager we will configure a list of values used to select virtual machine size.

  8. Click Create property and input VMName as internal name, click Create
  9. Click Create property and input VMSize as internal name, click Create
  10. In the Details pane for the VMSize property, change Data Type to List
  11. In the Select a list dialog box, click Create List
  12. Create List, input VMSizeList as internal name and VM Size as Display name. Click Create
  13. In the Select a list dialog box, select the new VM Size list, click Ok
  14. In the Management Pack Explorer, right-click Workflows and select Create
  15. Create Workflow Wizard, General, input ContosoSMAInvokeRunbook as name. Click Next
  16. Create Workflow Wizard, Trigger Condition, select Run only when… click Next
  17. Create Workflow Wizard, Trigger Criteria, click Browse and select the Contoso.SMA.DeployVM class. Change Change event to When an object of the selected class is updated, click Additonal Criteria
  18. Pick additional criteria, click the Change To tab, add Criteria as
    [Activity] Status equals In Progress
    Click Ok
  19. Create Workflow Wizard, Trigger Criteria, click Next
  20. Create Workflow Wizard, Summary, click Create
  21. Create Workflow Wizard, Completion, click Close
  22. Once you click Close the workflow designer will be displayed. Add a Windows PowerShell Script to the workflow
  23. We will configure the WindowsPowerShell activity to run a Powershell script to start the SMA runbook. Select the WindowsPowerShell activity, in the Details pane click Script Body
  24. Configure a Script Activity, paste the following script to the Script Body text fieldimport-module SMLets
    $size1 = “$InstanceSize”
    $size2 = $size1 -replace “{“, “”
    $size3 = $size2 -replace “}”, “”
    $size4 = get-scsmenumeration -id $size3
    $SizeName = $size4.DisplayName
    Start-SmaRunbook -WebServiceEndpoint https://wap01 -Name “SCSM__Deploy_New_VM” -Parameters @{“InstanceSize”=”$SizeName”; “VMName”=”$VMName”;”ActivityID”=”$ActivityID”}The script first imports the SMLets PowerShell module. The SMLets module is used to convert the GUID for the list value (enum value) into displayname. For example from Service Manager the workflow gets {300dfe04-a0a0-e5fc-8892-963e7146d86c} instead of Medium, as VM Size. Before we can convert the GUID into a displaystring we must remove “{” and “}”, which the two replace lines do. We then start the runbook and pass on three parameters, VM name, VM Size and the activity ID. This example script starts a SMA runbook named SCSM__Deploy_New_VM and the SMA web service has adress https://wap01
  25. Configure a Script Activity, click Script Properties. Create three parameters. Use class properties from the Contoso.SMA.DeployVM class for all three parameters. Use the ID property from the class for the ActivityID property. Click OK
  26. The activity and management pack is now ready to import. Great work! Save the management pack in the Service Manager Authoring Tool
  27. Copy the workflow dll, ContosoSMAInvokeRunbook.dll from the management pack folder to Service Manager installation folder (C:\Program Files\Microsoft System Center 2012 R2\Service Manager) and then restart the Microsoft Monitoring Agent on the Service Manager management server running workflow
  28. You can now open Service Manager console and import the management pack
  29. In the Service Manager Console, browse to Library and Lists, open the VM Size list
  30. List Properties, add the following items, that are all Azure VM sizes, click OKExtraSmall
    Small
    Medium
    Large
    ExtraLargeFor more information about Windows Azure VM sizes look at http://www.windowsazure.com/en-us/pricing/details/virtual-machines/
  31. In the Service Manager Console, browse to Library and Templates, click Create Template
  32. Create Template, input a name, for example Contoso SMA Deploy Azure VM. Select Contoso.SMA.DeployVM as Class and click OK
  33. Contoso.SMA.DeployVM Properties, input Contoso SMA Deploy Azure VM as Display Name and click OK
  34. You can now use the new activity anywhere you like, for example service request templates.

 

But what about the SMA runbook?

SMA Runbook

The SMA runbook is attached to this blog post. The important part of the runbook, or the really interesting part of it, is the last part of the runbook. This part creates a remote PowerShell session to the Service Manager server (SM01) and marks the activity as completed, the work item will now move on to the next activity.

Inlinescript {
$session = new-pssession -ComputerName SM01
Invoke-Command -Session $session {
$workitem = Get-SCSMObject -Class (get-scsmclass -name Contoso.SMA.DeployVM) | Where-Object {$_.ID -eq “$using:ActivityID”}
$workitem | Set-SCSMObject -Property Status -Value Completed
}

 

In the Windows Azure Pack portal you can see the SMA runbook start and you can also see the input parameters coming from Service Manager

 Summary

This post show you an example of how to invoke a SMA runbook from Service Manager with a custom activity.

This example is written in a very simply way, no complicated configuration or requirements. For example you might want to add error handling in the script, handle situation when SMLets can’t be loaded or Service Manager can’t be contacted. In both those cases you want to set the activity status to failure in Service Manager. Also it is a good practices to seal management packs that include class structure.

Note that this is provided “AS-IS” with no warranties at all. This is not a production ready solution, just an idea and an example.

Installing the Service Manager Authoring Tool

Posted: 6th February 2014 by Anders Bengtsson in System Center Service Manager

Today I tried to install the Service Manager Authoring Tool on a couple of different machines. The pre-req check always said that Microsoft Visual Studio Shell 2008 was not installed, but I was sure I did install it. I followed the download link in the Authroing Tool setup and downloaded vs_AppEnvRedistand then I ran that file. After a while I read on this blog about an unsupported modification to skip that pre-check. If I did that unsupported modification the pre-req check did not complain about Visual Studio Shell anymore, but the installation wizard crashed during installation. I then found out that just downloading Visual Studio Shell (vs_AppEnvRedist) and run it did not install it, only extract it to in my example D:\VS 2008 Shell Redist. What we need to do is to browse to that folder and run vs_shell_isolated.enu which actually installed the Visual Studio Shell. After that I could pass both the pre-req check finish eh installation successfully.

20140206 SCSM AuthTool 02

20140206 SCSM AuthTool 01