Showing posts with label Azure. Show all posts
Showing posts with label Azure. Show all posts

Tuesday, November 7, 2017

Service Principals and Azure AD

There are a few scenarios with Azure AD that folks commonly run in to.

I have not blogged about the relationships of an Azure Tenant and Azure AD.  So let me briefly mention the relationship between these two.
(I will be repeating this all in future posts, as this relationship is important to grok)

An Azure Tenant is the Account that you or your company has in Azure.  It is divided into Subscriptions. 
Each Subscription is where you 'consume' in Azure; and it also serves as an isolation boundary (as in, resources in different services can only talk to each other through public entry points - they cannot directly touch each other).
Below that you have Resource Groups, which are management containers (not isolation).
And then you have the actual resources that you get billed for consuming.

All of this together is an Azure Tenant - or phrased another way, you are a Tenant of Azure and this is your playground and thus billing entity.
I will keep using the phrase Azure Tenant in this way.
(I run across MSFT folks that use the word Subscription when referring to the Tenant, and it is just plain incorrect and thus confusing as to the ramifications)

Azure AD is an entirely separate thing.  It is this huge multi-tenant cloud based identity provider, with a number of cool features and touch points.
An Azure Tenant must have an associated Azure AD, but an Azure AD has no dependency on an Azure Tenant (or an Office365 tenant - which is yet another entity).

A single company can have multiple Azure AD's (which is highly likely), they could also have multiple Azure Tenants (which is not very likely, but possible).

A single Azure Tenant can only be associated with one Azure AD.  Nuance here; the tenant has one Azure AD, but people from other Azure ADs can be granted access.  But the invited accounts are foreign accounts.

I bring all of this up since it is this multi-pronged association that usually gets folks into a pickle.

The "Service Principal" is a term that has been within the IT world for a long time.  It describes the user account that a particular application or service runs under.  If that application needs to access resources on the network, the Service Principal user account for that particular service is used.

This has worked well for decades in the enterprise with Active Directory.  And now we need to take this to the cloud.  And it works a bit differently with Azure Active Directory.

Within Azure Active Directory the service principal is called an "App Registration".  And just like with the enterprise, you would have a unique app registration for each application.
This is different than a user account that you simply grant access to Azure resources.  While it really appears to be the same thing, it actually isn't.

Now, as we put things together a number of questions arise.  Which Azure AD should my app registration reside in?  Is there any limitation on the user account?  What resources does the app registration need to access?

Most likely you are using the app registration to interact with your Azure tenant resources.  For example, the app registration is used to provision new machines, or to power machines on and off.  Essentially to perform lifecycle events on your Azure resources.

This means that the app registration must be "native" to the Azure Tenant Azure AD - regardless of what Azure AD your user accounts reside in.  You cannot simply use a random user account.

If you manually create your app registration, you need to be a user administrator in your Azure AD.  And then you can grant the permissions to the Subscription or Resource Groups and you are golden.

https://itproctology.blogspot.com/2017/04/manually-creating-service-principal-for.html

If you are using some other app to create the app registration programmatically things immediately get unique.  All of a sudden your user account matters.
And to programmatically create an app registration, your user account needs to be native to the 
Azure AD.
This is a special kind of native.  The Azure AD account that you use must be an "onMicrosoft" account within that Azure AD.  You cannot use a user account that is synchronized with your on-premises Active Directory.  It does not even matter if your user is a domain admin.

Each Azure AD begins life as an "onMicrosoft" entity.  If you look at the properties of the Azure AD, you will see the information about its original creation, such as brianeh.onmicrosoft.com.  And this remains even if you add a vanity domain, such as ITProctology.com to the Azure AD.

I mention all of this because you might be in a position where you need to create a special Azure AD account, so that your app can create its own app registration (Citrix Cloud does this, RDMI does this).

In your Azure AD, create a new cloud user, using name@domain.onmicrosoft.com  This will create a cloud user that is native only to the Azure AD, and this user will have the full permissions to the API that it needs to create an app registration.

In your app you need to then use the credentials of this new user account so that it can access the API and self create its app registration.

A lot of explanation just to get you to the answer, but the why is often as important as the what.


Monday, October 9, 2017

The gotchas of Azure AD Domain Services in ARM

Not too awful long ago Azure Active Directory Domain Services moved over to the ARM portal from the Azure Classic portal.

Yea! the world said.  And there was much rejoicing.

Now, the real world impacts of this.

There are a few scenarios with Azure AD that folks commonly run in to.

I have not blogged about the relationships of an Azure Tenant and Azure AD.  So let me briefly mention the relationship between these two.
(I will be repeating this all in future posts, as this relationship is important to grok)

An Azure Tenant is the Account that you or your company has in Azure.  It is divided into Subscriptions. 
Each Subscription is where you 'consume' in Azure; and it also serves as an isolation boundary (as in, resources in different services can only talk to each other through public entry points - they cannot directly touch each other).
Below that you have Resource Groups, which are management containers (not isolation).
And then you have the actual resources that you get billed for consuming.

All of this together is an Azure Tenant - your phrased another way, you are a Tenant of Azure and this is your playground and thus billing entity.
I will keep using the phrase Azure Tenant in this way.
(I run across MSFT folks that use the word Subscription when referring to the Tenant, and it is just plain incorrect and thus confusing as to the ramifications)

Azure AD is an entirely separate thing.  It is this huge multi-tenant cloud based identity provider, with a number of cool features and touch points.
An Azure Tenant must have an associated Azure AD, but an Azure AD has no dependency on an Azure Tenant (or an Office365 tenant - which is yet another entity).

A single company can have multiple Azure AD's (which is highly likely), they could also have multiple Azure Tenants (which is not very likely, but possible).

A single Azure Tenant can only be associated with one Azure AD.  Nuance here; the tenant has one Azure AD, but people from other Azure ADs can be granted access.  But the invited accounts are foreign accounts.

Now.  Some background into the processes that get us into the strange places that folks end up in.

When an Azure Tenant is created an Azure AD is created for it.
So you end up with some Azure AD such as you@tenantName.onmicrosoft.com

This is fine.  It gets you up and running and then you add your admins which might be your.admin@yourcomapny.com  and they get invited.  Everything in the Azure Portal works.  Now, lets get into the cases that won't work in this scenario.

This actually puts you in a very common scenario, the scenario where the Azure AD associated with your Azure Tenant is not the same Azure AD where your corporate user accounts reside.

Now, if you only want to use Azure AD RBAC to add your IT folks to the Azure Tenant for administrative purposes, this is fine.  And thus, a more common scenario than most folks want to realize.

Now, lets get to Azure AD Domain Services in ARM.  There is a security boundary here.  The Azure Tenant.  Therefore, when you enable AAD DS in ARM you are restricted to the Azure AD that is associated with the Azure Tenant.

Oh, your Azure Tenant Azure AD is not the one with your users?  Oh my!  How do we resolve this?
(trust me, the sarcasm is real here, I can't tell you how many times I have spoken to folks about this and it takes a while for all the dots to connect before they realize the dilemma).

There are three ways to resolve this:
  1. 're-parent' the Azure Tenant.  What does this mean?  It means that you make some other Azure AD the primary Azure AD for your Azure Tenant.  There is an option in the Azure Portal "Move to another Directory".  The impacts:  If you had any RBAC set up, you will break it, and therefore need to set it up all over again.
  2. Use a vNet.  When logged on to the Azure AD where the users are, create a new Azure Tenant and subscription.  Turn on AAD DS there.  Then set up a gateway between the vNet in this subscription where your AAD DS and user accounts are, and a vNet in a subscription of the Azure Tenant where your workloads are that require the domain services provided by AAD DS.
  3. Don't use AAD DS.  Stand up a Windows Server Domain Service VM (more than one for a proper deployment) and use Azure AD Connect to sync the users with the AD domain.
In the end, this is about your user accounts, the reasons why you wanted AAD DS in the first place (you need NTLM or Kerberos for any reason).
Yes, AAD DS is convenient, but the security models that forced it into this particular assumption is not always in line with reality.

Friday, July 28, 2017

Virtual Network permissions for Citrix Cloud

In a previous post I covered how to manually create a Service Principal (App registration) for XenDesktop Essentials.  (this also applies to the XenApp and XenDesktop Service)

If you recall, this is the identity that Citrix Cloud will be using when it performs machine lifecycle actions in your Azure Subscription.

Things with permissions can get a bit strange in Azure pretty quickly.  One such area is Virtual Networks.

First of all, a Virtual Network exists within a Subscription.  It can belong to any Resource Group for management, but can be used by any machines or services within the subscription.

Now, in the world of assumptions, this is all fine and easy if you grant the Service Principal account the Contributor role AND the resource group that your virtual network belongs to is within a resource group under that same subscription.  You can take advantage of the inheritance.

This is not always the case.  In fact, it might not be the case for you at all.  You might be putting very tight controls on that Virtual Network to ensure it never gets messed up.

The minimum permissions that the Service Principal needs to your Virtual Network is the VM Contributor Role.  This level of access is necessary for the automated provisioning and lifecycle of desktop or session workers.

If you have a need to grant access to your Virtual Network or want to constrain access to your virtual network, here is how.

Remove the inheritance at the Virtual Network Resource Group from the subscription if it is enabled.
Explicitly grant the App Registration the VM Contributor role on the Virtual Network where worker machines will be attached when provisioned.

You can find more about the permissions in this article that I authored:  Manually granting Citrix Cloud Access to your Azure Subscription

Friday, April 14, 2017

Getting started with Citrix Essentials on Azure


Earlier this month two Citrix Essentials products hit the Azure Marketplace;
XenApp Essentials and XenDesktop Essentials. https://www.citrix.com/blogs/2017/04/03/xendesktop-essentials-xenapp-essentials-now-available-in-azure-marketplace/

In this short period of time, there has been  customers who have purchased the services or are kicking the tires.
While I didn't give a number, I can say that it has been a pretty exciting first two weeks, and the interest from customers has been great.  Really great.

Both Essentials offerings run on Azure (exclusively) and are managed through Citrix Cloud.

Since these are new services, the documentation is constantly coming on-line. Here are some references that should get you over the initial hurdles of understanding how to implement it all.

The newly updated XenDesktop Essentials guide: http://docs.citrix.com/en-us/citrix-cloud/xenapp-and-xendesktop-service/xendesktop-essentials.html

If you were wondering if you could take advantage of Azure Active Directory Domain Service? Yes, you can: https://www.citrix.com/blogs/2017/04/11/xenapp-xendesktop-services-support-azure-ad-domain-services/

If you are in a hybrid cloud scenario (user workers in Azure with a VPN back to the datacenter where they need Kerberos or Windows pass-through authentication) you will need to setup up an Active Directory replica server in Azure: https://docs.microsoft.com/en-us/azure/active-directory/active-directory-install-replica-active-directory-domain-controller

Are you setting up Windows Desktops in Azure? 
Be aware that you must implement Azure Active Directory. More details on the way.

And take advantage of the Hybrid Use Benefit Windows 10 image in the Azure Gallery if you create a new golden desktop image.

Friday, April 7, 2017

Active Directory with XenDesktop Essentials in Azure

XenDesktop Essentials and XenApp Essentials have hit the Azure Marketplace, and they are catching on.

For those of you that remember Azure RemoteApp, XenApp Essentials is the replacement for that.  And for those of you that want to give Windows Client desktops to your user-base, XenDesktop Essentials is for that.
And, for those that want it all, There is XenApp and XenDesktop Service.  Which offers it all.

Now, the reason for my post.  Active Directory and Azure Active Directory.
There is a requirement of all of these solutions that the provisioned machines are joined to a domain.  This is where I see many folks getting confused between all of the various Active Directory options.

In reality, there are only two models that will work today (at the date of this post).  Let me describe them in terms of what you need to accomplish.

In both models, you have the user side running in Azure.  Whether that be XenApp Servers (Terminal Servers for you really old folks) or Desktops (Windows Client or Windows Server desktops).

Your answer to this next question defines the path that you need to head down.

Do your Azure based user sessions need to access resources in some other cloud / datacenter?
A different way to ask this - do you need a VPN between your users in Azure and whatever other resources they need to access in some other cloud / datacenter.

If your answer was no; 
Then I am calling you 'cloud born' or 'Azure based'.
Knowing this you can use Azure AD plus Azure Active Directory Domain Service.

AD Sync is built in, and most likely Azure AD is your source for users.  But you need the additional service to support domain join, group policy, and those traditional things that Active Directory provides.

I personally love the following guide for getting AADDS all up and running: Azure Active Directory Domain Services for Beginners

The trick here is that you need to use FQDNs for domain joins and domain references.  If you customize your Azure AD domain, use that.  If you don't it is YourDomain.onmicrosoft.com.

When you need to add Group Policy to lock things down; https://docs.microsoft.com/en-us/azure/active-directory-domain-services/active-directory-ds-admin-guide-administer-group-policy

If your answer was yes;
Then you are more of a 'traditional' enterprise that is in some hybrid deployment model.
Knowing this you need to use Azure AD plus Active Directory.

You will need to enable AD Sync, you will need to establish a replica domain controller in Azure, and you (probably) already have a VPN between your datacenter and Azure virtual network.

The replica domain controller in Azure: https://docs.microsoft.com/en-us/azure/active-directory/active-directory-install-replica-active-directory-domain-controller
Active Directory Sync / Connect to Azure AD: https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect
(It does not matter where you install / run that, just that you do).

In both cases; Don't forget to update the DNS settings of your Virtual Network with these new machine IP addresses.


Wednesday, April 5, 2017

Manually creating a Service Principal for XenDesktop Essentials

I have been looking at the customer experience around XenDesktop Essentials lately, and I have helped a few customers with issues around defining their Service Principal accounts.

Backing up a bit.  What is this 'Service Principal' account and what is it used for?

The Service Principal is the username / secret that is used by Citrix Cloud to talk to the Azure API and perform machine lifecycle actions in your Azure Subscription.

You could call it a delegated user, or an application user, or simply an application account.
The Service Principal is not a new concept in the enterprise world.  In my background we always created very restricted user accounts for use by applications, granting only those permissions that were necessary for the application to perform its functions.

I know there is guidance on using various PowerShell scripts to do this.  But quite honestly, it is so few clicks in the Azure Portal, you might as well do it there.  Far less hassle than installing the Azure cmdlets.

Plus - by doing it this way, you can quickly identify if you have the permissions necessary, and get it fixed or pass the responsibility to the person that can do it.

First, login to the Azure Account that 'Citrix' will be deploying workstations to.
Next make sure that you have a subscription container for the 'Citrix stuff' and a Virtual Network for the workstations to use all ready to go.


Create the App Registration / Service Principal
  1. Select the Azure Active Directory blade in the Azure Account
  2. Select 'App registrations'
  3. Select 'Add +'
  4. Enter a name, leave the application type as web app / API, and enter a Sign-on URL such as 'https://localhost/xde'
  5. Select Create
Grant it permission to interact with the Azure API for your account
  1. Once the registration is created, select it to view its settings
  2. Select 'Required permissions'
  3. Select 'Windows Azure Active Directory'
  4. Select 'Sign in and read user profile' and
  5. Select 'Read all users' basic profiles'
  6. Select 'Save'
  7. Select Add, Select an API, Select 'Windows Azure Service Management API', Select 'Select'
  8. Select 'Access Azure Service Management as organization users'
  9. Select 'Select'
  10. Select 'Done'
Add a Key (the secret)
  1. In the Settings, Select 'Keys'
  2. Enter a Key description, select a duration
  3. Select 'Save'
  4. Copy the Value of the key  (this value is necessary when this Service Principal is used with Citrix Cloud - and there are warnings that you can never see this key again)
Grant the Service Principal access to the Subscription for 'Citrix stuff'
  1. Select the Billing Blade
  2. Select the Subscription that you would like Citrix Cloud to be using
  3. Select 'Access control'
  4. Select '+ Add'
  5. Under 'Role' select 'Contributor'
  6. Under Select, type in the name of the App Registration you created (mine was 'xendesktop')
  7. Select the Azure AD user
  8. Select 'Save'
At this point in time, the Service Principal information can be handed off to your Citrix Administrator for establishing the Host connection to Azure in the Citrix Cloud portal.  
When Adding the Connection select the 'Use existing' option.

They will need;
  • the Subscription UUID
  • the Active Directory ID
  • the Application ID
  • the Application secret (that value that I mentioned you had to copy and save)
If you return the Azure Active Directory blade, Select the Properties, you will find the Directory ID.
Then select App registrations, select the one you created you can find the Application ID.
The Subscription id, is back under the Billing blade.


Wednesday, October 8, 2014

XenDesktop DSC resource and the Azure DSC VM Extension

After all of the previous blog posts, I thought that I would climax with a few real examples of using the DSC resource for XenDesktop.

Earlier this year (just a few++ weeks ago) Microsoft released the VM extensions for Virtual Machines.  This is the IaaS style VM role.  The VM Extensions are small modules that you can inject into your VM and you can interface with them.  The simplest way to think of it is they are purpose built agents.  You can configure them on provisioning, but also nifty is that you can update the configuration of an extension after deployment and do something else.

There is a script extension that can be used to download and execute any script(s) inside of your VM.  Handy for performing a number of things. You can use this to drive DSC if you like.
After that the DSC extension was released.  This one is purpose built just for DSC and the one this post will be focusing on.

I will warn you, I am going to expose a few warts of the process as I do this, just because the extension is built to support DSC and only the DSC packages.  And this process requires external media - yes, the media could be bundled into the DSC resource (the only workaround to this process at the moment), but that would make the resource really fat.  So, why not continue to think of it as two problems.

One thing - the DSC provider for XenDesktop expects media to be on the machine where it runs or a DVD attached ISO.  So a ZIP or ISO (DVD attached or downloaded to the machine) or folder.  This way there is no requirement to save credentials for connecting to some share or other store.

Now, let get everything set up.  (I am experimenting with a slightly different writing format here, so you will have to let me know if it works for you)

First of all, I am going to assume that you are sitting at your 'configuration computer' - that management computer that you use that has all of the consoles and what not installed.  In this case it is where you build all of your configurations that you later push to machines or place on your pull server.  Your configuration computer needs the XenDesktop resource module installed under the path "%ProgramFiles%\WindowsPowerShell\Modules" so a later cmdlet for the DSC script provider can automagically pick it up and bundle it for you.

Begin by connecting to your Azure subscription and set the storage account you will be using ( Set-AzureStorageAccount -StorageAccountName "YourCoolStorageAccount" )

Then upload the XenDesktop media.  ( the media is created from the ISO, simply ZIP the contents of the ISO - don't add any folders into the path)
Be sure that your container security is set to public blob (not public container) since we don't want folks discovering it.

For a later step you will need the URI to the blob that you just uploaded.

Now, we need to define the configuration (the DSC one) that will be applied to the VM.

For that I created a PowerShell script that accepts two parameters; the URI to the media and the role to be installed.

The DSC extension will run this and then apply the configuration.

Now that the configuration script exists, this must be packaged up, with the module, for the Azure DSC extension to use.  I saved mine with the name "XenDesktopInAzure.ps1".

The Azure PowerShell cmdlets have created a cmdlet just for this action; Publish-AzureVMDscConfiguration

After running the Publish-AzureVMDscConfiguration cmdlet, go check out your Azure management portal and look into the container and you will find a ZIP archive with a name that matches your script.  What the Public- command does is package the script and the modules that are used into the ZIP, then uploads them to Azure for you.

Now, define the VM, so that can be created.

First needed is an Azure VM Image - an 'image' is a virtual disk that is installed with an OS and prepared with sysprep and registered with Azure as an image - to the management platform, this means that it can specialize the OS on provisioning through mini-setup and the use of an unattended answer file.
Moving forward to the next step of building the VM configuration.

First, begin with a base VM configuration.

Then add the provisioning configuration ( these are the specialization settings ).
Then configure the Azure DSC VM extension.

Then create the VM.  Azure and the VM extension take care of processing the configuration script, and the configuration script downloads the ZIP, unpacks it, and installs the role.



One really cool thing about DSC is that you can keep applying configurations.  The last applied settings to a specific thing win, configurations are not undone when a new one is added, simply the changes defined in the new configuration are applied.  So, if you have some management layer, it can apply configuration after configuration if it so wanted to, or change a configuration over time to modify something.



As an option for delivering media, you can use a data disk with the XenDesktop media within it.  Then you can attach that to a new VM and have DSC mount the disk (rather, make sure it is mounted at a specific drive letter) and then perform the installation.

If you are using SCVMM, you can have an ISO attached to the VM as part of the template.  You could even use DSC to map a drive if that is what fits for your environment.  They are all possibilities.

Have fun! And please, send feedback!

Friday, August 15, 2014

Getting errors from the Azure VM custom script extension without RDP

Since Azure has begun adding the VM agent and other extension to IaaS virtual machines (persistent VM Roles) a number of scenarios and possibilities have opened up.

The extension is a simple binary that is dropped into your VM and built to be triggered and to perform very specific actions in the security context of Local System.

The Desired State Configuration Azure extension is the very latest. 

Prior to this I have been spending some time with the Custom Script Extension.  And it is rather nifty.  But the biggest pain that I have had is in working through the process of troubleshooting the script as I develop it.

I have found no way to capture the standard output - other than directing to a text file.  But then I have to RDP into the VM to fetch it.

I can also look at the runtime status of the extension while connected over RDP - that that is one file with bad line endings, making it difficult to read in Notepad.

Trough a bit of searching I came across a few tips and started poking around a bit with the Azure PowerShell cmdlets. 

What I discovered is that you cannot get the standard output, but you can get the standard error through the API.  So, if the script tosses some terminating error, there is output to be fetched. If there was no error, there is no output to be returned.

What I ended up doing is the following:

New-AzureVM -Location $location -VM $vmConfig -ServiceName $Service

(Get-Date -Format s) + " .. Watch the script extionsion to monitor the deployment and configuration"
Do {
    $Vm = Get-AzureVM -Name $vmName -ServiceName $Service

    Get-Date -Format s
    "  Machine status: " + $Vm.Status
    "  Guest agent status: " + $Vm.GuestAgentStatus.FormattedMessage.Message
       
    foreach ( $extension in $Vm.ResourceExtensionStatusList ) {
        If ( $extension.HandlerName -match 'CustomScriptExtension' ) {
            "  ExtensionStatus: " + $extension.ExtensionSettingStatus.FormattedMessage.Message
            $scriptStatus = $extension.ExtensionSettingStatus.FormattedMessage.Message
            $scriptError = foreach ($substatus in $extension.ExtensionSettingStatus.SubStatusList) { ($substatus.FormattedMessage.Message).Replace("\n","`n") }
        }
    }
    Start-Sleep 10
} until ( ($scriptStatus -eq "Finished executing command") )


I fetch the VM, then drill into the object for the Custom Script Extension, then I dig into the Extension status, and it even has sub status.  It is in this sub status where the Standard Error ends up being bubbled up for the extension.

I realize that this leaves me waiting around and calling back and forth.  But a green light on "Finished executing command" only means the script extension is completed running whatever I told it to run, not that it worked.

I just wish I could get the standard output.




 

Wednesday, June 18, 2014

Cannot load Windows PowerShell snap-in microsoft.windowsazure.serviceruntime

There are some issues that simply lose interest due to not being pertinent enough, I believe I have found one.
  
 
And I can see from searching that I am not alone here.
 
The thing that is going on is that I am using startup tasks in a Worker Role to install an MSI and configure it.
 
When the script being executed by my startup task attempts to: add-pssnapin microsoft.windowsazure.serviceruntime

I receive the error:
add-pssnapin : Cannot load Windows PowerShell snap-in microsoft.windowsazure.serviceruntime because of the following error: The Windows PowerShell snap-in module
 
F:\plugins\RemoteAccess\Microsoft.WindowsAzure.ServiceRuntime.Commands.dll does not have the required Windows PowerShell snap-in strong name Microsoft.WindowsAzure.ServiceRuntime.Commands, Version=1.0.0.0, Culture=neutral,
 
 
The work around that has been posted is to edit the registry key for the DLL, because the version is wrong.
My impression of this workaround is this:  "So, now I have to script a work around for an MSFT provided DLL because no one is updating the DLL registration for the snap-in in MSFT provided Gallery Images in Azure."
 
Mind you, these are developers, and if a workaround can be done in code - my experience has been that the issue is ignored after the workaround exists.

A workaround is great, but there are caveats to all of the workarounds posted thus far;
  • if I update the registry key with the incorrect version number, it still won’t load.  
  • I have to get the right version number and fix the registry entry.
  • And edit both the Assembly Name string and the version string.
Each posted workaround that I can find through search is a point version, and a point version edit.  A lasting workaround (since it seems like this bug is not going to get fixed anytime soon) is to dynamically deal with any version of the DLL and strong name enforcement in the OS.
I always preface that my solution might not be the most elegant thing that a developer comes up with, but I hope that folks can follow it and understand what I did.
 
# Get the current execution path
$exPath = Split-Path -parent $MyInvocation.MyCommand.Definition
$exPath # Echo for logging

######################################################################################
### Before we can load the service runtime, we must fix the broken registry information for the DLL
### and the version must be right, or it will continue to be broken.

$runtimeDllReg = Get-Item HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.WindowsAzure.ServiceRuntime
$runtimeDll = Get-Item $runtimeDllReg.GetValue('ModuleName')

$exportPath = $expath + "\AzureServiceRuntime.reg"

& $env:SystemRoot\System32\regedt32.exe /E $exportPath 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.WindowsAzure.ServiceRuntime'

# This is because the wait does not wait until regedit actually completes.

Do {

Start-Sleep 10

$regFile = Get-Item -Path $exportPath -ErrorAction SilentlyContinue

} Until ($regFile.Exists)

$runtimeRegFile Get-Content -Path $exportPath
$newRuntimeRegFile = @()

foreach ($e in $runtimeRegFile) {
     switch -wildcard ($e) {
          "*1.0.0.0*" { $e = $e -replace "1.0.0.0", ($runtimeDll.VersionInfo.FileMajorPart.ToString() + '.' + $runtimeDll.VersionInfo.FileMinorPart.ToString() + '.0.0') }
     }
     $newRuntimeRegFile += $e
}

Set-Content -Value $newRuntimeRegFile -Path $exportPath -Force

Start-Sleep 2

& $env:SystemRoot\System32\regedt32.exe /S $exportPath

Start-Sleep 2

# Load the necessary PowerShell modules for configuration and management Web and Work Roles
 
 
add-pssnapin microsoft.windowsazure.serviceruntime

# Take the VM Instance offline with Azure, or else Azure will keep attempting to start the script
 
 
Set-RoleInstanceStatus -Busy

You might wonder why I am using regedit.exe instead of the PowerShell cmdlets to set the value. What I found is that I kept running into permissions issues. And using regedit to export and import is a way around that.

Friday, February 28, 2014

SCVMM Service deployment Error (22758) The system cannot find the file specified – but it is right there

I spend days on this issue and did not want to lose the ‘why’ this cost me days.

First, the details of the error:

Error (22753)

The script command with properties: Type (PreInstall), Deployment Order (20) and Parent Type (ApplicationProfile), failed to complete successfully. Refer to the errors list for more information.

Error (22758)

The guest agent encountered an exception while running a script command. Win32ErrorCode: 2147942402 DetailedErrorMessage: The system cannot find the file specified

I can definitively tell you that this error has nothing and something to do with the script being run.  And, this is the SCVMM Agent itself tossing this error, not my script.

First; the most useful log in SCVMM Service Templates is the SCVMM Guest Agent diagnostic log.  You find it buried in the OS of the VM under %ProgramFiles%\<System Center Version>\<VMM Guest Agent Version>\bin\diagnostics\VmmGuestLog.svclog

If you try to open this up with Notepad or WordPad or NotePad++ it just looks like a bunch of poorly formatted XML.  Very difficult to troll through.

However, if you use Microsoft Service Trace Viewer, you have a totally different experience.  Trace Viewer is part of Visual Studio, which you can get an Express version for free, or download it here.

Looking through this I go looking for the events that the SCVMM Job log tossed at me.

I find:

4: GetExpandedGCEErrorInfo reported The script command with properties: Type (PreInstall), Deployment Order (20) and Parent Type (ApplicationProfile), failed to complete successfully. Refer to the errors list for more information.

But not the Win32ErrorCode.

Right after the above is the following:

4: Encountered an exception for ActionItem Type: Gce, Exception: Microsoft.VirtualManager.GuestAgent.Common.GuestAgentException: Error in the application.
   at Microsoft.VirtualManager.GuestAgent.Gce.GceProcessor.GetStdErrorMatch()
   at Microsoft.VirtualManager.GuestAgent.Gce.GceProcessor.PerformPostProcessing(List`1& warnings)
   at Microsoft.VirtualManager.GuestAgent.Gce.GceProcessor.Run(IQueryCancel queryCancel, List`1& warnings)
   at Microsoft.VirtualManager.GuestAgent.AIFactory.GceActionProcessor.ExecuteActionItemSync(Boolean restarting, ActionItem actionItem, IQueryCancel queryCancel, List`1& warnings)
   at Microsoft.VirtualManager.GuestAgent.QueueManager.QueueManager.QueueProcessorThread(Object context)

This definitively tells me that it is not my script, but instead the SCVMM Agent is the one not finding the file. The best that I can determine is that that GetStdErrorMatch() being empty is the root.  But what does a positive return look like?

And, to make it worse, the script ran.  Everything worked!  And if I checked the VM all of the SCVMM artifacts from my Custom Resource were there ( %ProgramData%VirtualMachineManagerData\<one of the temp paths>).  Nothing was missing!

I spent the next few days changing the script, settings for the execution, accounts, paths, different ways to execute it.  It would work sometimes but mostly not.  This was the most frustrating part.  Every now and then I would not get the error; that small glimmer of hope and gets you frustrated and ends up driving you insane.

On the drive home last night the pieces slid together.  This was my log cleanup script.  It was deleting all of the log files that were empty (0kb).  I produce a lot of logs,  this is remote and headless execution, it could be happening anywhere but I have no console to observe anything.  You have to capture every little thing that happens and you don’t want to sort through 26 files when only the 5 with any details actually mean anything.

Not being the one that wrote the code what I am guessing is that; It appears that the output file is created, then fetched, then written back to. And my script deleted it in the middle somewhere.  Simply timing alone, milliseconds, would let it pass.  A moment of a slow disk drive on a hypervisor, possibly.

So, I removed the capturing of the Standard Out and Standard Error and all is good.  Seems like a silly little thing, right?  But again, this is remote installation, if you don’t log it you have no idea what happened.  So turning off logging was actually the very last thing I had any desire to do.

Friday, February 1, 2013

Reincarnating - Exporting - Importing an Azure Virtual Machine and Service

There are times when I really like the fact that I have to figure stuff out.  And then I have to do it again, and then for a co-worker.  Then before you know it I have to do it in a really serious way.

You could also describe this as Exporting and Importing an entire multi-machine Service.

Why might you want to do this?

  • Moving a Service from one Subscription to another.
  • Moving a Service from one Storage Account to another.
  • Rebuilding a Service in place to force the machines to new hardware.
  • Recover a ‘misbehaving’ machine.
  • Fixing / changing configurations of the Virtual Network or subnet (okay, you would have to modify the XML files, but still).
  • Bringing your machine / service configuration down to earth (without some other tool).

In this case there are the traditional IaaS / Datacenter reasons, of which there a few.  But from the PaaS side there might be lots of reasons.  And coming for a datacenter background, the PaaS thinking around this simply seems foreign and strange, but it really is the ‘cloud’ way of thinking about this – when you are working at an abstracted layer.

In my case; this script began with having to destroy and reincarnate Virtual Machines in Azure (over and over again, for various reasons).  Then I had to move my entire Service to an entirely different Account and thus Subscription.  So it evolved into that.

To complicate things I use Virtual Networks (the Azure software defined networking abstraction) and its Subnets.

Why would you need to reincarnate a Virtual Machine?  (and why are you using this reincarnate word?).

I love the term ‘reincarnate’ when describing changing the configuration of an Azure machine.  Due to the PaaS beginnings it is a fitting description of what actually happens.  The virtual disk stays intact, only the configuration and the deployed machine go away.

For example, you want to move a VM to a different Virtual Network, or Subnet.  You need to destroy it and make it again.  If you want to change the Affinity Group, you need to destroy and make again.  If something on Azure is going all pear-shaped – what do they recommend?  Delete and recreate.

What happens when you reincarnate?  Well, for starters you end up on a different stamp.  Your machine will literally be some place else in the infrastructure.  If you are like me and constantly play with Beta releases, this can be a great thing (or a not so great thing).

Any way, lets get to preserving my script where I can find it in the future when I need it again.  The other thing this will demonstrate is walking through various things in Azure and dependency chains.

 

#Azure cmdlets v0.6.9

Import-Module -Name Azure

# Download the settings file.  This only needs to be done once, until the certificates expire.
# Get-AzurePublishSettingsFile # (this opens an IE window.  Logon.  A certificate is generated in all accounts that your Microsoft Account has access to and embedded in the settings file.  Download the settings file.)

Import-AzurePublishSettingsFile 'C:\Users\Public\Documents\MyServices.publishsettings'

###### start Azure Subscription Selector  ######
Get-AzureSubscription | ft
$sourceSub = [string](Read-Host -Prompt "Type the name of the SOURCE Subscription")
Select-AzureSubscription -SubscriptionName $sourceSub

Get-AzureStorageAccount | ft
$sourceStor = [string](Read-Host -Prompt "Type the name of the SOURCE Storage Account")
$sourceStorKey = Get-AzureStorageKey -StorageAccountName $sourceStor
Set-AzureSubscription -SubscriptionName $sourceSub -CurrentStorageAccount $sourceStor

Get-AzureStorageAccount | ft
$targetStor = [string](Read-Host -Prompt "Type the name of the TARGET Storage Account")
$targetStorKey = Get-AzureStorageKey -StorageAccountName $targetStor

Get-AzureSubscription | ft
$targetSub = [string](Read-Host -Prompt "Type the name of the TARGET Subscription")
Select-AzureSubscription -SubscriptionName $targetSub
###### end Azure Subscription Selector ######

###### start Azure Service VM export ######
Get-AzureService | ft ServiceName, Description, AffinityGroup, URL
$sourceSer = [string](Read-Host -Prompt "Type the name of the SOURCE Service")
Get-AzureVM -ServiceName $sourceSer | ft
$myVm = Read-Host -Prompt "what is the VM name you want to export?  (type '*' for all)"

If ($myVm -eq "*") {
    $path = 'C:\users\public\Downloads\azure\' + $sourceSer
    if ((Test-Path -Path $path -PathType Container) -eq $false) {New-Item -ItemType directory -Path $path}
    Get-AzureVNetConfig -ExportToFile ($path + "\vnetconfig.xml")
     Get-AzureVM -ServiceName $sourceSer | foreach { 
         $vmpath = $path + '\' + $_.Name + '.xml'
         Export-AzureVM -ServiceName $sourceSer -Name $_.Name -Path $vmpath
    }
}
else{
    $path = 'C:\users\public\Downloads\azure\' + $sourceSer 
    if ((Test-Path -Path $path -PathType Container) -eq $false) {New-Item -ItemType directory -Path $path}
    Get-AzureVNetConfig -ExportToFile ($path + "\vnetconfig.xml")
    $vmpath = $path + '\' + $myVm + '.xml'
    Export-AzureVM -ServiceName $sourceSer -Name $myVm -Path $vmpath
}
###### end Azure Service VM export ######

##### Start Service and Deployment deletion #####
$vms = Get-AzureVM -ServiceName $sourceSer

###### start Azure Service Removal ######
If ($myVm -eq "*") {
    foreach($vm in $vms){
        Remove-AzureVM -ServiceName $sourceSer -Name $vm.name
    }
    Start-Sleep 10
    Remove-AzureDeployment -ServiceName $sourceSer -Slot Production -Force
    Start-Sleep 10
    Remove-AzureService -ServiceName $sourceSer -Force
}
###### end Azure Service Removal ######

# Remove-AzureDisk to de-register from the VHD Library and remove the lease before the blobs can be copied to another Storage account
If ($myVm -eq "*") {
    foreach ($vm in $vms) {
        $osDisk = Get-AzureOSDisk -VM $vm
        $dataDisk = Get-AzureDataDisk -VM $vm
        If ($osDisk -ne $null){ Remove-AzureDisk -DiskName $osDisk.DiskName }
        Foreach ($dat in $dataDisk){
            If ($dat -ne $null){ Remove-AzureDisk -DiskName $dat.DiskName }
        }
    }
}

##### end Service and Deployment deletion ######

###### start Azure VM VHD copy ######


At this writing this is all hand wavy because the PowerShell cmdlets don’t support it yet.  I used a third party GUI that did the copying using the Azure Storage API.

 

## Start VHD registration with the VHD Library ##
Add-AzureDisk -OS Windows -MediaLocation
http://mydemo.blob.core.windows.net/vhds/myDemo-Foo-2013-1-8-762B.vhd -DiskName 'myDemo-Foo-0-2013010819464B' -Label Foo
Add-AzureDisk -OS Windows -MediaLocation
http://mydemo.blob.core.windows.net/vhds/MyDemo-Bar-2013-1-8-761B.vhd -DiskName 'myDemo-Bar-0-2013010819450B' -Label Bar
## End VHD registration with the VHD Library ##

###### end Azure VM VHD copy ######

 

##### start create new Service / VMs #####
# Query New Service name, and Subscription name
# $targetSer = $sourceSer  # for reincarnation

$vms = @()
$path = 'C:\users\public\Downloads\azure\' + $targetSer
$vmsToImport = Get-ChildItem $path

foreach ($vm in $vmsToImport) { 
    if ($vm.Name -match 'vnetconfig'){
        [xml]$vNetConfig = Get-Content -Path $vm.FullName  # if modification, it needs to happen, but this can be used later
        Set-AzureVNetConfig -ConfigurationPath $vm.FullName  -ErrorAction Continue  #if adding a VNet to a Subscription with an existing VNet, this will falsely error.  Check after this step to be sure the VNet created before adding the VMs.
    }
    else {
        $vms += Import-AzureVM -Path $vm.FullName
    }
}

# Choose the VNet to properly fill the following.  This is at the Subscription level
Get-AzureVNetSite | ft Name, AddressSpacePrefixes, AffinityGroup, Subnets, DnsServers, InUse
$myVNet = Read-Host "What is the Name of your target Virtual Network for the Domain Controller / DNS Server?"
$myVNet = Get-AzureVNetSite -VNetName $myVNet
# no need to query the subnet because the VM configurations contain that.

If ((Test-AzureName -Service $targetSer) -eq $false){
    # Importing to Existing Service is the assumption
    New-AzureVM -ServiceName $targetSer -VMs $vms -VNetName $myVNet.Name
}
else {
    # Creating new Service is the Assumption
    New-AzureVM -ServiceName $targetSer -VMs $vms -Location "You Should Know" -VNetName $myVNet.Name -AffinityGroup "SorryIDidn’tQuery"
}

##### end create new Service / VMs #####