AzureAutomation.psm1

<#
LICENSE:
The MIT License (MIT)
Copyright (c) 2020 Preston K. Parsard
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
DISCLAIMER:
THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a nonexclusive,
royalty-free right to use and modify the Sample Code and to reproduce and distribute the Sample Code, provided that You agree: (i) to not use Our name,
logo, or trademarks to market Your software product in which the Sample Code is embedded;
(ii) to include a valid copyright notice on Your software product in which the Sample Code is embedded; and (iii) to indemnify, hold harmless,
and defend Us and Our suppliers from and against any claims or lawsuits, including attorneys’ fees,
that arise or result from the use or distribution of the Sample Code.
#>


function New-AutomationAccountRunAsServicePrincipal
{
<#
.SYNOPSIS
 Creates a new Azure Automation Account RunAs service principal.
.DESCRIPTION
 This script creates a new Azure Automation Account RunAs service principal, which will be granted contributor level access at the subscription level to execute runbooks in the subscription that the automation account belongs to.
 In order for this script to create the RunAs account, the user or service principal context in which this script is executed, must have owner permissions to the specified subscription.
.EXAMPLE
 New-AutomationAccountRunAsServicePrincipal -rgName <rgName> `
 -AutomationAccountName <AutomationAccountName> `
 -ApplicationDisplayName <ApplicationDisplayName> `
 -SubscriptionId <SubscriptionId> `
 -SelfSignedCertPlainPassword <SelfSignedCertPlainPassword> `
 -SelfSignedCertNoOfMonthsUntilExpired <NumberOfMonthsForCerificateExpiry> `
 -Verbose
.PARAMETER rgName
 The resource group name in which the Azure automation account resides.
.PARAMETER AutomationAccountName
 The Azure automaiton account name for which the RunAs account will be provisioned.
.PARAMETER SubscriptionId
 The subscription ID for the subscription that the automation account belongs to.
.PARAMETER SelfSignedCertPlainPassword
 The user supplied password for the self-signed certificate that will be associated with the RunAs service principal
.PARAMETER SelfSignedCertNoOfMonthsUntilExpired
 The certificate expiration period in months. The default is 12.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Azure Automation, Certificate, RunAs, Runbooks
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
 2: https://docs.microsoft.com/en-us/azure/automation/manage-runas-account
#>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true)]
        [String] $rgName,
        [Parameter(Mandatory = $true)]
        [String] $AutomationAccountName,
        [Parameter(Mandatory = $true)]
        [String] $ApplicationDisplayName,
        [Parameter(Mandatory = $true)]
        [String] $SubscriptionId,
        [Parameter(Mandatory = $true)]
        [String] $SelfSignedCertPlainPassword,
        [int] $SelfSignedCertNoOfMonthsUntilExpired = 12
    ) # end param

    # Create self-signed certificate
    function New-SelfSignedCertificateForRunAsAccount
    {
        param
        (
            [string] $CertificateAssetName,
            [string] $SelfSignedCertPlainPassword,
            [string] $certPath,
            [string] $certPathCer,
            [string] $selfSignedCertNoOfMonthsUntilExpired
        ) # end param

        $Cert = New-SelfSignedCertificate -DnsName $$CertificateAssetName `
        -CertStoreLocation cert:\LocalMachine\My `
        -KeyExportPolicy Exportable `
        -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" `
        -NotAfter (Get-Date).AddMonths($selfSignedCertNoOfMonthsUntilExpired) `
        -HashAlgorithm SHA256

        $CertPassword = ConvertTo-SecureString $selfSignedCertPlainPassword -AsPlainText -Force
        Export-PfxCertificate -Cert ("Cert:\localmachine\my\" + $Cert.Thumbprint) -FilePath $certPath -Password $CertPassword -Force | Write-Verbose
        Export-Certificate -Cert ("Cert:\localmachine\my\" + $Cert.Thumbprint) -FilePath $certPathCer -Type CERT | Write-Verbose
    } # end function

    # Create the RunAs Account
    function New-ServicePrincipalForRunAsAccount
    {
        [OutputType([string])]
        [CmdletBinding()]
        param
        (
            [System.Security.Cryptography.X509Certificates.X509Certificate2] $PfxCert,
            [string] $ApplicationDisplayName
        ) # end param

        $keyValue = [System.Convert]::ToBase64String($PfxCert.GetRawCertData())
        $keyId = (New-Guid).Guid

        # Create an Azure AD application, AD App Credential, AD ServicePrincipal
        $homePage = "www." + $ApplicationDisplayName.ToLower() + ".com"
        # Requires Application Developer Role, but works with Application administrator or GLOBAL ADMIN
        New-AzADApplication -DisplayName $ApplicationDisplayName -HomePage ("http://" + $homePage) -IdentifierUris ("http://" + $keyId)
        $applicationId = (Get-AzAdApplication -DisplayName $ApplicationDisplayName | Where-Object {$_.IdentifierUris[0] -match $keyId}).ApplicationId.guid
        # Requires Application administrator or GLOBAL ADMIN
        # $ApplicationCredential = New-AzADAppCredential -ApplicationId $Application.ApplicationId -CertValue $keyValue -StartDate $PfxCert.NotBefore -EndDate $PfxCert.NotAfter
        New-AzADAppCredential -ApplicationId $applicationId -CertValue $keyValue -StartDate $PfxCert.NotBefore -EndDate $PfxCert.NotAfter
        # Requires Application administrator or GLOBAL ADMIN
        New-AzADServicePrincipal -ApplicationId $applicationId
        # New-AzADServicePrincipal -ApplicationId $Application.ApplicationId -PasswordCredential $ApplicationCredential
        # $servicePrincipalObj = Get-AzADServicePrincipal -ObjectId $ServicePrincipal.Id
        # Sleep here for a few seconds to allow the service principal application to become active (ordinarily takes a few seconds)
        Start-Sleep -Seconds 15
        # Requires User Access Administrator or Owner.
        $NewRole = New-AzRoleAssignment -ApplicationId $applicationId -RoleDefinitionName Contributor -ErrorAction SilentlyContinue
        $Retries = 0;
        While (($Retries -le 6) -and ($NewRole.RoleAssignmentId -eq $null))
        {
            Start-Sleep -Seconds 10
            $NewRole = Get-AzRoleAssignment -ServicePrincipalName $applicationId -ErrorAction SilentlyContinue
            $Retries++;
        } # end while
        return $applicationId
    } # end function

    # Create the certificate asset
    function New-AutomationCertificateAsset
    {
        param
        (
            [string] $resourceGroup,
            [string] $automationAccountName,
            [string] $certificateAssetName,
            [string] $certPath,
            [string] $certPlainPassword,
            [Boolean] $Exportable
        ) # end param

        $CertPassword = ConvertTo-SecureString $certPlainPassword -AsPlainText -Force
        Remove-AzAutomationCertificate -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $certificateAssetName -ErrorAction SilentlyContinue -Verbose
        New-AzAutomationCertificate -AutomationAccountName $automationAccountName -Name $certificateAssetName -Path $certPath -Description $certificateAssetName -Password $CertPassword -ResourceGroupName $resourceGroup -Exportable:$Exportable  | write-verbose
    } # end function

    # Create the connection asset
    function New-AutomationConnectionAsset
    {
        param
        (
            # Had to overwrite the value for the $resourceGroup parameter and then later extract a substring of 19 characters to avoid the issue filed at:
            # https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/38585344-new-azautomationconnection-cmdlet-incorrectly-stat
            [string] $resourceGroup,
            [string] $automationAccountName,
            [string] $connectionAssetName,
            [string] $connectionTypeName,
            [System.Collections.Hashtable] $connectionFieldValues
        ) # end params

        Remove-AzAutomationConnection -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $connectionAssetName -Force -ErrorAction SilentlyContinue -Verbose
        New-AzAutomationConnection -ResourceGroupName $resourceGroup -AutomationAccountName $automationAccountName -Name $connectionAssetName -ConnectionTypeName $connectionTypeName -ConnectionFieldValues $connectionFieldValues
    } # end function

    # Create a Run As account by using a service principal
    $CertificateAssetName = "AzureRunAsCertificate"
    $ConnectionAssetName = "AzureRunAsConnection"
    $ConnectionTypeName = "AzureServicePrincipal"

    $PfxCertPathForRunAsAccount = Join-Path $env:TEMP -ChildPath ($CertificateAssetName + ".pfx")
    $PfxCertPlainPasswordForRunAsAccount = $SelfSignedCertPlainPassword
    $CerCertPathForRunAsAccount = Join-Path $env:TEMP -ChildPath ($CertificateAssetName + ".cer")

    New-SelfSignedCertificateForRunAsAccount -CertificateAssetName $CertificateAssetName `
    -SelfSignedCertPlainPassword $SelfSignedCertPlainPassword `
    -certPath $PfxCertPathForRunAsAccount `
    -certPathCer $CerCertPathForRunAsAccount `
    -selfSignedCertNoOfMonthsUntilExpired  $SelfSignedCertNoOfMonthsUntilExpired

    # Create the Automation certificate asset
    New-AutomationCertificateAsset -resourceGroup $rgName `
    -automationAccountName $AutomationAccountName `
    -certificateAssetName $CertificateAssetName `
    -certPath $PfxCertPathForRunAsAccount `
    -certPlainPassword $PfxCertPlainPasswordForRunAsAccount `
    -Exportable $true
    # Wait for 2 minutes to avoid a race condition to allow the RunAs Account time to populate the certificate attributes.
    Start-Sleep -Seconds 120
    # Create a service principal
    $PfxCert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @($PfxCertPathForRunAsAccount, $PfxCertPlainPasswordForRunAsAccount)
    $applicationId = New-ServicePrincipalForRunAsAccount -PfxCert $PfxCert -applicationDisplayName $ApplicationDisplayName
    [guid]$applicationId = ($applicationId)[0].ApplicationId

    # Populate the ConnectionFieldValues
    $SubscriptionInfo = Get-AzSubscription -SubscriptionId $SubscriptionId
    $TenantID = $SubscriptionInfo | Select-Object TenantId -First 1
    $Thumbprint = $PfxCert.Thumbprint
    $ConnectionFieldValues = @{"ApplicationId" = $applicationId; "TenantId" = $TenantID.TenantId; "CertificateThumbprint" = $Thumbprint; "SubscriptionId" = $SubscriptionId}

    # Create an Automation connection asset named AzureRunAsConnection in the Automation account. This connection uses the service principal.
    New-AutomationConnectionAsset -resourceGroup $rgName `
    -automationAccountName $AutomationAccountName `
    -connectionAssetName  $ConnectionAssetName `
    -ConnectionTypeName  $ConnectionTypeName `
    -ConnectionFieldValues $ConnectionFieldValues

    # Cleanup temporary certificate files from local file system
    Remove-Item -Path $env:TEMP -Include *.pfx, *.cer -Force -Verbose

} # end function

function Publish-AutomationAccountRunbookScripts
{
<#
.SYNOPSIS
 Uploads and publishes a set of runbook scripts to an automation account.
.DESCRIPTION
 This function uploads and publishes a set of PowerShell runbook scripts to an Azure Automation account so they can be executed manually, triggered by an event, or scheduled.
.EXAMPLE
 Publish-AutomationAccountRunbookScripts -rbScripts <rbScripts> -ResourceGroupName <ResourceGroupName> -Verbose
.PARAMETER rbScripts
 The array of full runboook script paths to publish.
.PARAMETER ResourceGroupName
 The Azure resource group name hosting the automation account where the runbooks will be published to.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Azure Automation, Runbooks, Publish
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
#>

    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]]$rbScripts,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$ResourceGroupName,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$AutomationAccountName
    ) # end param

    ForEach ($runbookScript in $runbookScripts)
    {
        Import-AzAutomationRunbook -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Path $runbookScript -Type PowerShell -LogProgress $true -LogVerbose $true -Published -Verbose
    } # end foreach
} # end function

function New-AutomationAccountRunbookModules
{
<#
.SYNOPSIS
 Imports module assets into an Azure automation account.
.DESCRIPTION
 This function imports modules from the public https://www.powershellgallery.com repository, into a specified Azure automation account as a module asset to support runbooks or state configuration scripts.
.EXAMPLE
 New-AutomationAccountRunbookModules -ResourceGroupName <ResourceGroupName> -runbookModules <runbookModules>
.PARAMETER ResourceGroupName
 The resource group hosting the Azure automation account where the modules will be imported into.
.PARAMETER runbookModules
 The array of runbook modules that will be imported into the specified aut
.PARAMETER AutomationAccountName
 The Azure automation account that the modules will be imported into as module assets.
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: Modules, Azure Automation, Assets
.LINK
 1: https://www.powershellgallery.com/packages/AzureAutomation
 2: https://mcpmag.com/articles/2018/09/27/upload-powershell-gallery-module-to-azure.aspx
#>

    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $ResourceGroupName,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string[]] $runbookModules,
        [parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $AutomationAccountName
    ) # end param
    $i = 0
    $preReqModule = "Az.Accounts"
    $repoUriPrefix = (Find-Module -Name $preReqModule -Repository PSGallery).RepositorySourceLocation
    $repoUriInfix = "/package/"
    ForEach ($runbookModule in $runbookModules)
    {
        $i++
        If ($i -eq 1)
        {
            $runbookModule = $preReqModule
            $uri = $repoUriPrefix + $repoUriInfix + $runbookModule
            New-AzAutomationModule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $runbookModule -ContentLinkUri $uri -Verbose -ErrorAction SilentlyContinue
        } # end if
        ElseIf ($runbookModule -ne $preReqModule)
        {
            $uri = $repoUriPrefix + $repoUriInfix + $runbookModule
            New-AzAutomationModule -ResourceGroupName $ResourceGroupName -AutomationAccountName $AutomationAccountName -Name $runbookModule -ContentLinkUri $uri -Verbose -ErrorAction SilentlyContinue
        } # end else if
        # Wait for 4 minutes
        Start-Sleep -Seconds 240
    } # end foreach
} # end function

function Format-AutomationAccountScheduleTimeZoneOffset
{
<#
.SYNOPSIS
 Convert the current UTC offset of the local time zone (i.e. -5 for EST US) into the runbook time scheduling format: "yyyy-MM-ddT00:00:00-00:00"
.DESCRIPTION
 This function will detect the current UTC offset based on the local system time from where the script executes, and convert it to the required Azure Automation Account schedule format so that runbooks can be scheduled.
.EXAMPLE
 Format-AutomationAccountScheduleTimeZoneOffset -offset <offset>
.PARAMETER offset
 The current UTC offset of the local system time zone from where the script executes (i.e. If the script runs from a machine in the US Eastern Standard Time zone <EST>, the offset would be "-5")
.INPUTS
 None
.OUTPUTS
 None
.NOTES
 AUTHOR: Preston K. Parsard
 KEYWORDS: NSG, Network Security Group, Subnet
.LINK
 1: https://www.powershellgallery.com/ARMDeploy
#>

    [OutputType([string])]
    [CmdletBinding()]
    param
    (
        [ValidateLength(1,3)]
        [string]$offset
    ) # end param
    if ($offset -match "-")
    {
        $offset = $offset.Remove(0,1)
        If ($offset.Length -eq 1)
        {
            $offset = $offset.Insert(0,"-0")
        } # end if
        elseif ($offset.Length -eq 2)
        {
            $offset = $offset.Insert(0,"-")
        } # end else
    } # end if
    elseif ($offset -notmatch "-")
    {
        if ($offset.Length -eq 1)
        {
            $offset = $offset.Insert(0,"+0")
        } # end if
        elseif ($offset.Length -eq 2)
        {
            $offset = $offset.Insert(0,"+")
        } # end else
    } # end else if
    return $offset
} # end function

Export-ModuleMember -Function *AutomationAccount* -Verbose