From a721e4badcf614354f3a0b4c050012ec6fb47be9 Mon Sep 17 00:00:00 2001 From: Nik Charlebois Date: Mon, 11 Nov 2024 11:03:51 -0500 Subject: [PATCH 1/2] AzureBillingAccountPolicy - Initial Release --- CHANGELOG.md | 5 + .../MSFT_AzureBillingAccountPolicy.psm1 | 475 ++++++++++++++++++ .../MSFT_AzureBillingAccountPolicy.schema.mof | 25 + .../MSFT_AzureBillingAccountPolicy/readme.md | 6 + .../settings.json | 20 + ...FT_AzureBillingAccountScheduledAction.psm1 | 2 +- .../AzureBillingAccountPolicy/2-Update.ps1 | 39 ++ ...365DSC.AzureBillingAccountPolicy.Tests.ps1 | 186 +++++++ 8 files changed, 757 insertions(+), 1 deletion(-) create mode 100644 Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 create mode 100644 Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.schema.mof create mode 100644 Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/readme.md create mode 100644 Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/settings.json create mode 100644 Modules/Microsoft365DSC/Examples/Resources/AzureBillingAccountPolicy/2-Update.ps1 create mode 100644 Tests/Unit/Microsoft365DSC/Microsoft365DSC.AzureBillingAccountPolicy.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 6845ab5c9e..147673142d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Change log for Microsoft365DSC +# UNRELEASED + +* AzureBillingAccountPolicy + * Initial release. + # 1.24.1106.3 * AzureBillingAccountScheduledAction diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 new file mode 100644 index 0000000000..2066157785 --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 @@ -0,0 +1,475 @@ +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $BillingAccount, + + [Parameter()] + [Microsoft.Management.Infrastructure.CimInstance] + $EnterpriseAgreementPolicies, + + [Parameter()] + [System.String] + $MarketplacePurchases, + + [Parameter()] + [System.String] + $ReservationPurchases, + + [Parameter()] + [System.String] + $SavingsPlanPurchases, + + [Parameter()] + [System.String] + $Name, + + [Parameter()] + [ValidateSet('Present', 'Absent')] + [System.String] + $Ensure = 'Present', + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + New-M365DSCConnection -Workload 'Azure' ` + -InboundParameters $PSBoundParameters | Out-Null + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $nullResult = $PSBoundParameters + $nullResult.Ensure = 'Absent' + try + { + $uri = "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($BillingAccount)/policies/default?api-version=2024-04-01" + $response = Invoke-AzRest -Uri $uri -Method GET + $instance = (ConvertFrom-Json ($response.Content)).value + + if ($null -eq $instance) + { + return $nullResult + } + + $EnterpriseAgreementPoliciesValue = $null + if ($null -ne $EnterpriseAgreementPolicies) + { + $EnterpriseAgreementPoliciesValue = @{ + accountOwnerViewCharges = $instance.properties.enterpriseAgreementPolicies.accountOwnerViewCharges + authenticationType = $instance.properties.enterpriseAgreementPolicies.authenticationType + departmentAdminViewCharges = $instance.properties.enterpriseAgreementPolicies.departmentAdminViewCharges + } + } + + $results = @{ + BillingAccount = $BillingAccount + Name = $instance.name + EnterpriseAgreementPolicies = $EnterpriseAgreementPoliciesValue + MarketplacePurchases = $instance.properties.marketplacePurchases + ReservationPurchases = $instance.properties.reservationPurchases + SavingsPlanPurchases = $instance.properties.savingsPlanPurchases + Ensure = 'Present' + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + ManagedIdentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens + } + return [System.Collections.Hashtable] $results + } + catch + { + Write-Verbose -Message $_ + New-M365DSCLogEntry -Message 'Error retrieving data:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + + return $nullResult + } +} + +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $BillingAccount, + + [Parameter()] + [Microsoft.Management.Infrastructure.CimInstance] + $EnterpriseAgreementPolicies, + + [Parameter()] + [System.String] + $MarketplacePurchases, + + [Parameter()] + [System.String] + $ReservationPurchases, + + [Parameter()] + [System.String] + $SavingsPlanPurchases, + + [Parameter()] + [System.String] + $Name, + + [Parameter()] + [ValidateSet('Present', 'Absent')] + [System.String] + $Ensure = 'Present', + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + New-M365DSCConnection -Workload 'Azure' ` + -InboundParameters $PSBoundParameters | Out-Null + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $instanceParams = @{ + properties = @{ + enterpriseAgreementPolicies = @{ + accountOwnerViewCharges = $EnterpriseAgreementPolicies.accountOwnerViewCharges + authenticationType = $EnterpriseAgreementPolicies.authenticationType + departmentAdminViewCharges = $EnterpriseAgreementPolicies.departmentAdminViewCharges + } + marketplacePurchases = $MarketplacePurchases + reservationPurchases = $ReservationPurchases + savingsPlanPurchases = $SavingsPlanPurchases + } + } + $payload = ConvertTo-Json $instanceParams -Depth 5 -Compress + Write-Verbose -Message "Updating billing account policy for {$BillingAccount} with payload:`r`n$($payload)" + $uri = "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($BillingAccount)/policies/default?api-version=2024-04-01" + $response = Invoke-AzRest -Uri $uri -Method "PUT" -Payload $payload + Write-Verbose -Message "Response:`r`n$($response.Content)" +} + +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $BillingAccount, + + [Parameter()] + [Microsoft.Management.Infrastructure.CimInstance] + $EnterpriseAgreementPolicies, + + [Parameter()] + [System.String] + $MarketplacePurchases, + + [Parameter()] + [System.String] + $ReservationPurchases, + + [Parameter()] + [System.String] + $SavingsPlanPurchases, + + [Parameter()] + [System.String] + $Name, + + [Parameter()] + [ValidateSet('Present', 'Absent')] + [System.String] + $Ensure = 'Present', + + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + $CurrentValues = Get-TargetResource @PSBoundParameters + $ValuesToCheck = ([Hashtable]$PSBoundParameters).Clone() + + Write-Verbose -Message "Current Values: $(Convert-M365DscHashtableToString -Hashtable $CurrentValues)" + Write-Verbose -Message "Target Values: $(Convert-M365DscHashtableToString -Hashtable $ValuesToCheck)" + $testResult = $true + + #Compare Cim instances + foreach ($key in $PSBoundParameters.Keys) + { + $source = $PSBoundParameters.$key + $target = $CurrentValues.$key + if ($source.getType().Name -like '*CimInstance*') + { + $testResult = Compare-M365DSCComplexObject ` + -Source ($source) ` + -Target ($target) + + if (-Not $testResult) + { + $testResult = $false + break + } + + $ValuesToCheck.Remove($key) | Out-Null + } + } + + if ($testResult) + { + $testResult = Test-M365DSCParameterState -CurrentValues $CurrentValues ` + -Source $($MyInvocation.MyCommand.Source) ` + -DesiredValues $PSBoundParameters ` + -ValuesToCheck $ValuesToCheck.Keys + } + + Write-Verbose -Message "Test-TargetResource returned $testResult" + + return $testResult +} + +function Export-TargetResource +{ + [CmdletBinding()] + [OutputType([System.String])] + param + ( + [Parameter()] + [System.Management.Automation.PSCredential] + $Credential, + + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ApplicationSecret, + + [Parameter()] + [System.String] + $CertificateThumbprint, + + [Parameter()] + [Switch] + $ManagedIdentity, + + [Parameter()] + [System.String[]] + $AccessTokens + ) + + $ConnectionMode = New-M365DSCConnection -Workload 'Azure' ` + -InboundParameters $PSBoundParameters + + #Ensure the proper dependencies are installed in the current environment. + Confirm-M365DSCDependencies + + #region Telemetry + $ResourceName = $MyInvocation.MyCommand.ModuleName.Replace('MSFT_', '') + $CommandName = $MyInvocation.MyCommand + $data = Format-M365DSCTelemetryParameters -ResourceName $ResourceName ` + -CommandName $CommandName ` + -Parameters $PSBoundParameters + Add-M365DSCTelemetryEvent -Data $data + #endregion + + try + { + $Script:ExportMode = $true + + #Get all billing account + $accounts = Get-M365DSCAzureBillingAccount + + $i = 1 + $dscContent = '' + if ($accounts.Length -eq 0) + { + Write-Host $Global:M365DSCEmojiGreenCheckMark + } + else + { + Write-Host "`r`n" -NoNewline + } + foreach ($account in $accounts.value) + { + $displayedKey = $account.properties.displayName + Write-Host " |---[$i/$($accounts.value.Length)] $displayedKey" -NoNewline + + if ($null -ne $Global:M365DSCExportResourceInstancesCount) + { + $Global:M365DSCExportResourceInstancesCount++ + } + $params = @{ + BillingAccount = $account.name + Credential = $Credential + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + ManagedIdentity = $ManagedIdentity.IsPresent + AccessTokens = $AccessTokens + } + + $Results = Get-TargetResource @Params + $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` + -Results $Results + + + if ($Results.EnterpriseAgreementPolicies) + { + $complexTypeStringResult = Get-M365DSCDRGComplexTypeToString -ComplexObject $Results.EnterpriseAgreementPolicies -CIMInstanceName AzureBillingAccountPolicyEnterpriseAgreementPolicy + if ($complexTypeStringResult) + { + $Results.EnterpriseAgreementPolicies = $complexTypeStringResult + } + else + { + $Results.Remove('EnterpriseAgreementPolicies') | Out-Null + } + } + $currentDSCBlock = Get-M365DSCExportContentForResource -ResourceName $ResourceName ` + -ConnectionMode $ConnectionMode ` + -ModulePath $PSScriptRoot ` + -Results $Results ` + -Credential $Credential + + if ($Results.EnterpriseAgreementPolicies) + { + $isCIMArray = $false + if ($Results.EnterpriseAgreementPolicies.getType().Fullname -like '*[[\]]') + { + $isCIMArray = $true + } + $currentDSCBlock = Convert-DSCStringParamToVariable -DSCBlock $currentDSCBlock -ParameterName 'EnterpriseAgreementPolicies' -IsCIMArray:$isCIMArray + } + $dscContent += $currentDSCBlock + Save-M365DSCPartialExport -Content $currentDSCBlock ` + -FileName $Global:PartialExportFileName + $i++ + Write-Host $Global:M365DSCEmojiGreenCheckMark + } + return $dscContent + } + catch + { + Write-Host $Global:M365DSCEmojiRedX + + New-M365DSCLogEntry -Message 'Error during Export:' ` + -Exception $_ ` + -Source $($MyInvocation.MyCommand.Source) ` + -TenantId $TenantId ` + -Credential $Credential + + return '' + } +} + +Export-ModuleMember -Function *-TargetResource diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.schema.mof b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.schema.mof new file mode 100644 index 0000000000..5b68ca919e --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.schema.mof @@ -0,0 +1,25 @@ +[ClassVersion("1.0.0.0")] +class MSFT_AzureBillingAccountPolicyEnterpriseAgreementPolicy +{ + [Write, Description("The policy that controls whether account owner can view charges.")] String accountOwnerViewCharges; + [Write, Description("The state showing the enrollment auth level.")] String authenticationType; + [Write, Description("The policy that controls whether department admin can view charges.")] String departmentAdminViewCharges; +}; +[ClassVersion("1.0.0.0"), FriendlyName("AzureBillingAccountPolicy")] +class MSFT_AzureBillingAccountPolicy : OMI_BaseResource +{ + [Key, Description("Unique identifier of the associated billing account.")] String BillingAccount; + [Write, Description("Name of the policy.")] String Name; + [Write, Description("The policies for Enterprise Agreement enrollments."), EmbeddedInstance("MSFT_AzureBillingAccountPolicyEnterpriseAgreementPolicy")] String EnterpriseAgreementPolicies; + [Write, Description("The policy that controls whether Azure marketplace purchases are allowed.")] String MarketplacePurchases; + [Write, Description("The policy that controls whether Azure reservation purchases are allowed.")] String ReservationPurchases; + [Write, Description("The policy that controls whether users with Azure savings plan purchase are allowed.")] String SavingsPlanPurchases; + + [Write, Description("Present ensures the instance exists, absent ensures it is removed."), ValueMap{"Absent","Present"}, Values{"Absent","Present"}] string Ensure; + [Write, Description("Credentials of the workload's Admin"), EmbeddedInstance("MSFT_Credential")] string Credential; + [Write, Description("Id of the Azure Active Directory application to authenticate with.")] String ApplicationId; + [Write, Description("Id of the Azure Active Directory tenant used for authentication.")] String TenantId; + [Write, Description("Thumbprint of the Azure Active Directory application's authentication certificate to use for authentication.")] String CertificateThumbprint; + [Write, Description("Managed ID being used for authentication.")] Boolean ManagedIdentity; + [Write, Description("Access token used for authentication.")] String AccessTokens[]; +}; diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/readme.md b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/readme.md new file mode 100644 index 0000000000..8432d3040a --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/readme.md @@ -0,0 +1,6 @@ + +# AzureBillingAccountPolicy + +## Description + +Configures policies settings for an Azure billing account. diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/settings.json b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/settings.json new file mode 100644 index 0000000000..2be977460b --- /dev/null +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/settings.json @@ -0,0 +1,20 @@ +{ + "resourceName": "AzureBillingAccountPolicy", + "description": "Configures policies settings for an Azure billing account.", + "roles": { + "read": [], + "update": [] + }, + "permissions": { + "graph": { + "delegated": { + "read": [], + "update": [] + }, + "application": { + "read": [], + "update": [] + } + } + } +} diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountScheduledAction/MSFT_AzureBillingAccountScheduledAction.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountScheduledAction/MSFT_AzureBillingAccountScheduledAction.psm1 index e6b49c0e6f..5eff8056b5 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountScheduledAction/MSFT_AzureBillingAccountScheduledAction.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountScheduledAction/MSFT_AzureBillingAccountScheduledAction.psm1 @@ -81,7 +81,7 @@ function Get-TargetResource $nullResult.Ensure = 'Absent' try { - $uri = "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($account.name)/providers/Microsoft.CostManagement/scheduledActions?api-version=2023-11-01" + $uri = "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($BillingAccount)/providers/Microsoft.CostManagement/scheduledActions?api-version=2023-11-01" $response = Invoke-AzRest -Uri $uri -Method GET $actions = (ConvertFrom-Json ($response.Content)).value diff --git a/Modules/Microsoft365DSC/Examples/Resources/AzureBillingAccountPolicy/2-Update.ps1 b/Modules/Microsoft365DSC/Examples/Resources/AzureBillingAccountPolicy/2-Update.ps1 new file mode 100644 index 0000000000..4bedeb545c --- /dev/null +++ b/Modules/Microsoft365DSC/Examples/Resources/AzureBillingAccountPolicy/2-Update.ps1 @@ -0,0 +1,39 @@ +<# +This example is used to test new resources and showcase the usage of new resources being worked on. +It is not meant to use as a production baseline. +#> + +Configuration Example +{ + param( + [Parameter()] + [System.String] + $ApplicationId, + + [Parameter()] + [System.String] + $TenantId, + + [Parameter()] + [System.String] + $CertificateThumbprint + ) + Import-DscResource -ModuleName Microsoft365DSC + node localhost + { + AzureBillingAccountPolicy "MyBillingAccountPolicy" + { + BillingAccount = "1e5b9e50-a1ea-581e-fb3a-xxxxxxxxx:6487d5cf-0a7b-42e6-9549-xxxxxxx_2019-05-31"; + Name = "default" + ApplicationId = $ApplicationId + TenantId = $TenantId + CertificateThumbprint = $CertificateThumbprint + EnterpriseAgreementPolicies = MSFT_AzureBillingAccountPolicyEnterpriseAgreementPolicy { + authenticationType = "OrganizationalAccountOnly" + } + MarketplacePurchases = "AllAllowed" + ReservationPurchases = "Allowed" + SavingsPlanPurchases = "NotAllowed" + } + } +} diff --git a/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AzureBillingAccountPolicy.Tests.ps1 b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AzureBillingAccountPolicy.Tests.ps1 new file mode 100644 index 0000000000..1aaf278223 --- /dev/null +++ b/Tests/Unit/Microsoft365DSC/Microsoft365DSC.AzureBillingAccountPolicy.Tests.ps1 @@ -0,0 +1,186 @@ +[CmdletBinding()] +param( +) +$M365DSCTestFolder = Join-Path -Path $PSScriptRoot ` + -ChildPath '..\..\Unit' ` + -Resolve +$CmdletModule = (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\Stubs\Microsoft365.psm1' ` + -Resolve) +$GenericStubPath = (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\Stubs\Generic.psm1' ` + -Resolve) +Import-Module -Name (Join-Path -Path $M365DSCTestFolder ` + -ChildPath '\UnitTestHelper.psm1' ` + -Resolve) + +$CurrentScriptPath = $PSCommandPath.Split('\') +$CurrentScriptName = $CurrentScriptPath[$CurrentScriptPath.Length -1] +$ResourceName = $CurrentScriptName.Split('.')[1] +$Global:DscHelper = New-M365DscUnitTestHelper -StubModule $CmdletModule ` + -DscResource $ResourceName -GenericStubModule $GenericStubPath + +Describe -Name $Global:DscHelper.DescribeHeader -Fixture { + InModuleScope -ModuleName $Global:DscHelper.ModuleName -ScriptBlock { + Invoke-Command -ScriptBlock $Global:DscHelper.InitializeScript -NoNewScope + BeforeAll { + + $secpasswd = ConvertTo-SecureString (New-Guid | Out-String) -AsPlainText -Force + $Credential = New-Object System.Management.Automation.PSCredential ('tenantadmin@mydomain.com', $secpasswd) + + Mock -CommandName Confirm-M365DSCDependencies -MockWith { + } + + Mock -CommandName New-M365DSCConnection -MockWith { + return "Credentials" + } + + Mock -CommandName Get-M365DSCAzureBillingAccount -MockWith { + return @{ + value = @{ + name = "1e5b9e50-a1ea-581e-fb3a-xxxxxxxxx:6487d5cf-0a7b-42e6-9549-xxxxxxx_2019-05-31" + properties = @{ + displayName = "MyBillingAccount" + } + } + } + } + + # Mock Write-Host to hide output during the tests + Mock -CommandName Write-Host -MockWith { + } + $Script:exportedInstances =$null + $Script:ExportMode = $false + } + # Test contexts + Context -Name "The instance exists and values are already in the desired state" -Fixture { + BeforeAll { + $testParams = @{ + BillingAccount = "1e5b9e50-a1ea-581e-fb3a-xxxxxxxxx:6487d5cf-0a7b-42e6-9549-xxxxxxx_2019-05-31"; + Name = "default" + EnterpriseAgreementPolicies = (New-CimInstance -ClassName MSFT_AzureBillingAccountPolicyEnterpriseAgreementPolicy -Property @{ + authenticationType = "OrganizationalAccountOnly" + } -ClientOnly) + MarketplacePurchases = "AllAllowed" + ReservationPurchases = "Allowed" + SavingsPlanPurchases = "NotAllowed" + Ensure = 'Present' + Credential = $Credential; + } + + Mock -CommandName Invoke-AzRest -MockWith { + return @{ + Content = ConvertTo-Json @{ + value = @( + @{ + name = "default" + id = "12345-12345-12345-12345-12345" + properties = @{ + enterpriseAgreementPolicies = @{ + authenticationType = "OrganizationalAccountOnly" + } + marketplacePurchases = "AllAllowed" + reservationPurchases = "Allowed" + savingsPlanPurchases = "NotAllowed" + } + } + ) + } -Dept 10 -Compress + } + } + } + + It 'Should return true from the Test method' { + Test-TargetResource @testParams | Should -Be $true + } + } + + Context -Name "The instance exists and values are NOT in the desired state" -Fixture { + BeforeAll { + $testParams = @{ + BillingAccount = "1e5b9e50-a1ea-581e-fb3a-xxxxxxxxx:6487d5cf-0a7b-42e6-9549-xxxxxxx_2019-05-31"; + Name = "default" + EnterpriseAgreementPolicies = (New-CimInstance -ClassName MSFT_AzureBillingAccountPolicyEnterpriseAgreementPolicy -Property @{ + authenticationType = "OrganizationalAccountOnly" + } -ClientOnly) + MarketplacePurchases = "AllAllowed" + ReservationPurchases = "Allowed" + SavingsPlanPurchases = "Allowed" #Drift + Ensure = 'Present' + Credential = $Credential; + } + + Mock -CommandName Invoke-AzRest -MockWith { + return @{ + Content = ConvertTo-Json @{ + value = @( + @{ + name = "default" + id = "12345-12345-12345-12345-12345" + properties = @{ + enterpriseAgreementPolicies = @{ + authenticationType = "OrganizationalAccountOnly" + } + marketplacePurchases = "AllAllowed" + reservationPurchases = "Allowed" + savingsPlanPurchases = "NotAllowed" + } + } + ) + } -Dept 10 -Compress + } + } + } + + It 'Should return Values from the Get method' { + (Get-TargetResource @testParams).Ensure | Should -Be 'Present' + } + + It 'Should return false from the Test method' { + Test-TargetResource @testParams | Should -Be $false + } + + It 'Should call the Set method' { + Set-TargetResource @testParams + Should -Invoke -CommandName Invoke-AzRest -Exactly 1 + } + } + + Context -Name 'ReverseDSC Tests' -Fixture { + BeforeAll { + $Global:CurrentModeIsExport = $true + $Global:PartialExportFileName = "$(New-Guid).partial.ps1" + $testParams = @{ + Credential = $Credential; + } + + Mock -CommandName Invoke-AzRest -MockWith { + return @{ + Content = ConvertTo-Json @{ + value = @( + @{ + name = "default" + id = "12345-12345-12345-12345-12345" + properties = @{ + enterpriseAgreementPolicies = @{ + authenticationType = "OrganizationalAccountOnly" + } + marketplacePurchases = "AllAllowed" + reservationPurchases = "Allowed" + savingsPlanPurchases = "NotAllowed" + } + } + ) + } -Dept 10 -Compress + } + } + } + It 'Should Reverse Engineer resource from the Export method' { + $result = Export-TargetResource @testParams + $result | Should -Not -BeNullOrEmpty + } + } + } +} + +Invoke-Command -ScriptBlock $Global:DscHelper.CleanupScript -NoNewScope From 3f43bad769a10f43c08e077c68f790e80f3b00c0 Mon Sep 17 00:00:00 2001 From: Nik Charlebois Date: Wed, 13 Nov 2024 07:32:34 -0500 Subject: [PATCH 2/2] Update MSFT_AzureBillingAccountPolicy.psm1 --- .../MSFT_AzureBillingAccountPolicy.psm1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 index 2066157785..8b9275b11f 100644 --- a/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 +++ b/Modules/Microsoft365DSC/DSCResources/MSFT_AzureBillingAccountPolicy/MSFT_AzureBillingAccountPolicy.psm1 @@ -216,6 +216,10 @@ function Set-TargetResource Write-Verbose -Message "Updating billing account policy for {$BillingAccount} with payload:`r`n$($payload)" $uri = "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/$($BillingAccount)/policies/default?api-version=2024-04-01" $response = Invoke-AzRest -Uri $uri -Method "PUT" -Payload $payload + if (-not [System.String]::IsNullOrEmpty($response.Error)) + { + throw "Error: $($response.Error)" + } Write-Verbose -Message "Response:`r`n$($response.Content)" } @@ -422,7 +426,6 @@ function Export-TargetResource $Results = Update-M365DSCExportAuthenticationResults -ConnectionMode $ConnectionMode ` -Results $Results - if ($Results.EnterpriseAgreementPolicies) { $complexTypeStringResult = Get-M365DSCDRGComplexTypeToString -ComplexObject $Results.EnterpriseAgreementPolicies -CIMInstanceName AzureBillingAccountPolicyEnterpriseAgreementPolicy