
Azure Automation Release pipeline for Runbooks & Modules
I recently did a refactor of my release pipeline code for azure automation Runbooks and Modules to support Runtime Environments. As this still is not added to the Az-module even as RTE has now been GA for some time.
Therefor I had to write some Powershell functions that uses the ARM REST-api directly instead of Import-AzAutomationRunbook, Publish-AzAutomationRunbook and New-AzAutomationModule i previously used.
One downside of this is one needs to spinn up a public accessible storage account to temporary store the Runbooks and Modules for the ARM-api to consume when publishing to the azure automation account. So therefore the pipeline identity will need rights on the azure automation resource group to be able to create the storage account there. The code will automatically remove the storage account after it is finished. There seems to be no other way around this, and no way of using a more secure storage account config for the ARM-api to use. Though risk should be minimal as the storage account will only exist until the publish logic is done, though if one are publishing a lot of modules this can take some time.
I use azure devops and the traditional release pipeline for running the code, but should run on any tool that can orchestrate calling a powershell script.

To run the script one has to call it with input parameters defined belove.
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 | <# .SYNOPSIS Release Pipeline logic to publish updated Runbooks to the different environments defined in AzD. Note: logic can not handle multiple Azure Automation Account in same subscription. Note: check to see if azure policy that blocks public access storage accounts are active, if so temp storage account creation will fail .DESCRIPTION Account running script must have RBAC on AA account RG set so it is allowed to create an Azure Storage account to store Runbooks and Modules to upload. .PARAMETER SubscriptionName Required. Name of subscription where Azure Automation Account resides. .PARAMETER AutomationAccountName Required. Name of azure automation account to publish assets to. .PARAMETER RuntimeEnvironmentName Required. Name of azure automation runtime environment to publish assets to. .NOTES AUTHOR: Morten Lerudjordet #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [ValidateNotNullorEmpty()] [String]$SubscriptionName, [Parameter(Mandatory = $true)] [ValidateNotNullorEmpty()] [String]$AutomationAccountName, [Parameter(Mandatory = $true)] [ValidateNotNullorEmpty()] [String]$RuntimeEnvironmentName ) # fix for terminal rendering problems in release if ($PSStyle.OutputRendering -and $ENV:AGENT_NAME) { $PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]"PlainText" } $ErrorTriggered = $false Write-Host -Object "`n-----------------------------------------------" Write-Host -Object " Start " Write-Host -Object "-----------------------------------------------" Write-Host -Object "Starting Task at time: $(Get-Date -Format r).`nRunning PS version: $($PSVersionTable.PSVersion)`nOn agent: $($env:computername)" #region Variables $StorageContainerNames = @("modules", "runbooks") $AzureAutomationAPIversion = "2024-10-23" #endregion #region Functions #region Get-AutomationJob function Get-AutomationJob { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $AutomationAccountName, [Parameter(Mandatory = $false)] [String] $RunbookName = $null, [Parameter(Mandatory = $false)] [String] $Status = $null ) try { $ReturnJobs = @() $AzContext = Get-AzContext if ( $AzContext ) { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/jobs?api-version=$AzureAutomationAPIversion" $Response = Invoke-AzRestMethod -Uri $AArtEnvURL -Method GET -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to get packages from runtime environment: $RuntimeEnvironmentName in automation account: $AutomationAccountName" -ErrorAction Stop } else { if ( $Response ) { $AAjobs = ($Response.Content | ConvertFrom-Json ).value if ( $RunbookName -and $Status) { $AAfilteredJobs = $AAjobs | Where-Object { $PSItem.properties.runbook.name -eq $RunbookName -and $PSItem.properties.status -eq $Status } } elseif ( $RunbookName ) { $AAfilteredJobs = $AAjobs | Where-Object { $PSItem.properties.runbook.name -eq $RunbookName } } elseif ( $Status) { $AAfilteredJobs = $AAjobs | Where-Object { $PSItem.properties.status -eq $Status } } else { $AAfilteredJobs = $AAjobs } foreach ($Job in $AAfilteredJobs) { $CustomJob = [PSCustomObject][ordered]@{ ResourceGroupName = $ResourceGroupName AutomationAccountName = $AutomationAccountName RunbookName = $Job.properties.runbook.name RuntimeEnvironmentName = $Job.properties.jobRuntimeEnvironment.runtimeEnvironmentName Status = $Job.properties.status } $ReturnJobs += $CustomJob $CustomJob = $null } if ( $ReturnJobs ) { return $ReturnJobs } else { if ( $RunbookName -and $Status) { Write-Warning -Message "No jobs found for runbook: $RunbookName with status: $Status in automation account: $AutomationAccountName" } elseif ( $Status ) { Write-Warning -Message "No jobs found with status: $Status in automation account: $AutomationAccountName" } elseif ( $RunbookName ) { Write-Warning -Message "No jobs found for runbook: $RunbookName in automation account: $AutomationAccountName" } else { Write-Warning -Message "No jobs found in automation account: $AutomationAccountName" } } } else { Write-Error -Message "No data returned from api targeting runtime environment: $RuntimeEnvironmentName in automation account: $AutomationAccountName" -ErrorAction Stop } } } else { Write-Error -Message "Faild to retrieve az context with subscription id" -ErrorAction Stop } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #region Get-RuntimeEnvAutomationModule function Get-RuntimeEnvAutomationModule { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $AutomationAccountName, [Parameter(Mandatory = $true)] [String] $RuntimeEnvironmentName, [Parameter(Mandatory = $false)] [String] $Name = $null ) try { $CustomAArtEnvPackages = @() $AzContext = Get-AzContext if ( $AzContext ) { if ( $Name ) { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/runtimeEnvironments/$RuntimeEnvironmentName/packages/$($Name)?api-version=$AzureAutomationAPIversion" } else { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/runtimeEnvironments/$($RuntimeEnvironmentName)/packages?api-version=$AzureAutomationAPIversion" } $Response = Invoke-AzRestMethod -Uri $AArtEnvURL -Method GET -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to get packages from runtime environment: $RuntimeEnvironmentName in automation account: $AutomationAccountName" -ErrorAction Stop } else { if ( $Response ) { if ( $Name ) { $AArtEnvPackages = ($Response.Content | ConvertFrom-Json ) } else { $AArtEnvPackages = ($Response.Content | ConvertFrom-Json ).value } ForEach ($Package in $AArtEnvPackages) { $CustomAPackage = [PSCustomObject][ordered]@{ ResourceGroupName = $ResourceGroupName AutomationAccountName = $AutomationAccountName RuntimeEnvironmentName = $RuntimeEnvironmentName Name = $Package.name Version = $Package.Properties.version SizeInBytes = $Package.Properties.sizeInBytes CreationTime = $Package.systemData.createdAt LastModifiedTime = $Package.systemData.lastModifiedAt ProvisioningState = $Package.Properties.provisioningState } $CustomAArtEnvPackages += $CustomAPackage $CustomAPackage = $null } if ( $CustomAArtEnvPackages ) { return $CustomAArtEnvPackages } else { if ( $Name ) { Write-Warning -Message "No packages with name: $Name found in runtime environment: $RuntimeEnvironmentName hosted in automation account: $AutomationAccountName" } else { Write-Warning -Message "No packages found in runtime environment: $RuntimeEnvironmentName hosted in automation account: $AutomationAccountName" } } } else { Write-Error -Message "No data returned from api targeting runtime environment: $RuntimeEnvironmentName in automation account: $AutomationAccountName" -ErrorAction Stop } } } else { Write-Error -Message "Failed to retrieve az context with subscription id" -ErrorAction Stop } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #region Import-RuntimeEnvAutomationModule function Import-RuntimeEnvAutomationModule { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $AutomationAccountName, [Parameter(Mandatory = $true)] [String] $RuntimeEnvironmentName, [Parameter(Mandatory = $true)] [String] $Name, [Parameter(Mandatory = $true)] [String]$ContentLink ) try { $CustomAArtEnvPackages = @() $AzContext = Get-AzContext if ( $AzContext ) { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/runtimeEnvironments/$RuntimeEnvironmentName/packages/$($Name)?api-version=$AzureAutomationAPIversion" $Payload = @{ "properties" = @{ "contentLink" = @{ "uri" = $ContentLink } } } $Response = Invoke-AzRestMethod -Uri $AArtEnvURL -Payload $($Payload | ConvertTo-Json) -Method PUT -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to upload packages for environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Stop } elseif ( $Response.StatusCode -notmatch '20[01]' ) { Write-Error -Message "API returned status code: $($Response.StatusCode) trying to upload package: $Name to environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Continue $ResponseContent = $Response.Content | ConvertFrom-Json if ( $ResponseContent.error ) { Write-Error -Message "Error message: $($ResponseContent.error.message)" -ErrorAction Stop } } else { if ( $Response ) { $ResponseInfo = $Response.Content | ConvertFrom-Json Write-Verbose -Message "Module import status: $($ResponseInfo.properties.provisioningState)" $ResponseInfo = $Response.Content | ConvertFrom-Json $PackageInfo = [PSCustomObject][ordered]@{ ResourceGroupName = $ResourceGroupName AutomationAccountName = $AutomationAccountName RuntimeEnvironmentName = $RuntimeEnvironmentName Name = $Name ContentLink = $ContentLink ProvisioningState = $ResponseInfo.Properties.provisioningState } return $PackageInfo } else { Write-Error -Message "Response from package upload is empty" -ErrorAction Stop } } } else { Write-Error -Message "Failed to retrieve az context with subscription id" -ErrorAction Stop } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #region Import-RuntimeEnvAutomationRunbook function Import-RuntimeEnvAutomationRunbook { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $AutomationAccountName, [Parameter(Mandatory = $true)] [String] $RuntimeEnvironmentName, [Parameter(Mandatory = $true)] [String] $Name, [Parameter(Mandatory = $false)] [String] $Location = "West Europe", [Parameter(Mandatory = $true)] [String]$ContentLink, [Parameter(Mandatory = $false)] [bool]$RunbookPublishDraft = $true, [Parameter(Mandatory = $false)] [ValidateSet("PowerShell")] [String]$RunbookType = "PowerShell", [Parameter(Mandatory = $false)] [String]$Description = "" ) try { $AzContext = Get-AzContext if ( $AzContext ) { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/runbooks/$($Name)?api-version=$AzureAutomationAPIversion" if ( $RunbookPublishDraft ) { $Payload = @{ "name" = $Name "location" = $Location "properties" = @{ "publishContentLink" = @{ "uri" = $ContentLink } "description" = $Description "logProgress" = $true "logActivityTrace" = 1 "logVerbose" = $false "runbookType" = $RunbookType "runtimeEnvironment" = $RuntimeEnvironmentName } } } else { $Payload = @{ "name" = $Name "location" = $Location "properties" = @{ "publishContentLink" = @{ "uri" = $ContentLink } "description" = $Description "draft" = @{} "logProgress" = $false "logVerbose" = $false "runbookType" = $RunbookType "runtimeEnvironment" = $RuntimeEnvironmentName } } } $Response = Invoke-AzRestMethod -Uri $AArtEnvURL -Payload $($Payload | ConvertTo-Json) -Method PUT -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to import Runbook for environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Stop } elseif ( $Response.StatusCode -notmatch '20[01]' ) { Write-Error -Message "API returned status code: $($Response.StatusCode) trying to import Runbook: $Name to environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Continue $ResponseContent = $Response.Content | ConvertFrom-Json if ( $ResponseContent.error ) { Write-Error -Message "Error message: $($ResponseContent.error.message)" -ErrorAction Stop } } else { if ( $Response ) { $ResponseInfo = $Response.Content | ConvertFrom-Json Write-Verbose -Message "Runbook import status: $($ResponseInfo.properties.provisioningState)" $ResponseInfo = $Response.Content | ConvertFrom-Json $PackageInfo = [PSCustomObject][ordered]@{ ResourceGroupName = $ResourceGroupName AutomationAccountName = $AutomationAccountName RuntimeEnvironmentName = $RuntimeEnvironmentName Name = $Name ContentLink = $ContentLink ProvisioningState = $ResponseInfo.Properties.provisioningState runbookType = $ResponseInfo.Properties.runbookType State = $ResponseInfo.Properties.state } return $PackageInfo } else { Write-Error -Message "Response from Runbook import is empty" -ErrorAction Stop } } } else { Write-Error -Message "Failed to retrieve az context with subscription id" -ErrorAction Stop } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #region Publish-RuntimeEnvAutomationRunbook function Publish-RuntimeEnvAutomationRunbook { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $AutomationAccountName, [Parameter(Mandatory = $true)] [String] $RuntimeEnvironmentName, [Parameter(Mandatory = $true)] [String] $Name ) try { $AzContext = Get-AzContext if ( $AzContext ) { $AArtEnvURL = "https://management.azure.com/subscriptions/$($AzContext.Subscription.Id)/resourceGroups/$ResourceGroupName/providers/Microsoft.Automation/automationAccounts/$AutomationAccountName/runbooks/$($Name)/publish?api-version=$AzureAutomationAPIversion" $Response = Invoke-AzRestMethod -Uri $AArtEnvURL -Method POST -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to publish Runbook for environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Stop } elseif ( $Response.StatusCode -notmatch '20[01]' ) { Write-Error -Message "API returned status code: $($Response.StatusCode) trying to publish Runbook: $Name to environment: $RuntimeEnvironmentName in account: $AutomationAccountName" -ErrorAction Continue $ResponseContent = $Response.Content | ConvertFrom-Json if ( $ResponseContent.error ) { Write-Error -Message "Error message: $($ResponseContent.error.message)" -ErrorAction Stop } } else { if ( $Response.StatusCode -eq "202" ) { $ResponseInfo = $Response.Content | ConvertFrom-Json Write-Verbose -Message "Runbook publish status: success" $ResponseInfo = $Response.Content | ConvertFrom-Json $PackageInfo = [PSCustomObject][ordered]@{ ResourceGroupName = $ResourceGroupName AutomationAccountName = $AutomationAccountName RuntimeEnvironmentName = $RuntimeEnvironmentName Name = $Name } return $PackageInfo } else { Write-Error -Message "Response from Runbook publish is empty" -ErrorAction Stop } } } else { Write-Error -Message "Failed to retrieve az context with subscription id" -ErrorAction Stop } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #region New-TempStorageAccount function New-TempStorageAccount { [CmdletBinding()] Param( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $Location, [Parameter(Mandatory = $true)] [String] $Name, [Parameter(Mandatory = $true)] [String[]] $StorageContainerNames ) try { $StorageAccountCreated = $false $ContainerError = $false $StorageAccount = New-AzStorageAccount -ResourceGroupName $ResourceGroupName ` -Name $Name -SkuName "Standard_LRS" -AllowBlobPublicAccess $true -PublicNetworkAccess "Enabled" -AccessTier "Hot" ` -Location $Location -Kind "BlobStorage" -MinimumTlsVersion "TLS1_2" -EnableHttpsTrafficOnly $true ` -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { if($oErr.ErrorDetails.Message) { Write-Error -Message "Failed to create temp storage account: $Name" -ErrorAction Continue Write-Error -Message "Error msg: $($oErr.ErrorDetails.Message)" -ErrorAction Stop } else { Write-Error -Message "Failed to create temp storage account: $Name)" -ErrorAction Continue Write-Error -Message "Error msg: $($oErr.Exception.Message)" -ErrorAction Stop } } else { $StorageAccountCreated = $true } $Ctx = $StorageAccount.Context if ($Ctx) { # Write-Information -Object "Creating storage container(s) for RTE asset types:`n$($StorageContainerNames | Out-String)" foreach ($Container in $StorageContainerNames) { $null = New-AzStorageContainer -Name $Container -Context $Ctx -Permission Container -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { if($oErr.ErrorDetails.Message) { Write-Error -Message "Failed to create temp storage account container: $Container" -ErrorAction Continue Write-Error -Message "Error msg: $($oErr.ErrorDetails.Message)" -ErrorAction Continue } else { Write-Error -Message "Failed to create temp storage account container: $Container" -ErrorAction Continue Write-Error -Message "Error msg: $($oErr.Exception.Message)" -ErrorAction Continue } $oErr = $null $ContainerError = $true } } } else { Write-Error -Message "Failed to get temp storage account context for: $Name" -ErrorAction Continue } if($ContainerError) { Write-Error -Message "Error creating container in temp storage account" -ErrorAction Continue } else { if($StorageAccountCreated) { if($Ctx) { # return storage account context for temp storage return $Ctx } else { return "Created" } } } } catch { if ($_.Exception.Message) { Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Error -Message "$($_.Exception)" -ErrorAction Continue } throw "$($_.Exception)" } } #endregion #endregion try { #region Initialize # Write-Host -Object "##[group]Initialize" $VerbosePreference = "silentlycontinue" $Error.Clear() Import-Module -Name Az.Accounts, Az.Automation, Az.Storage -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to load needed modules, check that Az.Automation is available on pipeline agent host" -ErrorAction Stop } If($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) { $VerbosePreference = "Continue" } else { $VerbosePreference = "silentlycontinue" } $Path = Resolve-Path -Path $PSScriptRoot -ErrorAction SilentlyContinue if ( [string]::IsNullOrEmpty($Path) ) { $PSScriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path -Parent if ($PSScriptRoot) { $RunbooksPath = Resolve-Path -Path "$PSScriptRoot\..\Runbooks" -ErrorAction Ignore $ModulesPath = Resolve-Path -Path "$PSScriptRoot\..\Modules" -ErrorAction Ignore } else { Write-Host -Object "##vso[task.logissue type=error;]Failed to resolve path of files to publish." Write-Error -Message "Failed to resolve path of files to publish" -ErrorAction Stop } } else { $RunbooksPath = Resolve-Path -Path "$Path\..\Runbooks" -ErrorAction Ignore $ModulesPath = Resolve-Path -Path "$Path\..\Modules" -ErrorAction Ignore } Write-Host -Object "`nSelecting subscription: $SubscriptionName" $null = Select-AzSubscription -SubscriptionName $SubscriptionName -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to select subscription: $SubscriptionName" -ErrorAction Stop } if ($AutomationAccountName) { $AutomationAccount = Get-AzAutomationAccount -ErrorAction SilentlyContinue -ErrorVariable oErr | Where-Object { $_.AutomationAccountName -eq $AutomationAccountName } if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve automation account. Error: $($oErr.Message)" Write-Error -Message "Failed to retrieve automation account" -ErrorAction Stop } else { if ($AutomationAccount) { Write-Host -Object "Current automation account: $($AutomationAccount.AutomationAccountName), in resource group: $($AutomationAccount.ResourceGroupName) in: $($AutomationAccount.Location)." } else { Write-Error -Message "No AA account with name: $AutomationAccountName found" -ErrorAction Stop } } } else { $AutomationAccount = Get-AzAutomationAccount -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve automation account. Error: $($oErr.Message)" Write-Error -Message "Failed to retrieve automation account" -ErrorAction Stop } else { # check if multiple AA accounts are selected if($AutomationAccount -is [array]) { Write-Error -Message "Only support selecting one azure automation account, multiple found" -ErrorAction Stop } else { Write-Host -Object "Current automation account: $($AutomationAccount.AutomationAccountName), in resource group: $($AutomationAccount.ResourceGroupName) in: $($AutomationAccount.Location)" } } } # Write-Host -Object "##[endgroup]" #endregion #region Create temp azure storage account # Write-Host -Object "##[group]Storage Account" # only create SA if there are assets to publish if($RunbooksPath -or $ModulesPath) { $Number = Get-Random -Minimum 1000 -Maximum 10000 if ( $AutomationAccount.AutomationAccountName -match "-") { $AutomationAccountStripped = ($AutomationAccount.AutomationAccountName).Replace('-', '') } elseif ( $AutomationAccount.AutomationAccountName -match "_") { $AutomationAccountStripped = ($AutomationAccount.AutomationAccountName).Replace('_', '') } else { $AutomationAccountStripped = $AutomationAccount.AutomationAccountName } # create temp storage account $StorageAccountName = ("$($AutomationAccountStripped)$Number").ToLower() # check if storage account name is to long if( $StorageAccountName.Length -gt 24) { $StorageAccountName = $StorageAccountName.Substring(0, 24) } Write-Host -Object "Creating temp storage account with name: $StorageAccountName" $Ctx = New-TempStorageAccount -ResourceGroupName $AutomationAccount.ResourceGroupName ` -Location $AutomationAccount.Location -Name $StorageAccountName -StorageContainerNames $StorageContainerNames ` -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Failed to create temp storage account with containers: $($StorageContainerNames | Out-String)" -ErrorAction Stop } else { if ( $Ctx -and $Ctx -ne "Created") { Write-Host -Object "Temp storage account created successfully with name: $StorageAccountName" } else { Write-Host -Object "##vso[task.logissue type=error;]Temp storage account context object is empty" Write-Error -Message "Temp storage account context object is empty" -ErrorAction Stop } } } # Write-Host -Object "##[endgroup]" #endregion #region Import Runbooks to RTE # Write-Host -Object "##[group]Runbooks" Write-Host -Object "`n-----------------------------------------------" Write-Host -Object " Runbooks " Write-Host -Object "-----------------------------------------------`n" if ($RunbooksPath) { Write-Host -Object "Fetching Runbook files from path: $RunbooksPath" $Files = Get-ChildItem $RunbooksPath -File -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve files from pipeline with error: $($oErr.Message)" Write-Error -Message "Failed to retrieve Runbook files" -ErrorAction Stop } else { Write-Host -Object "Successfully retrieved Runbook files from agent" if ($Files) { Write-Host -Object "Runbook files found on agent:`n$($Files.Name)" } else { Write-Host -Object "No Runbook files found on agent to publish" } } if ( $Files ) { $ContainerName = "runbooks" #region Process runbooks to upload to RTE ForEach ($Runbook in $Files) { $RunbookType = Switch -Exact ($Runbook.Extension) { ".ps1" { "PowerShell" } ".py" { "Python3" } } if ( [string]::IsNullOrEmpty($RunbookType) ) { $AST = [System.Management.Automation.Language.Parser]::ParseFile($Runbook.FullName, [ref]$null, [ref]$null); if ($null -ne $AST.EndBlock -and $AST.EndBlock.Extent.Text.ToLower().StartsWith("workflow")) { Write-Verbose "File is a PowerShell workflow" $RunbookType = "PowerShellWorkflow" } } if ($RunbookType) { Write-Host Write-Host -Object "Runbook: $($Runbook.BaseName) has changed since last PR." # upload runbook to temp storage account Write-Host -Object "Processing runbook $($Runbook.BaseName)" Write-Host -Object "Uploading runbook: $($Runbook.FullName) to container: $ContainerName in storage account: $StorageAccountName" $RunbookBlob = Set-AzStorageBlobContent -File $Runbook.FullName ` -Container $ContainerName ` -Blob $Runbook.Name ` -Context $Ctx ` -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to upload: $($Runbook.Name) to storage account: $StorageAccountName. Error: $($oErr.Message)" Write-Error -Message "Failed to upload: $($Runbook.Name) to storage account: $StorageAccountName" -ErrorAction Stop } if ($RunbookBlob.BlobClient.Uri.AbsoluteUri) { $RBImport = Import-RuntimeEnvAutomationRunbook -Name $Runbook.BaseName -ContentLink $RunbookBlob.BlobClient.Uri.AbsoluteUri -RunbookType $RunbookType ` -ResourceGroupName $AutomationAccount.ResourceGroupName ` -AutomationAccountName $AutomationAccount.AutomationAccountName ` -RuntimeEnvironmentName $RuntimeEnvironmentName -Location $AutomationAccount.Location ` -ErrorAction Continue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to import Runbook: $($Runbook.BaseName) with error: $($oErr.Message)" $oErr = $Null } # $RBImport = Import-AzAutomationRunbook -Name $Runbook.BaseName -Path $Runbook.FullName -Type $RunbookType ` # -ResourceGroupName $AutomationAccount.ResourceGroupName ` # -AutomationAccountName $AutomationAccount.AutomationAccountName -Force ` # -ErrorAction Continue -ErrorVariable oErr # if ($oErr) { # Write-Host -Object "##vso[task.logissue type=error;]Failed to import Runbook: $($Runbook.BaseName) with error: $($oErr.Message)" # $oErr = $Null # } else { if ($RBImport) { Write-Host -Object "Runbook import result:$($RBImport | Out-String)" -NoNewline if ($RBImport.ProvisioningState -eq "Succeeded") { # No error publish runbook Write-Host -Object "Successfully imported runbook: $($Runbook.BaseName) for environment: $RuntimeEnvironmentName in account: $($AutomationAccount.AutomationAccountName)`n" } } # $RBPublish = Publish-AzAutomationRunbook -Name $Runbook.BaseName -ResourceGroupName $AutomationAccount.ResourceGroupName ` # -AutomationAccountName $AutomationAccount.AutomationAccountName -ErrorAction Continue -ErrorVariable oErr # if ($oErr) { # Write-Host -Object "##vso[task.logissue type=error;]Failed to publish Runbook: $($Runbook.BaseName) with error: $($oErr.Message)" # $oErr = $null # } # else { # if ($RBPublish) { # Write-Host -Object "Runbook publish result:`n$($RBPublish | Out-String)" # } # Write-Host -Object "Successfully published Runbook: $($Runbook.BaseName) to automation account $($AutomationAccount.AutomationAccountName)`n" # } } } else { Write-Error -Message "Runbook: $($Runbook.BaseName) not available in temp storage account" } } else { Write-Host -Object "##vso[task.logissue type=error;]Not a supported Runbook type" } } #endregion } } else { Write-Host -Object "No Runbooks found to publish" } # Write-Host -Object "##[endgroup]" #endregion #region Import Modules to RTE # Write-Host -Object "##[group]Modules" Write-Host -Object "`n-----------------------------------------------" Write-Host -Object " Modules " Write-Host -Object "-----------------------------------------------`n" if ($ModulesPath) { Write-Host -Object "Fetching Modules files from path: $ModulesPath" $Modules = Get-ChildItem $ModulesPath -ErrorAction SilentlyContinue -File -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to retrieve files from pipeline with error: $($oErr.Message)" Write-Error -Message "Failed to retrieve Modules files" -ErrorAction Stop } else { Write-Host -Object "Successfully retrieved Modules files from agent" if ($Modules) { Write-Host -Object "Module files found on agent:`n$($Modules.Name)" } else { Write-Host -Object "No module files found on agent to publish" } } if ($Modules) { $VerbosePreference = "silentlycontinue" $ContainerName = "modules" #region Process modules to upload to RTE foreach ($Module in $Modules) { Write-Host # Needs first to be uploaded to a storage account before importing Write-Host -Object "Processing module $($Module.BaseName)" Write-Host -Object "Uploading file: $($Module.FullName) to container: $ContainerName in storage account: $StorageAccountName" $ModuleBlob = Set-AzStorageBlobContent -File $Module.FullName ` -Container $ContainerName ` -Blob $Module.Name ` -Context $Ctx ` -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to upload module: $($Module.Name) to temp storage account: $StorageAccountName. Error: $($oErr.Message)" Write-Error -Message "Failed to upload module: $($Module.Name) to temp storage account: $StorageAccountName" -ErrorAction Stop } if ($ModuleBlob.BlobClient.Uri.AbsoluteUri) { Write-Host -Object "Publishing module: $($Module.BaseName) for environment: $RuntimeEnvironmentName in account: $($AutomationAccount.AutomationAccountName)" $ModuleImport = Import-RuntimeEnvAutomationModule -Name $Module.BaseName ` -AutomationAccountName $AutomationAccount.AutomationAccountName ` -ResourceGroupName $AutomationAccount.ResourceGroupName ` -RuntimeEnvironmentName $RuntimeEnvironmentName ` -ContentLink $ModuleBlob.BlobClient.Uri.AbsoluteUri -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to import module: $($Module.Name). Error: $($oErr.Message)" Write-Error -Message "Failed to import module: $($Module.Name)" -ErrorAction Stop } else { if ($ModuleImport) { Write-Host -Object "Module import result:$($ModuleImport | Out-String)" -NoNewline } } Write-Host -Object "Pulling module import status" # Pull to check if module import has finished $AutomationModule = Get-RuntimeEnvAutomationModule -Name $Module.BaseName ` -AutomationAccountName $AutomationAccount.AutomationAccountName ` -ResourceGroupName $AutomationAccount.ResourceGroupName ` -RuntimeEnvironmentName $RuntimeEnvironmentName -ErrorAction SilentlyContinue -ErrorVariable oErr $oErr = $null while ( (-not ([string]::IsNullOrEmpty($AutomationModule))) -and $AutomationModule.ProvisioningState -ne "Created" -and $AutomationModule.ProvisioningState -ne "Succeeded" -and $AutomationModule.ProvisioningState -ne "Failed" -and [string]::IsNullOrEmpty($oErr) ) { Start-Sleep -Seconds 5 Write-Verbose -Message "Polling module import status for: $($AutomationModule.Name)" $AutomationModule = Get-RuntimeEnvAutomationModule -Name $Module.BaseName ` -AutomationAccountName $AutomationAccount.AutomationAccountName ` -ResourceGroupName $AutomationAccount.ResourceGroupName ` -RuntimeEnvironmentName $RuntimeEnvironmentName -ErrorAction SilentlyContinue -ErrorVariable oErr if ($oErr) { Write-Error -Message "Error fetching module status for: $($AutomationModule.Name)" -ErrorAction Continue oErr = $null } else { Write-Verbose -Message "Module import pull status: $($AutomationModule.ProvisioningState)" } } if ( ($AutomationModule.ProvisioningState -eq "Failed") -or $oErr ) { Write-Error -Message "Failed to imported module: $($AutomationModule.Name) to Automation account." -ErrorAction Continue Write-Host -Object "Failed to imported module: $($AutomationModule.Name) to Automation account." $oErr = $null } else { Write-Host -Object "Successfully imported module: $($AutomationModule.Name) for environment: $RuntimeEnvironmentName in account: $($AutomationAccount.AutomationAccountName)`n" } # New-AzAutomationModule -Name $Module.BaseName ` # -AutomationAccountName $AutomationAccount.AutomationAccountName ` # -ResourceGroupName $AutomationAccount.ResourceGroupName ` # -ContentLinkUri $ModuleBlob.BlobClient.Uri.AbsoluteUri -ErrorAction SilentlyContinue -ErrorVariable oErr # if ($oErr) { # Write-Host -Object "##vso[task.logissue type=error;]Failed to import module: $($Module.Name). Error: $($oErr.Message)" # Write-Error -Message "Failed to import module: $($Module.Name)" -ErrorAction Stop # } # $AutomationModule = Get-AzAutomationModule -Name $Module.BaseName ` # -AutomationAccountName $AutomationAccount.AutomationAccountName ` # -ResourceGroupName $AutomationAccount.ResourceGroupName # $oErr = $null # while ( # (-not ([string]::IsNullOrEmpty($AutomationModule))) -and # $AutomationModule.ProvisioningState -ne "Created" -and # $AutomationModule.ProvisioningState -ne "Succeeded" -and # $AutomationModule.ProvisioningState -ne "Failed" -and # [string]::IsNullOrEmpty($oErr) # ) { # Start-Sleep -Seconds 5 # Write-Verbose -Message "Polling module import status for: $($AutomationModule.Name)" # $AutomationModule = $AutomationModule | Get-AzAutomationModule -ErrorAction silentlycontinue -ErrorVariable oErr # if ($oErr) { # Write-Error -Message "Error fetching module status for: $($AutomationModule.Name)" -ErrorAction Continue # } # else { # Write-Verbose -Message "Module import pull status: $($AutomationModule.ProvisioningState)" # } # } # if ( ($AutomationModule.ProvisioningState -eq "Failed") -or $oErr ) { # Write-Error -Message "Import of $($AutomationModule.Name) module to Automation account failed." -ErrorAction Continue # Write-Output -InputObject "Import of $($AutomationModule.Name) module to Automation account failed." # $oErr = $null # } # else { # Write-Output -InputObject "Import of: $($AutomationModule.Name) module to Automation account succeeded.`n" # } } else { Write-Error -Message "Module: $($Module.BaseName) not available in temp storage account" } } #endregion } } else { Write-Host -Object "No Modules found to publish" } # Write-Host -Object "##[endgroup]" #endregion } catch { $ErrorTriggered = $true if ($_.Exception.Message) { Write-Host -Object "##vso[task.logissue type=error;]$($_.Exception.Message)" Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue } else { Write-Host -Object "##vso[task.logissue type=error;]$($_.Exception)" Write-Error -Message "$($_.Exception)" -ErrorAction Continue } } finally { Write-Host -Object "`n-----------------------------------------------" Write-Host -Object " End " Write-Host -Object "-----------------------------------------------" #region Remove temp azure storage account $oErr = $null if($Ctx) { Write-Host -Object "Removing temp storage account: $StorageAccountName" Remove-AzStorageAccount -ResourceGroupName $AutomationAccount.ResourceGroupName ` -Name $StorageAccountName ` -Force ` -ErrorAction silentlycontinue -ErrorVariable oErr if ($oErr) { Write-Host -Object "##vso[task.logissue type=error;]Failed to remove storage account: $StorageAccountName" Write-Error -Message "Failed to remove storage account: $StorageAccountName" -ErrorAction Continue $oErr = $null } } #endregion Write-Host -Object "Termination error detected: $ErrorTriggered" Write-Host -Object "Number of errors detected: $($Error.Count)" # if error fail azdevops pipeline if( ($Error.Count -gt 0) -or $ErrorTriggered) { Write-Host "##vso[task.logissue type=error]Error detected, failing pipeline run" Write-Host "##vso[task.complete result=Failed]" } else { Write-Host -Object "##vso[task.complete result=Succeeded;]Runbook(s)/Module(s) import successful" } Write-Host -Object "Task ended at time: $(Get-Date -Format r)" } |
Happy tinkering!