diff --git a/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToEnvironment.ps1 b/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToEnvironment.ps1 index 56ae55f2..3a5bf57b 100644 --- a/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToEnvironment.ps1 +++ b/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToEnvironment.ps1 @@ -1,27 +1,33 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function AddCustomerManagedKeyToEnvironment +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) { - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - LinkPolicyToEnv -policyType cmk -environmentId $environmentId -policyArmId $policyArmId -endpoint $endpoint + return } -AddCustomerManagedKeyToEnvironment \ No newline at end of file + +New-PolicyToEnvLink -PolicyType [PolicyType]::Encryption -EnvironmentId $EnvironmentId -PolicyArmId $PolicyArmId -Endpoint $Endpoint \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToPlatformAppsData.ps1 b/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToPlatformAppsData.ps1 index 9dc6f8ec..76031ae7 100644 --- a/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToPlatformAppsData.ps1 +++ b/powershell/enterprisePolicies/Cmk/AddCustomerManagedKeyToPlatformAppsData.ps1 @@ -1,18 +1,19 @@ param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] - [String]$policyArmId, + [String]$PolicyArmId, [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint + [BAPEndpoint]$Endpoint = "prod" ) -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" +$ErrorActionPreference = "Stop" -if (![bool]$endpoint) { - $endpoint = "prod" +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return } -LinkPolicyToPlatformAppsData -policyType cmk -policyArmId $policyArmId -endpoint $endpoint +New-PolicyToPlatformAppsDataLink -PolicyType [PolicyType]::Encryption -PolicyArmId $PolicyArmId -Endpoint $Endpoint diff --git a/powershell/enterprisePolicies/Cmk/CreateCMKEnterprisePolicy.ps1 b/powershell/enterprisePolicies/Cmk/CreateCMKEnterprisePolicy.ps1 index 160bdc9a..94845fb0 100644 --- a/powershell/enterprisePolicies/Cmk/CreateCMKEnterprisePolicy.ps1 +++ b/powershell/enterprisePolicies/Cmk/CreateCMKEnterprisePolicy.ps1 @@ -1,81 +1,60 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function CreateCMKEnterprisePolicy -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy subscription" - )] - [string]$subscriptionId, +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> - [Parameter( - Mandatory=$true, - HelpMessage="The Policy resource group" - )] - [string]$resourceGroup, +param( + [Parameter(Mandatory, HelpMessage="The Policy subscription")] + [string]$subscriptionId, - [Parameter( - Mandatory=$true, - HelpMessage="The Policy name" - )] - [string]$enterprisePolicyName, + [Parameter(Mandatory, HelpMessage="The Policy resource group")] + [string]$resourceGroup, - [Parameter( - Mandatory=$true, - HelpMessage="The Policy location" - )] - [string]$enterprisePolicyLocation, + [Parameter(Mandatory, HelpMessage="The Policy name")] + [string]$enterprisePolicyName, - [Parameter( - Mandatory=$true, - HelpMessage="The KeyVault ARM Id" - )] - [string]$keyVaultId, + [Parameter(Mandatory, HelpMessage="The Policy location")] + [string]$enterprisePolicyLocation, - [Parameter( - Mandatory=$true, - HelpMessage="The Key name" - )] - [string]$keyName, + [Parameter(Mandatory, HelpMessage="The KeyVault ARM Id")] + [string]$keyVaultId, - [Parameter( - Mandatory=$true, - HelpMessage="The Key version" - )] - [string]$keyVersion + [Parameter(Mandatory, HelpMessage="The Key name")] + [string]$keyName, - ) + [Parameter(Mandatory, HelpMessage="The Key version")] + [string]$keyVersion +) - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } +$ErrorActionPreference = "Stop" - Write-Host "Logged In..." -ForegroundColor Green +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force - if ($keyVersion -eq "N/A") - { - $keyVersion = $null - } - - $body = GenerateEnterprisePolicyBody -policyType "cmk" -policyLocation $enterprisePolicyLocation -policyName $enterprisePolicyName -keyVaultId $keyVaultId -keyName $keyName -keyVersion $keyVersion +if (-not(Connect-Azure)) +{ + return +} - $result = PutEnterprisePolicy $resourceGroup $body - if ($result -eq $false) - { - return - } - Write-Host "CMK Enterprise policy created" -ForegroundColor Green +if ($keyVersion -eq "N/A") +{ + $keyVersion = $null +} - $policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" - $policy = GetEnterprisePolicy $policyArmId - $policyString = $policy | ConvertTo-Json -Depth 7 - Write-Host "Policy created" - Write-Host $policyString +$body = New-EnterprisePolicyBody -PolicyType [PolicyType]::Encryption -PolicyLocation $enterprisePolicyLocation -PolicyName $enterprisePolicyName -KeyVaultId $keyVaultId -KeyName $keyName -KeyVersion $keyVersion +$result = Set-EnterprisePolicy -ResourceGroup $resourceGroup -Body $body +if ($result -eq $false) +{ + return } -CreateCMKEnterprisePolicy \ No newline at end of file +Write-Host "CMK Enterprise policy created" -ForegroundColor Green + +$policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" +$policy = Get-EnterprisePolicy -PolicyArmId $policyArmId +$policyString = $policy | ConvertTo-Json -Depth 7 +Write-Host "Policy created" +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInResourceGroup.ps1 b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInResourceGroup.ps1 index 6dd02d34..5787b7d7 100644 --- a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInResourceGroup.ps1 +++ b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInResourceGroup.ps1 @@ -1,32 +1,28 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function GetCMKEnterprisePoliciesInResourceGroup -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The subscriptionId" - )] - [string]$subscriptionId, +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The subscriptionId")] + [string]$subscriptionId, - [Parameter( - Mandatory=$true, - HelpMessage="The resource group" - )] - [string]$resourceGroup - ) + [Parameter(Mandatory, HelpMessage="The resource group")] + [string]$resourceGroup +) - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } +$ErrorActionPreference = "Stop" - Write-Host "Logged In..." -ForegroundColor Green - $cmkPolicies = GetEnterprisePoliciesInResourceGroup $subscriptionId "Encryption" $resourceGroup - $cmkPolicies | Select-Object -Property ResourceId, Location, Name +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force +if (-not(Connect-Azure)) +{ + return } -GetCMKEnterprisePoliciesInResourceGroup \ No newline at end of file + +$cmkPolicies = Get-EnterprisePoliciesInResourceGroup -SubscriptionId $subscriptionId -PolicyType [PolicyType]::Encryption -ResourceGroup $resourceGroup +$cmkPolicies | Select-Object -Property ResourceId, Location, Name \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInSubscription.ps1 b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInSubscription.ps1 index c5b11112..8095142f 100644 --- a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInSubscription.ps1 +++ b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePoliciesInSubscription.ps1 @@ -1,26 +1,25 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function GetCMKEnterprisePoliciesInSubscription -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The subscriptionId" - )] - [string]$subscriptionId - ) +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The subscriptionId")] + [string]$SubscriptionId +) - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } +$ErrorActionPreference = "Stop" - Write-Host "Logged In..." -ForegroundColor Green - $cmkPolicies = GetEnterprisePoliciesInSubscription $subscriptionId "Encryption" - $cmkPolicies | Select-Object -Property ResourceId, Location, Name +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force +if (-not(Connect-Azure)) +{ + return } -GetCMKEnterprisePoliciesInSubscription \ No newline at end of file + +$cmkPolicies = Get-EnterprisePoliciesInSubscription -SubscriptionId $SubscriptionId -PolicyType [PolicyType]::Encryption +$cmkPolicies | Select-Object -Property ResourceId, Location, Name \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyByResourceId.ps1 b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyByResourceId.ps1 index add49bee..869d1135 100644 --- a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyByResourceId.ps1 +++ b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyByResourceId.ps1 @@ -1,28 +1,26 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function GetCMKEnterprisePolicyByResourceId -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy Id" - )] - [string]$enterprisePolicyArmId - ) +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } +param( + [Parameter(Mandatory, HelpMessage="The Policy Id")] + [string]$EnterprisePolicyArmId +) - Write-Host "Logged In..." -ForegroundColor Green +$ErrorActionPreference = "Stop" - $policy = GetEnterprisePolicy $enterprisePolicyArmId - $policyString = $policy | ConvertTo-Json -Depth 7 - Write-Host $policyString +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force +if (-not(Connect-Azure)) +{ + return } -GetCMKEnterprisePolicyByResourceId \ No newline at end of file + +$policy = Get-EnterprisePolicy -PolicyArmId $EnterprisePolicyArmId +$policyString = $policy | ConvertTo-Json -Depth 7 +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyForEnvironment.ps1 b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyForEnvironment.ps1 index b3aea011..0bf4868f 100644 --- a/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyForEnvironment.ps1 +++ b/powershell/enterprisePolicies/Cmk/GetCMKEnterprisePolicyForEnvironment.ps1 @@ -1,23 +1,28 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function GetCMKEnterprisePolicyForEnvironment -{ - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" +) - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint +$ErrorActionPreference = "Stop" - ) +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force - if (![bool]$endpoint) { - $endpoint = "prod" - } - - GetEnterprisePolicyForEnvironment -policyType cmk -environmentId $environmentId -endpoint $endpoint +if (-not(Connect-Azure)) +{ + return } -GetCMKEnterprisePolicyForEnvironment \ No newline at end of file + +Get-EnterprisePolicyForEnvironment -PolicyType [PolicyType]::Encryption -EnvironmentId $EnvironmentId -Endpoint $Endpoint \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/RemoveCMKEnterprisePolicy.ps1 b/powershell/enterprisePolicies/Cmk/RemoveCMKEnterprisePolicy.ps1 index 0587cac0..932eac04 100644 --- a/powershell/enterprisePolicies/Cmk/RemoveCMKEnterprisePolicy.ps1 +++ b/powershell/enterprisePolicies/Cmk/RemoveCMKEnterprisePolicy.ps1 @@ -1,31 +1,30 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function RemoveCMKEnterprisePolicy -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy Id" - )] - [string]$policyArmId - ) +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The Policy Id")] + [string]$PolicyArmId +) + +$ErrorActionPreference = "Stop" - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force - Write-Host "Logged In..." -ForegroundColor Green +if (-not(Connect-Azure)) +{ + return +} - $policy = RemoveEnterprisePolicy $policyArmId - if ($policy -eq "true") - { - Write-Host "Policy removed" -ForegroundColor Green - return - } - Write-Host "Policy not removed" -ForegroundColor Red +$policy = Remove-EnterprisePolicy -PolicyArmId $PolicyArmId +if ($policy -eq "true") +{ + Write-Host "Policy removed" -ForegroundColor Green + return } -RemoveCMKEnterprisePolicy \ No newline at end of file +Write-Host "Policy not removed" -ForegroundColor Red \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromEnvironment.ps1 b/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromEnvironment.ps1 index cb3b8e94..b108d44f 100644 --- a/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromEnvironment.ps1 +++ b/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromEnvironment.ps1 @@ -1,27 +1,32 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function RemoveCustomerManagedKeyFromEnvironment +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$environmentId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$policyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) { - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - UnLinkPolicyFromEnv -policyType cmk -environmentId $environmentId -policyArmId $policyArmId -endpoint $endpoint + return } -RemoveCustomerManagedKeyFromEnvironment \ No newline at end of file + +Remove-PolicyToEnvLink -PolicyType [PolicyType]::Encryption -EnvironmentId $EnvironmentId -PolicyArmId $PolicyArmId -Endpoint $Endpoint \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromPlatformAppsData.ps1 b/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromPlatformAppsData.ps1 index e990cc36..e6efbda5 100644 --- a/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromPlatformAppsData.ps1 +++ b/powershell/enterprisePolicies/Cmk/RemoveCustomerManagedKeyFromPlatformAppsData.ps1 @@ -1,19 +1,28 @@ -param( - [Parameter(Mandatory=$true)] +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] - [String]$policyArmId, + [String]$PolicyArmId, [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - + [BAPEndpoint]$Endpoint = "prod" ) -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force -if (![bool]$endpoint) { - $endpoint = "prod" +if (-not(Connect-Azure)) +{ + return } -UnLinkPolicyFromPlatformAppsData -policyType cmk -policyArmId $policyArmId -endpoint $endpoint +Remove-PolicyToPlatformAppsDataLink -PolicyType [PolicyType]::Encryption -PolicyArmId $PolicyArmId -Endpoint $Endpoint diff --git a/powershell/enterprisePolicies/Cmk/UpdateCMKEnterprisePolicy.ps1 b/powershell/enterprisePolicies/Cmk/UpdateCMKEnterprisePolicy.ps1 index 26369f19..6ad58450 100644 --- a/powershell/enterprisePolicies/Cmk/UpdateCMKEnterprisePolicy.ps1 +++ b/powershell/enterprisePolicies/Cmk/UpdateCMKEnterprisePolicy.ps1 @@ -1,118 +1,101 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE -function UpdateCMKEnterprisePolicy +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The Policy subscription")] + [string]$subscriptionId, + + [Parameter(Mandatory, HelpMessage="The Policy resource group")] + [string]$resourceGroup, + + [Parameter(Mandatory, HelpMessage="The Policy name")] + [string]$enterprisePolicyName, + + [Parameter(Mandatory, HelpMessage="The updated KeyVault ARM Id, enter N/A if no update is required for this field")] + [string]$keyVaultId, + + [Parameter(Mandatory, HelpMessage="The Key name, enter N/A if no update is required for this field")] + [string]$keyName, + + [Parameter(Mandatory,HelpMessage="The Key version, enter N/A if no update is required for this field")] + [string]$keyVersion +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if ($keyVaultId -eq "N/A" -and $keyName -eq "N/A" -and $keyVersion -eq "N/A") +{ + Write-Host "No change given as input..." -ForegroundColor Green + return +} + +if (-not(Connect-Azure)) +{ + return +} + +$policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" +$policy = Get-EnterprisePolicy -PolicyArmId $policyArmId +if ($null -eq $policy) +{ + Write-Host "CMK Enterprise Policy not found for $policyArmId" -ForegroundColor Red + return +} + +if ($policy.Kind -ne [PolicyType]::Encryption) +{ + $kindString = $policy.Kind | ConvertTo-Json + Write-Host "Enterprise found for $policyArmId is not CMK Enterprise Policy. Policy is of type $kindString " -ForegroundColor Red + return +} + +if ($null -eq $policy.Identity -or $policy.Identity.Type -ne "SystemAssigned") +{ + $identityString = $policy.Identity | ConvertTo-Json -Depth 7 + Write-Host "Enterprise found for $policyArmId is not having valid Identity property $identityString" -ForegroundColor Red + return +} + +$keyVaultIdUpdated = $policy.properties.encryption.keyVault.id +$keyNameUpdated = $policy.properties.encryption.keyVault.key.name +$keyVersionUpdated = $policy.properties.encryption.keyVault.key.version +if ($keyVaultId -ne "N/A") +{ + Write-Host "Updating KeyVaultId as $keyVaultId" -ForegroundColor Green + $keyVaultIdUpdated = $keyVaultId +} +if ($keyName -ne "N/A") { - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy subscription" - )] - [string]$subscriptionId, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy resource group" - )] - [string]$resourceGroup, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy name" - )] - [string]$enterprisePolicyName, - - [Parameter( - Mandatory=$true, - HelpMessage="The updated KeyVault ARM Id, enter N/A if no update is required for this field" - )] - [string]$keyVaultId, - - [Parameter( - Mandatory=$true, - HelpMessage="The Key name, enter N/A if no update is required for this field" - )] - [string]$keyName, - - [Parameter( - Mandatory=$true, - HelpMessage="The Key version, enter N/A if no update is required for this field" - )] - [string]$keyVersion - - ) - - if ($keyVaultId -eq "N/A" -and $keyName -eq "N/A" -and $keyVersion -eq "N/A") - { - Write-Host "No change given as input..." -ForegroundColor Green - return - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - $policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" - $policy = GetEnterprisePolicy $policyArmId - if ($policy -eq $null) - { - Write-Host "CMK Enterprise Policy not found for $policyArmId" -ForegroundColor Red - return - } - - if ($policy.Kind -ne "Encryption") - { - $kindString = $policy.Kind | ConvertTo-Json - Write-Host "Enterprise found for $policyArmId is not CMK Enterprise Policy. Policy is of type $kindString " -ForegroundColor Red - return - } - - if ($policy.Identity -eq $null -or $policy.Identity.Type -ne "SystemAssigned") - { - $identityString = $policy.Identity | ConvertTo-Json -Depth 7 - Write-Host "Enterprise found for $policyArmId is not having valid Identity property $identityString" -ForegroundColor Red - return - } - - $keyVaultIdUpdated = $policy.properties.encryption.keyVault.id - $keyNameUpdated = $policy.properties.encryption.keyVault.key.name - $keyVersionUpdated = $policy.properties.encryption.keyVault.key.version - if ($keyVaultId -ne "N/A") - { - Write-Host "Updating KeyVaultId as $keyVaultId" -ForegroundColor Green - $keyVaultIdUpdated = $keyVaultId - } - if ($keyName -ne "N/A") - { - Write-Host "Updating keyName as $keyName" -ForegroundColor Green - $keyNameUpdated = $keyName - } - if ($keyVersion -ne "N/A") - { - Write-Host "Updating keyVersion as $keyVersion" -ForegroundColor Green - $keyVersionUpdated = $keyVersion - } - - $body = GenerateEnterprisePolicyBody -policyType "cmk" -policyLocation $policy.Location -policyName $policy.Name -keyVaultId $keyVaultIdUpdated -keyName $keyNameUpdated -keyVersion $keyVersionUpdated - $body.resources.identity.Add("principalId", $policy.Identity.PrincipalId) - $body.resources.identity.Add("tenantId", $policy.Identity.TenantId) - - $result = PutEnterprisePolicy $resourceGroup $body - if ($result -eq $false) - { - return - } - - Write-Host "CMK Enterprise policy updated" -ForegroundColor Green - - $policy = GetEnterprisePolicy $policyArmId - $policyString = $policy | ConvertTo-Json -Depth 7 - Write-Host "The updated policy" - Write-Host $policyString + Write-Host "Updating keyName as $keyName" -ForegroundColor Green + $keyNameUpdated = $keyName } -UpdateCMKEnterprisePolicy \ No newline at end of file +if ($keyVersion -ne "N/A") +{ + Write-Host "Updating keyVersion as $keyVersion" -ForegroundColor Green + $keyVersionUpdated = $keyVersion +} + +$body = New-EnterprisePolicyBody -PolicyType [PolicyType]::Encryption -PolicyLocation $policy.Location -PolicyName $policy.Name -KeyVaultId $keyVaultIdUpdated -KeyName $keyNameUpdated -KeyVersion $keyVersionUpdated +$body.resources.identity.Add("principalId", $policy.Identity.PrincipalId) +$body.resources.identity.Add("tenantId", $policy.Identity.TenantId) + +$result = Set-EnterprisePolicy -ResourceGroup $resourceGroup -Body $body +if ($result -eq $false) +{ + return +} + +Write-Host "CMK Enterprise policy updated" -ForegroundColor Green + +$policy = Get-EnterprisePolicy -PolicyArmId $policyArmId +$policyString = $policy | ConvertTo-Json -Depth 7 +Write-Host "The updated policy" +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/Cmk/ValidateKeyVaultForCMK.ps1 b/powershell/enterprisePolicies/Cmk/ValidateKeyVaultForCMK.ps1 index 3794c1f8..03a3f1cd 100644 --- a/powershell/enterprisePolicies/Cmk/ValidateKeyVaultForCMK.ps1 +++ b/powershell/enterprisePolicies/Cmk/ValidateKeyVaultForCMK.ps1 @@ -1,26 +1,34 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force function GetAndValidateKeyVaultProperties($keyVaultName) { Write-Host "Getting KeyVault $keyVaultName" -ForegroundColor Green `n $keyVault = Get-AzKeyVault -VaultName $keyVaultName $keyVaultString = $keyVault | ConvertTo-Json - if ($keyVault -eq $nul -or $keyVault.VaultName -eq $null) + if ($keyVault -eq $nul -or $null -eq $keyVault.VaultName) { - Write-Host "Could not reterieve vault $keyVaultName $keyVaultString. Please check if key vault exists and accessible" -ForegroundColor Red + Write-Host "Could not retrieve vault $keyVaultName $keyVaultString. Please check if key vault exists and accessible" -ForegroundColor Red return $null } #validate soft-delete - if ($keyVault.EnableSoftDelete -eq $null -or $keyVault.EnableSoftDelete.Equals("False")) + if ($null -eq $keyVault.EnableSoftDelete -or $keyVault.EnableSoftDelete.Equals("False")) { Write-Host "Soft delete not enabled for keyVault $keyVaultName. Please enable it as per the instruction at https://learn.microsoft.com/azure/key-vault/general/soft-delete-change " -ForegroundColor Red return $null } #validate purge-protection - if ($keyVault.EnablePurgeProtection -eq $null -or $keyVault.EnablePurgeProtection.Equals("False")) + if ($null -eq $keyVault.EnablePurgeProtection -or $keyVault.EnablePurgeProtection.Equals("False")) { Write-Host "Purge protection not enabled for keyVault $keyVaultName. Please enable it as per the instruction at https://learn.microsoft.com/azure/key-vault/general/soft-delete-overview#permitted-purge" -ForegroundColor Red return $null @@ -33,9 +41,9 @@ function GetAndValidateKeyVaultProperties($keyVaultName) function GetAndValidateEnterprisePolicyForKeyVault($enterprisePolicyArmId, $keyVault) { Write-Host "Getting CMK enterprise policy" -ForegroundColor Green `n - $cmkPolicy = GetEnterprisePolicy $enterprisePolicyArmId + $cmkPolicy = Get-EnterprisePolicy -PolicyArmId $enterprisePolicyArmId $cmkPolicyString = $cmkPolicy | ConvertTo-Json - if ($cmkPolicy.ResourceId -eq $null) + if ($null -eq $cmkPolicy.ResourceId) { Write-Host "Could not reterieve CMK Policy $enterprisePolicyArmId $cmkPolicyString" -ForegroundColor Red @@ -46,15 +54,15 @@ function GetAndValidateEnterprisePolicyForKeyVault($enterprisePolicyArmId, $keyV if ($cmkPolicy.Kind -ne "Encryption") { - Write-Host "Enterprise Policy reterieved for $enterprisePolicyArmId is not of Kind Encryption. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red + Write-Host "Enterprise Policy retrieved for $enterprisePolicyArmId is not of Kind Encryption. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red return $null } #validate enterprise policy is having SystemAssigned identity - if ($cmkPolicy.Identity -eq $null -or $cmkPolicy.Identity.Type -ne "SystemAssigned") + if ($null -eq $cmkPolicy.Identity -or $cmkPolicy.Identity.Type -ne "SystemAssigned") { - Write-Host "Enterprise Policy reterieved for $enterprisePolicyArmId is not having SystemAssigned identity. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red + Write-Host "Enterprise Policy retrieved for $enterprisePolicyArmId is not having SystemAssigned identity. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red return $null } @@ -63,12 +71,12 @@ function GetAndValidateEnterprisePolicyForKeyVault($enterprisePolicyArmId, $keyV if ($epKeyVaultConfig.Id -ne $keyVault.ResourceId) { - Write-Host "Enterprise Policy reterieved for $enterprisePolicyArmId is not having same key vault config as $keyVaultName. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red + Write-Host "Enterprise Policy retrieved for $enterprisePolicyArmId is not having same key vault config as $keyVaultName. Enterprise Policy = $cmkPolicyString" -ForegroundColor Red return $null } #check if key vault has vault access policy - if ($keyVault.AccessPolicies -ne $null) + if ($null -ne $keyVault.AccessPolicies) { #validate CMK enterprise policy identity has Get, UnwrapKey and WrapKey access permission for key vault $accessPolicies = $keyVault.AccessPolicies @@ -88,18 +96,18 @@ function GetAndValidateEnterprisePolicyForKeyVault($enterprisePolicyArmId, $keyV Write-Host "WrapKey access not present for Enterprise Policy $enterprisePolicyArmId in keyVault $keyVaultName" -ForegroundColor Red return $null } - Write-Host "Enterprise policy $enterprisePolicyArmId reterieved and is valid for $keyvaultName with Get, UnwrapKey and WrapKey access" -ForegroundColor Green `n + Write-Host "Enterprise policy $enterprisePolicyArmId retrieved and is valid for $keyvaultName with Get, UnwrapKey and WrapKey access" -ForegroundColor Green `n } else { #validate if CMK enterprise policy identity has "Key Vault Crypto Service Encryption User" role assignment $epRoleAssignment = Get-AzRoleAssignment -Scope $keyVault.ResourceId -ObjectId $cmkPolicy.Identity.PrincipalId -RoleDefinitionName "Key Vault Crypto Service Encryption User" - if ($epRoleAssignment -eq $null) + if ($null -eq $epRoleAssignment) { Write-Host "Enterprise policy $enterprisePolicyArmId identity is not assigned 'Key Vault Crypto Service Encryption User' role" -ForegroundColor Red return $null } - Write-Host "Enterprise policy $enterprisePolicyArmId reterieved and is valid for $keyvaultName with 'Key Vault Crypto Service Encryption User' role" -ForegroundColor Green `n + Write-Host "Enterprise policy $enterprisePolicyArmId retrieved and is valid for $keyvaultName with 'Key Vault Crypto Service Encryption User' role" -ForegroundColor Green `n } @@ -115,7 +123,7 @@ function GetAndValidateEnterprisePolicyKey($epKeyVaultConfig, $keyVaultName) Write-Host "Validating enterprise policy $enterprisePolicyArmId key $keyName in $keyVaultName" -ForegroundColor Green `n $key = $null #get the specific key version if it is present in enterprise policy - if ($keyVersion -ne $null) + if ($null -ne $keyVersion) { $key = Get-AzKeyVaultKey -VaultName $keyVaultName -keyName $keyName -Version $keyVersion } @@ -124,7 +132,7 @@ function GetAndValidateEnterprisePolicyKey($epKeyVaultConfig, $keyVaultName) $key = Get-AzKeyVaultKey -VaultName $keyVaultName -keyName $keyName } $keyString = $key | ConvertTo-Json - if ($key -eq $null -or $key.Id -eq $null) + if ($null -eq $key -or $null -eq $key.Id) { Write-Host "Key $keyName not reterieved from $keyVaultName $keyString" -ForegroundColor Red return $null @@ -138,21 +146,21 @@ function GetAndValidateEnterprisePolicyKey($epKeyVaultConfig, $keyVaultName) #validate if key is valid [datetime]$current = Get-Date - $currentDateinUTC = $current.ToUniversalTime() - if($key.NotBefore -ne $null) + $currentDateInUTC = $current.ToUniversalTime() + if($null -ne $key.NotBefore) { [datetime]$notBefore = Get-Date $key.NotBefore - if ($notBefore -ge $currentDateinUTC) + if ($notBefore -ge $currentDateInUTC) { Write-Host "Key $keyName is not activated. Activation Date $notBefore" -ForegroundColor Red return $null } } - if($key.Expires -ne $null) + if($null -ne $key.Expires) { [datetime]$expires = Get-Date $key.Expires - if ($expires -le $currentDateinUTC) + if ($expires -le $currentDateInUTC) { Write-Host "Key $keyName is expired. Expiry Date $expires" -ForegroundColor Red return $null @@ -181,32 +189,27 @@ function ValidateKeyVaultForCMK ) - Write-Host "Logging In..." -ForegroundColor Green - $logged = AzureLogin - if ($logged -eq $false) + if (-not(Connect-Azure)) { - Write-Host "Login failed" -ForegroundColor Red - return + return } - Write-Host "Logged In" -ForegroundColor Green - $setSubscription = Set-AzContext -Subscription $subscriptionId + Set-AzContext -Subscription $subscriptionId | Out-Null #validate key vault $keyVault = GetAndValidateKeyVaultProperties -keyVaultName $keyVaultName - if ($keyVault -eq $null) + if ($null -eq $keyVault) { return } #validate enterprise policy $cmkPolicy = GetAndValidateEnterprisePolicyForKeyVault -enterprisePolicyArmId $enterprisePolicyArmId -keyVault $keyVault - if ($cmkPolicy -eq $null) + if ($null -eq $cmkPolicy) { return } #validate key $key = GetAndValidateEnterprisePolicyKey -epKeyVaultConfig $cmkPolicy.Properties.Encryption.KeyVault -keyVaultName $keyVaultName - } ValidateKeyVaultForCMK \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/Assert-AzIsImported.ps1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/Assert-AzIsImported.ps1 new file mode 100644 index 00000000..f9ddb713 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/Assert-AzIsImported.ps1 @@ -0,0 +1,15 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +if(-not(Get-InstalledModule Az) -and -not(Get-module -ListAvailable Az)) +{ + throw "Az module not found. Ensure it is installed by running InstallPowerAppsCmdlets.ps1" +} + +Import-Module @("Az.Accounts", "Az.Resources", "Az.KeyVault", "Az.Network") \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/AuthenticationOperations.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/AuthenticationOperations.psm1 new file mode 100644 index 00000000..b35623a7 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/AuthenticationOperations.psm1 @@ -0,0 +1,55 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +function Connect-Azure{ + + Write-Host "Logging In..." -ForegroundColor Green + $connect = Connect-AzAccount + + if ($null -eq $connect) + { + Write-Error "Error connecting to Azure Account `n" + return $false + } + Write-Host "Logged In..." -ForegroundColor Green + return $true +} + +function Connect-Bap { + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [BAPEndpoint]$Endpoint + ) + + Write-Host "Logging In..." -ForegroundColor Green + $logIn = $false + + # Login - only needs to be run once per session + if ($null -eq $global:currentSession.userId) { + $logIn = $true + } + + if (($null -eq $global:currentSession.expiresOn) -or (get-date $global:currentSession.expiresOn) -lt (Get-Date)) { + $logIn = $true + } + + $envSearch = $env + "*" + + if ($global:currentSession.bapEndpoint -notlike $envSearch) { + $logIn = $true + } + + if ($logIn) { + $result = Add-PowerAppsAccount -Endpoint $Endpoint + Write-Host $result + } + Write-Host "Logged In..." -ForegroundColor Green + return $true +} \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicies.psd1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicies.psd1 new file mode 100644 index 00000000..90b62fac --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicies.psd1 @@ -0,0 +1,116 @@ +# +# Module manifest for module 'EnterprisePolicies' +# + +@{ + # Script module or binary module file associated with this manifest. + #RootModule = '' + + # Version number of this module. Gets replaced during build. + ModuleVersion = '1.0.0' + + # Supported PSEditions + CompatiblePSEditions = @("Desktop", "Core") + + # ID used to uniquely identify this module + GUID = 'fce8ece4-09c1-4455-9253-c68b6c2ea4d6' + + # Author of this module + Author = 'Microsoft' + + # Company or vendor of this module + CompanyName = 'Microsoft Corporation' + + # Copyright statement for this module + Copyright = '(c) 2025 Microsoft Corporation. All rights reserved.' + + # Description of the functionality provided by this module + Description = 'Microsoft PowerPlatform Enterprise policies module' + + # Minimum version of the Windows PowerShell engine required by this module + PowerShellVersion = '5.1.0' + + # Name of the Windows PowerShell host required by this module + # PowerShellHostName = '' + + # Minimum version of the Windows PowerShell host required by this module + # PowerShellHostVersion = '' + + # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + DotNetFrameworkVersion = '4.8.0' + + # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + # CLRVersion = '' + + # Processor architecture (None, X86, Amd64) required by this module + # ProcessorArchitecture = '' + + # Modules that must be imported into the global environment prior to importing this module + # RequiredModules = @() + + # Assemblies that must be loaded prior to importing this module + # RequiredAssemblies = @() + + # Script files (.ps1) that are run in the caller's environment prior to importing this module. + ScriptsToProcess = @('Assert-AzIsImported.ps1') + + # Type files (.ps1xml) to be loaded when importing this module + # TypesToProcess = @() + + # Format files (.ps1xml) to be loaded when importing this module + # FormatsToProcess = @() + + # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess + NestedModules = @('Types.psm1', 'AuthenticationOperations.psm1', 'Helpers.psm1', 'VnetOperations.psm1', 'EnterprisePolicyOperations.psm1', 'EnvironmentEnterprisePolicyOperations.psm1', 'EnvironmentOperations.psm1') + + # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. + FunctionsToExport = '*' + + # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. + CmdletsToExport = '*' + + # Variables to export from this module + VariablesToExport = '*' + + # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. + AliasesToExport = '*' + + # DSC resources to export from this module + # DscResourcesToExport = @() + + # List of all modules packaged with this module + # ModuleList = @() + + # List of all files packaged with this module + # FileList = @() + + # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. + PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + } # End of PSData hashtable + + } # End of PrivateData hashtable + + # HelpInfo URI of this module + # HelpInfoURI = '' + + # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. + #DefaultCommandPrefix = '' +} diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicyOperations.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicyOperations.psm1 new file mode 100644 index 00000000..aad84b60 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnterprisePolicyOperations.psm1 @@ -0,0 +1,227 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +function Get-EnterprisePolicySystemId { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicyArmId + ) + + $policy = Get-AzResource -ResourceId $PolicyArmId -ExpandProperties + if ($null -eq $policy.ResourceId -or $null -eq $policy.Properties) + { + Write-Error "Error getting Enterprise Policy for policyId $PolicyArmId `n" + return $null + } + + return $policy.Properties.systemId +} + +function Set-EnterprisePolicy { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $ResourceGroup, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + $Body + ) + + $tmp = New-TemporaryFile + $Body | ConvertTo-Json -Depth 7 | Out-File $tmp.FullName + $policy = New-AzResourceGroupDeployment -DeploymentName "EPDeployment" -ResourceGroupName $ResourceGroup -TemplateFile $tmp.FullName + + Remove-Item $tmp.FullName + if ($policy.ProvisioningState.Equals("Succeeded")) + { + return $true + } + $policyString = $policy | ConvertTo-Json + Write-Error "Error creating/updating Enterprise policy $policyString `n" + return $false +} + +function Get-EnterprisePolicy { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicyArmId + ) + + $policy = Get-AZResource -ResourceId $PolicyArmId -ExpandProperties + return $policy +} + +function Get-EnterprisePoliciesInSubscription { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $SubscriptionId, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType + ) + + Set-AzContext -Subscription $SubscriptionId | Out-Null + $allPolicies = Get-AzResource -ResourceType "Microsoft.Powerplatform/enterprisePolicies" + $requiredPolicies = @() + foreach ($policy in $allPolicies) + { + if ($policy.kind -eq $PolicyType) + { + $requiredPolicies += $policy + } + } + return $requiredPolicies +} + +function Get-EnterprisePoliciesInResourceGroup { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $SubscriptionId, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $ResourceGroup, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType + ) + + Set-AzContext -Subscription $SubscriptionId | Out-Null + $allPolicies = Get-AzResource -ResourceType "Microsoft.Powerplatform/enterprisePolicies" -ResourceGroupName $ResourceGroup + $requiredPolicies = @() + foreach ($policy in $allPolicies) + { + if ($policy.kind -eq $PolicyType) + { + $requiredPolicies += $policy + } + } + return $requiredPolicies + +} + +function Update-EnterprisePolicy { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + $Policy + ) + + return $Policy | Set-AzResource -Force +} + +function Remove-EnterprisePolicy { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicyArmId + ) + + return Remove-AzResource -ResourceId $PolicyArmId -Force +} + +function New-EnterprisePolicyBody { + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicyLocation, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicyName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $KeyVaultId, + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $KeyName, + [Parameter()] + [ValidateNotNullOrEmpty()] + [string] $KeyVersion, + [Parameter()] + [ValidateNotNullOrEmpty()] + [VnetInformation[]] $VnetInformation + ) + + switch($PolicyType){ + [PolicyType]::Encryption{ + $body = @{ + "`$schema" = "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#" + "contentVersion" = "1.0.0.0" + "parameters"= @{} + "resources" = @( + @{ + "type" = "Microsoft.PowerPlatform/enterprisePolicies" + "apiVersion" = "2020-10-30" + "name" = $PolicyName + "location"= $PolicyLocation + "kind" = "Encryption" + + "identity" = @{ + "type"= "SystemAssigned" + } + + "properties" = @{ + "encryption" = @{ + "state" = "Enabled" + "keyVault" = @{ + "id" = $KeyVaultId + "key" = @{ + "name" = $KeyName + "version" = $KeyVersion + } + } + } + "networkInjection" = $null + } + } + ) + } + } + [PolicyType]::NetworkInjection{ + $body = @{ + "`$schema" = "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#" + "contentVersion" = "1.0.0.0" + "parameters"= @{} + "resources" = @( + @{ + "type" = "Microsoft.PowerPlatform/enterprisePolicies" + "apiVersion" = "2020-10-30" + "name" = $PolicyName + "location"= $PolicyLocation + "kind" = "NetworkInjection" + + "properties" = @{ + "networkInjection" = @{ + "virtualNetworks" = @() + } + } + } + ) + } + + foreach($vnet in $VnetInformation) + { + $body.resources[0].properties.networkInjection.virtualNetworks += @{ + "id" = $vnet.VnetId + "subnet" = @{ + "name" = $vnet.SubnetName + } + } + } + } + Default { throw "The provided policy type is unsupported $PolicyType" } + } + return $body +} \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentEnterprisePolicyOperations.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentEnterprisePolicyOperations.psm1 new file mode 100644 index 00000000..c401ab45 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentEnterprisePolicyOperations.psm1 @@ -0,0 +1,357 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +function New-PolicyToEnvLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$PolicyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $endpoint)) + { + return + } + + #Validate Environment + $env = Get-Environment -EnvironmentId $environmentId + + if ($null -eq $env) + { + return + } + Write-Host "Environment retrieved `n" -ForegroundColor Green + + #Validate Enterprise Policy + $policySystemId = Get-EnterprisePolicySystemId -PolicyArmId $policyArmId + if ($null -eq $policySystemId) + { + return + } + Write-Host "Enterprise Policy retrieved `n" -ForegroundColor Green + + $linkResult = New-EnterprisePolicyLink -Environment $env -PolicyType $policyType -PolicySystemId $policySystemId + + $linkResultString = $linkResult | ConvertTo-Json + + if ($null -eq $linkResult -or $linkResult.StatusCode -ne "202") + { + Write-Host "Linking of $policyType policy did not start for environment $environmentId" + Write-Host "Error: $linkResultString" + return + } + + Write-Host "Linking of $policyType policy started for environment $environmentId" + Invoke-PollOperation -Headers $linkResult.Headers +} + +function Remove-PolicyToEnvLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$PolicyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $endpoint)) + { + return + } + + #Validate Environment + $env = Get-Environment -EnvironmentId $EnvironmentId + + if ($null -eq $env) + { + return + } + Write-Host "Environment retrieved `n" -ForegroundColor Green + + if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$PolicyType) + { + Write-Host "No enterprise policy present to remove for environment $EnvironmentId" + return + } + + if (!$PolicyArmId.Equals($env.properties.enterprisePolicies.$PolicyType.id)) + { + Write-Host "Given policyArmId $PolicyArmId not matching with $PolicyType policy ArmId for environment $EnvironmentId" + return + } + + #Validate Enterprise Policy + $policySystemId = Get-EnterprisePolicySystemId -PolicyArmId $PolicyArmId + if ($null -eq $policySystemId) + { + return + } + Write-Host "Enterprise Policy retrieved `n" -ForegroundColor Green + + $unLinkResult = Remove-EnterprisePolicyLink $env $policyType $policySystemId + + $unLinkResultString = $UnLinkResult | ConvertTo-Json + + if ($null -eq $unLinkResult -or $unLinkResult.StatusCode -ne "202") + { + Write-Host "Unlinking of $policyType policy did not start for environment $environmentId" + Write-Host "Error: $unLinkResultString" + return + } + + Write-Host "Unlinking of $policyType policy started for environment $environmentId" + Invoke-PollOperation -Headers $unLinkResult.Headers +} + +function SwapPolicyForEnv +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$PolicyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $Endpoint)) + { + return + } + + #Validate Environment + $env = Get-Environment -EnvironmentId $EnvironmentId + + if ($null -eq $env) + { + return + } + Write-Host "Environment retrieved `n" -ForegroundColor Green + + if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$PolicyType) + { + Write-Host "No enterprise policy of $PolicyType present to swap for environment $EnvironmentId" + return + } + + #Validate Enterprise Policy + $policySystemId = Get-EnterprisePolicySystemId -PolicyArmId $PolicyArmId + if ($null -eq $policySystemId) + { + return + } + Write-Host "Enterprise Policy retrieved `n" -ForegroundColor Green + + $swapResult = New-EnterprisePolicyLink -Environment $env -PolicyType $PolicyType -PolicySystemId $PolicySystemId + + $swapResultString = $swapResult | ConvertTo-Json + + if ($null -eq $swapResult -or $swapResult.StatusCode -ne "202") + { + Write-Host "Swapping of $policyType policy did not start for environment $environmentId" + Write-Host "Error: $swapResultString" + return + } + + Write-Host "Swapping of $policyType policy started for environment $environmentId" + Invoke-PollOperation -Headers $swapResult.Headers +} + + +function Get-EnterprisePolicyForEnvironment +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$PolicyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $Endpoint)) + { + return + } + + #Validate Environment + $env = Get-Environment -EnvironmentId $EnvironmentId + + if ($null -eq $env) + { + return + } + Write-Host "Environment retrieved `n" -ForegroundColor Green + + if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$PolicyType) + { + Write-Host "No enterprise policy present of $PolicyType in environment $EnvironmentId" + return + } + + Write-Host "Enterprise Policy of type $PolicyType retrieved for environment $EnvironmentId `n" -ForegroundColor Green + $policyArmId = $env.properties.enterprisePolicies.$PolicyType.id + Write-Host "Enterprise Policy Arm Id $policyArmId" +} + +function New-PolicyToPlatformAppsDataLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$policyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$policyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $endpoint)) + { + return + } + + #Validate PlatformApps enrollment + $platformAppsStatus = Get-PlatformApps + + if ($null -eq $platformAppsStatus -or $platformAppsStatus.enrollmentState -ne "Enrolled") + { + Write-Host "PlatformApps not enrolled" + return + } + Write-Host "PlatformApps enrolled `n" -ForegroundColor Green + + #Validate Enterprise Policy + $policySystemId = Get-EnterprisePolicySystemId -PolicyArmId $policyArmId + if ($null -eq $policySystemId) + { + return + } + Write-Host "Enterprise Policy retrieved `n" -ForegroundColor Green + + + $linkResult = New-EnterprisePolicyToPlatformAppsData -PolicyType $policyType -PolicySystemId $policySystemId + + $linkResultString = $linkResult | ConvertTo-Json + + if ($null -eq $linkResult -or $linkResult.StatusCode -ne "202") + { + Write-Host "Linking of $policyType policy did not start for platformapps" + Write-Host "Error: $linkResultString" + return + } + + Write-Host "Linking of $policyType policy started for platformapps" +} + + +function Remove-PolicyToPlatformAppsDataLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$policyType, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$policyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" + ) + + if (-not(Connect-Bap -Endpoint $endpoint)) + { + return + } + + #Validate PlatformApps enrollment + $platformAppsStatus = Get-PlatformApps + + if ($null -eq $platformAppsStatus -or $platformAppsStatus.enrollmentState -ne "Enrolled") + { + Write-Host "PlatformApps not enrolled" + return + } + Write-Host "PlatformApps enrolled `n" -ForegroundColor Green + + if ($null -eq $platformAppsStatus.enterprisePolicies -or $null -eq $platformAppsStatus.enterprisePolicies.$PolicyType) + { + Write-Host "No enterprise policy present of type $policyType to remove from PlatformApps" + return + } + + if (!$policyArmId.Equals($platformAppsStatus.enterprisePolicies.$PolicyType.id)) + { + Write-Host "Given policyArmId $policyArmId not matching with $policyType policy ArmId for Platformapps" + return + } + + #Validate Enterprise Policy + $policySystemId = Get-EnterprisePolicySystemId -PolicyArmId $policyArmId + if ($null -eq $policySystemId) + { + return + } + Write-Host "Enterprise Policy retrieved `n" -ForegroundColor Green + + $unLinkResult = Remove-EnterprisePolicyForPlatformAppsData -PolicyType $policyType -PolicySystemId $policySystemId + + $unLinkResultString = $unLinkResult | ConvertTo-Json + + if ($null -eq $unLinkResult -or $unLinkResult.StatusCode -ne "202") + { + Write-Host "Unlinking of $policyType policy did not start for platformapps" + Write-Host "Error: $unLinkResultString" + return + } + + Write-Host "Unlinking of $policyType policy started for platformapps" +} + + + + diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentOperations.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentOperations.psm1 new file mode 100644 index 00000000..7e2516ad --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/EnvironmentOperations.psm1 @@ -0,0 +1,201 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +function Get-Environment +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId + ) + + $ApiVersion = "2016-11-01" + + $getEnvironmentUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/environments/$EnvironmentId/?&api-version={apiVersion}" ` + + $environmentResult = InvokeApi -Method $method -Route $getEnvironmentUri -ApiVersion $ApiVersion -Body $body + + if ($null -eq $environmentResult.Id) + { + Write-Host "Error getting environment with $environmentId for endpoint $endpoint Error = $environmentResult `n" -ForegroundColor Red + return $null + } + + return $environmentResult +} + +function Invoke-BAPLinkOrUnlink +{ + [CmdletBinding()] + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$EnvironmentId, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$ApiVersion, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$Method, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PSCustomObject]$Body, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [LinkOperation]$LinkOperation, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType]$PolicyType + ) + + $linkEnterprisePolicyUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/environments/$EnvironmentId/enterprisePolicies/$PolicyType/$LinkOperation?&api-version={apiVersion}" ` + + $linkEnterprisePolicyResult = InvokeApi -Method $Method -Route $linkEnterprisePolicyUri -ApiVersion $ApiVersion -Body $Body + + return $linkEnterprisePolicyResult +} + +function New-EnterprisePolicyLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + $Environment, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + [PolicyType] $PolicyType, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + [string] $PolicySystemId + ) + + $ApiVersion = "2019-10-01" + + $body = [PSCustomObject]@{ + "SystemId" = $policySystemId + } + + $linkResult = Invoke-BAPLinkOrUnlink -EnvironmentId $Environment.Name -ApiVersion $ApiVersion -Method "Post" -Body $body -LinkOperation [LinkOperation]::Link -PolicyType $policyType + + return $linkResult +} + +function Remove-EnterprisePolicyLink +{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + $Environment, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + [PolicyType] $PolicyType, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty] + [string] $PolicySystemId + ) + + $ApiVersion = "2019-10-01" + + $body = [PSCustomObject]@{ + "SystemId" = $policySystemId + } + + $unlinkResult = Invoke-BAPLinkOrUnlink -EnvironmentId $environment.Name $ApiVersion -Method "Post" -Body $body -LinkOperation [LinkOperation]::unlink -PolicyType $policyType + + return $unlinkResult +} + +function New-EnterprisePolicyToPlatformAppsData +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicySystemId + ) + + $ApiVersion = "2024-05-01" + + $body = [PSCustomObject]@{ + "SystemId" = $PolicySystemId + } + + $linkResult = Invoke-BAPLinkOrUnlinkForPlatformAppsData -ApiVersion $ApiVersion -Method "Post" -Body $body -LinkOperation [LinkOperation]::Link -PolicyType $PolicyType + + return $linkResult +} + +function Invoke-BAPLinkOrUnlinkForPlatformAppsData +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $ApiVersion, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Method, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PSCustomObject] $Body, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [LinkOperation] $LinkOperation, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType + ) + + $linkEnterprisePolicyUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/platformapps/enterprisePolicies/$PolicyType/$LinkOperation?&api-version={apiVersion}" ` + + $linkEnterprisePolicyResult = InvokeApi -Method $Method -Route $linkEnterprisePolicyUri -ApiVersion $ApiVersion -Body $Body + + return $linkEnterprisePolicyResult +} + + +function Remove-EnterprisePolicyForPlatformAppsData +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [PolicyType] $PolicyType, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PolicySystemId + ) + + $ApiVersion = "2024-05-01" + + $body = [PSCustomObject]@{ + "SystemId" = $PolicySystemId + } + + $unlinkResult = Invoke-BAPLinkOrUnlinkForPlatformAppsData -ApiVersion $ApiVersion -Method "Post" -Body $body -LinkOperation [LinkOperation]::unlink -PolicyType $policyType + + return $unlinkResult +} + +function Get-PlatformApps +{ + $ApiVersion = "2024-05-01" + + $getPlatformAppsUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/platformapps/status?&api-version={apiVersion}" ` + + $platformAppsResult = InvokeApi -Method "GET" -Route $getPlatformAppsUri -ApiVersion $ApiVersion -Body $body + + if ($null -eq $platformAppsResult) + { + Write-Host "Error getting platformapps for endpoint $endpoint Error = $platformAppsResult `n" -ForegroundColor Red + return $null + } + + return $platformAppsResult +} \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/Helpers.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/Helpers.psm1 new file mode 100644 index 00000000..e3a505a3 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/Helpers.psm1 @@ -0,0 +1,66 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +function Invoke-PollOperation{ + param ( + [Parameter(Mandatory, ParameterSetName="Header")] + $Headers, + [Parameter(Mandatory, ParameterSetName="Manual")] + [ValidateNotNullOrEmpty()] + $PollEndpoint, + [Parameter(Mandatory, ParameterSetName="Manual")] + [ValidateNotNullOrEmpty()] + $PollInterval + ) + + Write-Host "Do you want to poll the operation (y/n)" + $poll = Read-Host + + if ("n" -eq $poll) + { + return + } + + if($PSCmdlet.ParameterSetName -eq "Header") + { + $PollEndpoint = $Headers.'operation-location' + $PollInterval = $Headers.'Retry-After' + } + + Write-Host "Polling the operation every $PollInterval seconds." + + $run = $true + while ($run) + { + $pollResult = InvokeApi -Method GET -Route $PollEndpoint + + if ($null -eq $pollResult -or $null -eq $pollResult.id -or $null -eq $pollResult.state) + { + Write-Host "Operation polling failed $pollResult" + $run = $false + } + + $operationState = $pollResult.state.id + if ($operationState.Equals("Failed") -or $operationState.Equals("Succeeded")) + { + Write-Host "Operation finished with state $operationState" + $run = $false + } + elseif ($operationState.Equals("Running")) + { + Write-Host "Operation still running. Poll after $PollInterval seconds" + Start-Sleep -Seconds $PollInterval + } + else + { + Write-Host "Unknown operation state $operationState" + $run = $false + } + } +} \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/Types.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/Types.psm1 new file mode 100644 index 00000000..7ba96e68 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/Types.psm1 @@ -0,0 +1,74 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +class VnetInformation +{ + [string] $VnetId + [string] $SubnetName +} + +enum PolicyType +{ + Encryption + NetworkInjection + Identity +} + +enum BAPEndpoint +{ + tip1 + tip2 + prod +} + +enum LinkOperation +{ + link + unlink +} + +# Define the types to export with type accelerators. +$ExportableTypes =@( + [VnetInformation] + [PolicyType] + [BAPEndpoint] + [LinkOperation] +) +# Get the internal TypeAccelerators class to use its static methods. +$TypeAcceleratorsClass = [psobject].Assembly.GetType( + 'System.Management.Automation.TypeAccelerators' +) +# Ensure none of the types would clobber an existing type accelerator. +# If a type accelerator with the same name exists, throw an exception. +$ExistingTypeAccelerators = $TypeAcceleratorsClass::Get +foreach ($Type in $ExportableTypes) { + if ($Type.FullName -in $ExistingTypeAccelerators.Keys) { + $Message = @( + "Unable to register type accelerator '$($Type.FullName)'" + 'Accelerator already exists.' + ) -join ' - ' + + throw [System.Management.Automation.ErrorRecord]::new( + [System.InvalidOperationException]::new($Message), + 'TypeAcceleratorAlreadyExists', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $Type.FullName + ) + } +} +# Add type accelerators for every exportable type. +foreach ($Type in $ExportableTypes) { + $TypeAcceleratorsClass::Add($Type.FullName, $Type) +} +# Remove type accelerators when the module is removed. +$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = { + foreach($Type in $ExportableTypes) { + $TypeAcceleratorsClass::Remove($Type.FullName) + } +}.GetNewClosure() \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicies/VnetOperations.psm1 b/powershell/enterprisePolicies/Common/EnterprisePolicies/VnetOperations.psm1 new file mode 100644 index 00000000..6a4e7e55 --- /dev/null +++ b/powershell/enterprisePolicies/Common/EnterprisePolicies/VnetOperations.psm1 @@ -0,0 +1,101 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +$SupportedVnetLocations = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" +$SupportedVnetLocations.Add("centraluseuap", "eastus|westus") +$SupportedVnetLocations.Add("eastus2euap", "eastus|westus") +$SupportedVnetLocations.Add("unitedstateseuap", "eastus|westus") +$SupportedVnetLocations.Add("unitedstates", "eastus|westus") +$SupportedVnetLocations.Add("southafrica", "southafricanorth|southafricawest") +$SupportedVnetLocations.Add("uk", "uksouth|ukwest") +$SupportedVnetLocations.Add("japan", "japaneast|japanwest") +$SupportedVnetLocations.Add("india", "centralindia|southindia") +$SupportedVnetLocations.Add("france", "francecentral|francesouth") +$SupportedVnetLocations.Add("europe", "westeurope|northeurope") +$SupportedVnetLocations.Add("germany", "germanynorth|germanywestcentral") +$SupportedVnetLocations.Add("switzerland", "switzerlandnorth|switzerlandwest") +$SupportedVnetLocations.Add("canada", "canadacentral|canadaeast") +$SupportedVnetLocations.Add("brazil", "brazilsouth|southcentralus") +$SupportedVnetLocations.Add("australia", "australiasoutheast|australiaeast") +$SupportedVnetLocations.Add("asia", "eastasia|southeastasia") +$SupportedVnetLocations.Add("uae", "uaecentral|uaenorth") +$SupportedVnetLocations.Add("korea", "koreasouth|koreacentral") +$SupportedVnetLocations.Add("norway", "norwaywest|norwayeast") +$SupportedVnetLocations.Add("singapore", "southeastasia") +$SupportedVnetLocations.Add("sweden", "swedencentral") + +function Assert-AzureRegionIsSupported +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PowerPlatformRegion, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $AzureRegion + ) + + $vnetLocationsAllowed = $SupportedVnetLocations[$PowerPlatformRegion].Split("|") + if (-not($vnetLocationsAllowed.Contains($AzureRegion))) + { + Write-Error "The location $AzureRegion is not supported for enterprise policy location $PowerPlatformRegion`n" + $vnetLocationsAllowedString = $vnetLocationsAllowed -join "," + Write-Error "The supported vnet location for enterprise policy location $PowerPlatformRegion are $vnetLocationsAllowedString`n" + return $null + } +} +function Assert-PowerPlatformRegionIsSupported +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PowerPlatformRegion + ) + + if(-not($SupportedVnetLocations.ContainsKey($PowerPlatformRegion))) + { + throw "The PowerPlatform region [$PowerPlatformRegion] is not supported. The supported enterprise policy locations are $($SupportedVnetLocations.Keys -join ",")`n" + } +} + +function Get-SupportedVnetRegionsForPowerPlatformRegion +{ + param ( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PowerPlatformRegion + ) + + Assert-PowerPlatformRegionIsSupported -PowerPlatformRegion $PowerPlatformRegion + return $SupportedVnetLocations[$PowerPlatformRegion].Split("|") +} + +function Get-Vnet{ + param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $VnetId, + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $EnterprisePolicyLocation + ) + + $vnetResource = Get-AzResource -ResourceId $vnetId + if ($null -eq $vnetResource.ResourceId) + { + Write-Error "Error getting virtual network for $vnetId `n" + return $null + } + + Assert-PowerPlatformRegionIsSupported -PowerPlatformRegion $EnterprisePolicyLocation + + Assert-AzureRegionIsSupported -PowerPlatformRegion $EnterprisePolicyLocation -AzureRegion $vnetResource.Location + + return $vnetResource +} \ No newline at end of file diff --git a/powershell/enterprisePolicies/Common/EnterprisePolicyOperations.ps1 b/powershell/enterprisePolicies/Common/EnterprisePolicyOperations.ps1 deleted file mode 100644 index a26a43a5..00000000 --- a/powershell/enterprisePolicies/Common/EnterprisePolicyOperations.ps1 +++ /dev/null @@ -1,186 +0,0 @@ -function AzureLogin() { - - $connect = Connect-AzAccount - - if ($null -eq $connect) - { - Write-Host "Error connecting to Azure Account `n" -ForegroundColor Red - return $false - } - - return $true -} - -function GetEnterprisePolicySystemId($policyArmId) { - - $policy = Get-AzResource -ResourceId $policyArmId -ExpandProperties - if ($policy.ResourceId -eq $null -or $policy.Properties -eq $null) - { - Write-Host "Error getting Enterprise Policy for policyId $policyArmId `n" -ForegroundColor Red - return $null - } - - return $policy.Properties.systemId - -} - -function PutEnterprisePolicy($resourceGroup, $body) - { - - $tmp = New-TemporaryFile - $body | ConvertTo-Json -Depth 7 | Out-File $tmp.FullName - $policy = New-AzResourceGroupDeployment -DeploymentName "EPDeployment" -ResourceGroupName $resourceGroup -TemplateFile $tmp.FullName - - Remove-Item $tmp.FullName - if ($policy.ProvisioningState.Equals("Succeeded")) - { - return $true - } - $policyString = $policy | ConvertTo-Json - Write-Host "Error creating/updating Enterprise policy $policyString `n" -ForegroundColor Red - return $false - - -} - -function GetEnterprisePolicy($policyArmId) - { - - $policy = Get-AZResource -ResourceId $policyArmId -ExpandProperties - return $policy - -} - -function GetEnterprisePoliciesInSubscription($subscriptionId, $policyType) -{ - - $setSubscription = Set-AzContext -Subscription $subscriptionId - $allPolicies = Get-AZResource -ResourceType Microsoft.Powerplatform/enterprisePolicies - $requiredPolicies = @() - foreach ($policy in $allPolicies) - { - if ($policy.kind -eq $policyType) - { - $requiredPolicies += $policy - } - } - return $requiredPolicies - -} - -function GetEnterprisePoliciesInResourceGroup($subscriptionId, $policyType, $resourceGroup) -{ - - $setSubscription = Set-AzContext -Subscription $subscriptionId - $allPolicies = Get-AZResource -ResourceType Microsoft.Powerplatform/enterprisePolicies -ResourceGroupName $resourceGroup - $requiredPolicies = @() - foreach ($policy in $allPolicies) - { - if ($policy.kind -eq $policyType) - { - $requiredPolicies += $policy - } - } - return $requiredPolicies - -} - -function UpdateEnterprisePolicy($policy) -{ - - return $policy | Set-AzResource -Force - -} - -function RemoveEnterprisePolicy($policyArmId) -{ - - return Remove-AzResource -ResourceId $policyArmId -Force - -} - -function GenerateEnterprisePolicyBody ($policyType, $policyLocation, $policyName, $keyVaultId, $keyName, $keyVersion, $primaryVnetId, $primarySubnetName, $secondaryVnetId, $secondarySubnetName) -{ - if ("cmk" -eq $policyType) - { - $body = @{ - "`$schema" = "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#" - "contentVersion" = "1.0.0.0" - "parameters"= @{} - "resources" = @( - @{ - "type" = "Microsoft.PowerPlatform/enterprisePolicies" - "apiVersion" = "2020-10-30" - "name" = $policyName - "location"= $policyLocation - "kind" = "Encryption" - - "identity" = @{ - "type"= "SystemAssigned" - } - - "properties" = @{ - "encryption" = @{ - "state" = "Enabled" - "keyVault" = @{ - "id" = $keyVaultId - "key" = @{ - "name" = $keyName - "version" = $keyVersion - } - } - } - "networkInjection" = $null - } - } - ) - - } - - } - - elseif ("vnet" -eq $policyType) - { - $body = @{ - "`$schema" = "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#" - "contentVersion" = "1.0.0.0" - "parameters"= @{} - "resources" = @( - @{ - "type" = "Microsoft.PowerPlatform/enterprisePolicies" - "apiVersion" = "2020-10-30" - "name" = $policyName - "location"= $policyLocation - "kind" = "NetworkInjection" - - "properties" = @{ - "networkInjection" = @{ - "virtualNetworks" = @( - @{ - "id" = $primaryVnetId - "subnet" = @{ - "name" = $primarySubnetName - } - }, - @{ - "id" = $secondaryVnetId - "subnet" = @{ - "name" = $secondarySubnetName - } - } - ) - } - } - } - ) - - } - } - - return $body -} - - - - - diff --git a/powershell/enterprisePolicies/Common/EnvironmentEnterprisePolicyOperations.ps1 b/powershell/enterprisePolicies/Common/EnvironmentEnterprisePolicyOperations.ps1 deleted file mode 100644 index 900b68b8..00000000 --- a/powershell/enterprisePolicies/Common/EnvironmentEnterprisePolicyOperations.ps1 +++ /dev/null @@ -1,532 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\EnvironmentOperations.ps1" - -# Load the environment script -. "$PSScriptRoot\EnterprisePolicyOperations.ps1" - -function Login($endpoint) { - - $logIn = $false - - # Login - only needs to be run once per session - if ($null -eq $global:currentSession.userId) { - $logIn = $true - } - - if (($null -eq $global:currentSession.expiresOn) -or (get-date $global:currentSession.expiresOn) -lt (Get-Date)) { - $logIn = $true - } - - $envSearch = $env + "*" - - if ($global:currentSession.bapEndpoint -notlike $envSearch) { - $logIn = $true - } - - if ($logIn) { - $result = Add-PowerAppsAccount -Endpoint $endpoint - echo $result - } - - $connect = Connect-AzAccount - - if ($null -eq $connect) - { - Write-Host "Error connecting to Azure Account `n" -ForegroundColor Red - return $false - } - return $true -} - -function LinkPolicyToEnv -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - #Validate Environment - $env = GetEnvironment $environmentId - - if ($env -eq $null) - { - return - } - Write-Host "Environment reterieved `n" -ForegroundColor Green - - #Validate Enterprise Policy - $policySystemId = GetEnterprisePolicySystemId $policyArmId - if ($null -eq $policySystemId) - { - return - } - Write-Host "Enterprise Policy reterieved `n" -ForegroundColor Green - - - $linkResult = LinkEnterprisePolicy $env $policyType $policySystemId - - $linkResultString = $linkResult | ConvertTo-Json - - if ($null -eq $linkResult -or $linkResult.StatusCode -ne "202") - { - Write-Host "Linking of $policyType policy did not start for environement $environmentId" - Write-Host "Error: $linkResultString" - return - } - - Write-Host "Linking of $policyType policy started for environement $environmentId" - $Headers = $linkResult.Headers - - Write-Host "Do you want to poll the linking operation (y/n)" - $poll = Read-Host - - if ("n" -eq $poll) - { - return - } - - # Poll the operation every retry-after seconds - $operationLocation = $headers.'operation-location' - $retryAfter = $headers.'Retry-After' - Write-Host "Polling the link operation every $retryAfter seconds." - - PollLinkUnlinkOperation $operationLocation $retryAfter -} - -function UnLinkPolicyFromEnv -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - #Validate Environment - $env = GetEnvironment $environmentId - - if ($env -eq $null) - { - return - } - Write-Host "Environment reterieved `n" -ForegroundColor Green - - $epPropertyName = switch ( $policyType ) - { - "cmk" { "CustomerManagedKeys" } - "vnet" { "VNets" } - } - - if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$epPropertyName) - { - Write-Host "No enterprise policy present to remove for environement $environmentId" - return - } - - if (!$policyArmId.Equals($env.properties.enterprisePolicies.$epPropertyName.id)) - { - Write-Host "Given policyArmId $policyArmId not matching with $policyType policy ArmId for environement $environmentId" - return - } - - - #Validate Enterprise Policy - $policySystemId = GetEnterprisePolicySystemId $policyArmId - if ($null -eq $policySystemId) - { - return - } - Write-Host "Enterprise Policy reterieved `n" -ForegroundColor Green - - - $unLinkResult = UnLinkEnterprisePolicy $env $policyType $policySystemId - - $unLinkResultString = $UnLinkResult | ConvertTo-Json - - if ($null -eq $unLinkResult -or $unLinkResult.StatusCode -ne "202") - { - Write-Host "Unlinking of $policyType policy did not start for environement $environmentId" - Write-Host "Error: $unLinkResultString" - return - } - - Write-Host "Unlinking of $policyType policy started for environement $environmentId" - $headers = $unlinkResult.Headers - - Write-Host "Do you want to poll the unlink operation (y/n)" - $poll = Read-Host - - if ("n" -eq $poll) - { - return - } - - # Poll the operation every retry-after seconds - $operationLocation = $headers.'operation-location' - $retryAfter = $headers.'Retry-After' - Write-Host "Polling the unlink operation every $retryAfter seconds." - - PollLinkUnlinkOperation $operationLocation $retryAfter - -} - -function SwapPolicyForEnv -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - #Validate Environment - $env = GetEnvironment $environmentId - - if ($env -eq $null) - { - return - } - Write-Host "Environment reterieved `n" -ForegroundColor Green - - $epPropertyName = switch ( $policyType ) - { - "cmk" { "CustomerManagedKeys" } - "vnet" { "VNets" } - } - - if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$epPropertyName) - { - Write-Host "No enterprise policy of $policyType present to swap for environement $environmentId" - return - } - - #Validate Enterprise Policy - $policySystemId = GetEnterprisePolicySystemId $policyArmId - if ($null -eq $policySystemId) - { - return - } - Write-Host "Enterprise Policy reterieved `n" -ForegroundColor Green - - - $swapResult = LinkEnterprisePolicy $env $policyType $policySystemId - - $swapResultString = $swapResult | ConvertTo-Json - - if ($null -eq $swapResult -or $swapResult.StatusCode -ne "202") - { - Write-Host "Swapping of $policyType policy did not start for environement $environmentId" - Write-Host "Error: $swapResultString" - return - } - - Write-Host "Swapping of $policyType policy started for environement $environmentId" - $headers = $swapResult.Headers - - Write-Host "Do you want to poll the swapping operation (y/n)" - $poll = Read-Host - - if ("n" -eq $poll) - { - return - } - - # Poll the operation every retry-after seconds - $operationLocation = $headers.'operation-location' - $retryAfter = $headers.'Retry-After' - Write-Host "Polling the swap operation every $retryAfter seconds." - - PollLinkUnlinkOperation $operationLocation $retryAfter - -} - - -function GetEnterprisePolicyForEnvironment -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - #Validate Environment - $env = GetEnvironment $environmentId - - if ($env -eq $null) - { - return - } - Write-Host "Environment reterieved `n" -ForegroundColor Green - - $epPropertyName = switch ( $policyType ) - { - "cmk" { "CustomerManagedKeys" } - "vnet" { "VNets" } - } - - if ($null -eq $env.properties.enterprisePolicies -or $null -eq $env.properties.enterprisePolicies.$epPropertyName) - { - Write-Host "No enterprise policy present of $policyType in environement $environmentId" - return - } - - Write-Host "Enterprise Policy of type $policyType reterived for environment $environmentId `n" -ForegroundColor Green - $policyArmId = $env.properties.enterprisePolicies.$epPropertyName.id - Write-Host "Enterprise Policy Arm Id $policyArmId" -} - -function LinkPolicyToPlatformAppsData -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet", "identity")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - #Validate PlatformApps enrollment - $platformAppsStatus = GetPlatformApps - - if ($platformAppsStatus -eq $null -or $platformAppsStatus.enrollmentState -ne "Enrolled") - { - Write-Host "PlatformApps not enrolled" - return - } - Write-Host "PlatformApps enrolled `n" -ForegroundColor Green - - #Validate Enterprise Policy - $policySystemId = GetEnterprisePolicySystemId $policyArmId - if ($null -eq $policySystemId) - { - return - } - Write-Host "Enterprise Policy reterieved `n" -ForegroundColor Green - - - $linkResult = LinkEnterprisePolicyToPlatformAppsData $policyType $policySystemId - - $linkResultString = $linkResult | ConvertTo-Json - - if ($null -eq $linkResult -or $linkResult.StatusCode -ne "202") - { - Write-Host "Linking of $policyType policy did not start for platformapps" - Write-Host "Error: $linkResultString" - return - } - - Write-Host "Linking of $policyType policy started for platformapps" -} - - -function UnLinkPolicyFromPlatformAppsData -{ - param( - [Parameter(Mandatory=$true)] - [ValidateSet("cmk","vnet", "identity")] - [ValidateNotNullOrEmpty()] - [String]$policyType, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = Login $endpoint - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - $epPropertyName = switch ( $policyType ) - { - "cmk" { "CustomerManagedKeys" } - "vnet" { "VNets" } - "identity" { "Identity" } - } - - #Validate PlatformApps enrollment - $platformAppsStatus = GetPlatformApps - - if ($platformAppsStatus -eq $null -or $platformAppsStatus.enrollmentState -ne "Enrolled") - { - Write-Host "PlatformApps not enrolled" - return - } - Write-Host "PlatformApps enrolled `n" -ForegroundColor Green - - if ($null -eq $platformAppsStatus.enterprisePolicies -or $null -eq $platformAppsStatus.enterprisePolicies.$epPropertyName) - { - Write-Host "No enterprise policy present of type $policyType to remove from PlatformApps" - return - } - - if (!$policyArmId.Equals($platformAppsStatus.enterprisePolicies.$epPropertyName.id)) - { - Write-Host "Given policyArmId $policyArmId not matching with $policyType policy ArmId for Platformapps" - return - } - - #Validate Enterprise Policy - $policySystemId = GetEnterprisePolicySystemId $policyArmId - if ($null -eq $policySystemId) - { - return - } - Write-Host "Enterprise Policy reterieved `n" -ForegroundColor Green - - - $unLinkResult = UnLinkEnterprisePolicyForPlatformAppsData $policyType $policySystemId - - $unLinkResultString = $UnLinkResult | ConvertTo-Json - - if ($null -eq $unLinkResult -or $unLinkResult.StatusCode -ne "202") - { - Write-Host "Unlinking of $policyType policy did not start for platformapps" - Write-Host "Error: $unLinkResultString" - return - } - - Write-Host "Unlinking of $policyType policy started for platformapps" - -} - - - - diff --git a/powershell/enterprisePolicies/Common/EnvironmentOperations.ps1 b/powershell/enterprisePolicies/Common/EnvironmentOperations.ps1 deleted file mode 100644 index cb1ea435..00000000 --- a/powershell/enterprisePolicies/Common/EnvironmentOperations.ps1 +++ /dev/null @@ -1,200 +0,0 @@ -function BapLogin($endpoint) { - - $logIn = $false - - # Login - only needs to be run once per session - if ($null -eq $global:currentSession.userId) { - $logIn = $true - } - - if (($null -eq $global:currentSession.expiresOn) -or (get-date $global:currentSession.expiresOn) -lt (Get-Date)) { - $logIn = $true - } - - $envSearch = $env + "*" - - if ($global:currentSession.bapEndpoint -notlike $envSearch) { - $logIn = $true - } - - if ($logIn) { - $result = Add-PowerAppsAccount -Endpoint $endpoint - echo $result - } -} - -function GetEnvironment ($environmentId) -{ - $ApiVersion = "2016-11-01" - $environmentResult = GetEnvironmentFromBAP $environmentId $ApiVersion "GET" - - if ($environmentResult.Id -eq $null) - { - Write-Host "Error getting environment with $environmentId for endpoint $endpoint Error = $environmentResult `n" -ForegroundColor Red - return $null - } - - return $environmentResult -} - -function GetEnvironmentFromBAP ($environmentId, $ApiVersion, $method, $body) -{ - $getEnvironmentUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/environments/{environmentId}/?&api-version={apiVersion}" ` - | ReplaceMacro -Macro "{environmentId}" -Value $environmentId - - $environmentResult = InvokeApi -Method $method -Route $getEnvironmentUri -ApiVersion $ApiVersion -Body $body - - return $environmentResult -} - -function CallBAPLinkOrUnlink ($environmentId, $ApiVersion, $method, $body, $isLink, $PolicyType) -{ - $operationName = switch ( $isLink ) - { - true { "link" } - false { "unlink" } - } - - $policyTypeInUrl = switch ($policyType) - { - "cmk" { "Encryption" } - "vnet" { "NetworkInjection" } - } - - $linkEnterprisePolicyUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/environments/{environmentId}/enterprisePolicies/{policyTypeInUrl}/{operationName}?&api-version={apiVersion}" ` - | ReplaceMacro -Macro "{environmentId}" -Value $environmentId | ReplaceMacro -Macro "{operationName}" -Value $operationName | ReplaceMacro -Macro "{policyTypeInUrl}" -Value $policyTypeInUrl - - $linkEnterprisePolicyResult = InvokeApi -Method $method -Route $linkEnterprisePolicyUri -ApiVersion $ApiVersion -Body $body - - return $linkEnterprisePolicyResult -} - -function LinkEnterprisePolicy ($environment, $policyType, $policySystemId) -{ - $ApiVersion = "2019-10-01" - - $body = [pscustomobject]@{ - "SystemId" = $policySystemId - } - - $linkResult = CallBAPLinkOrUnlink $environment.Name $ApiVersion "Post" $body true $policyType $policyType - - return $linkResult -} - -function UnLinkEnterprisePolicy ($environment, $policyType, $policySystemId) -{ - $ApiVersion = "2019-10-01" - - $body = [pscustomobject]@{ - "SystemId" = $policySystemId - } - - $unlinkResult = CallBAPLinkOrUnlink $environment.Name $ApiVersion "Post" $body false $policyType $policyType - - - return $unlinkResult -} - -function PollLinkUnlinkOperation ($operationLink, $pollInterval) -{ - - $run = $true - while ($run) - { - $pollResult = InvokeApi -Method GET -Route $operationLink - - if ($null -eq $pollResult -or $null -eq $pollResult.id -or $null -eq $pollResult.state) - { - echo "Operation polling failed $pollResult" - $run = $false - } - - $operationState = $pollResult.state.id - if ($operationState.Equals("Failed") -or $operationState.Equals("Succeeded")) - { - echo "Operation finished with state $operationState" - $run = $false - } - elseif ($operationState.Equals("Running")) - { - echo "Operation still running. Poll after $pollInterval seconds" - start-sleep -seconds $pollInterval - - } - else - { - echo "unknown operation state $operationState" - $run = $false - } - } -} - -function LinkEnterprisePolicyToPlatformAppsData ($policyType, $policySystemId) -{ - $ApiVersion = "2024-05-01" - - $body = [pscustomobject]@{ - "SystemId" = $policySystemId - } - - $linkResult = CallBAPLinkOrUnlinkForPlatformAppsData $ApiVersion "Post" $body true $policyType - - return $linkResult -} - -function CallBAPLinkOrUnlinkForPlatformAppsData ($ApiVersion, $method, $body, $isLink, $PolicyType) -{ - $operationName = switch ( $isLink ) - { - true { "link" } - false { "unlink" } - } - - $policyTypeInUrl = switch ($policyType) - { - "cmk" { "Encryption" } - "vnet" { "NetworkInjection" } - "identity" { "Identity" } - } - - $linkEnterprisePolicyUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/platformapps/enterprisePolicies/{policyTypeInUrl}/{operationName}?&api-version={apiVersion}" ` - | ReplaceMacro -Macro "{operationName}" -Value $operationName | ReplaceMacro -Macro "{policyTypeInUrl}" -Value $policyTypeInUrl - - $linkEnterprisePolicyResult = InvokeApi -Method $method -Route $linkEnterprisePolicyUri -ApiVersion $ApiVersion -Body $body - - return $linkEnterprisePolicyResult -} - - -function UnLinkEnterprisePolicyForPlatformAppsData ($policyType, $policySystemId) -{ - $ApiVersion = "2024-05-01" - - $body = [pscustomobject]@{ - "SystemId" = $policySystemId - } - - $unlinkResult = CallBAPLinkOrUnlinkForPlatformAppsData $ApiVersion "Post" $body false $policyType $policyType - - - return $unlinkResult -} - -function GetPlatformApps () -{ - $ApiVersion = "2024-05-01" - $method = "GET" - - $getPlatformAppsUri = "https://{bapEndpoint}/providers/Microsoft.BusinessAppPlatform/platformapps/status?&api-version={apiVersion}" ` - - $platformAppsResult = InvokeApi -Method $method -Route $getPlatformAppsUri -ApiVersion $ApiVersion -Body $body - - if ($platformAppsResult -eq $null) - { - Write-Host "Error getting platformapps for endpoint $endpoint Error = $platformAppsResult `n" -ForegroundColor Red - return $null - } - - return $platformAppsResult -} \ No newline at end of file diff --git a/powershell/enterprisePolicies/README.md b/powershell/enterprisePolicies/README.md index ec7661ed..9a7b9909 100644 --- a/powershell/enterprisePolicies/README.md +++ b/powershell/enterprisePolicies/README.md @@ -178,92 +178,126 @@ The Subnet Injection scripts are present in folder SubnetInjection at current lo ### 1. **Setup virtual network for Subnet Injection** This script adds the subnet delegation for Microsoft.PowerPlatform/enterprisePolicies for a given virtual network and subnet
-Script name : SetupVnetForSubnetDelegation.ps1
+Script name : New-VnetForSubnetDelegation.ps1
Input parameters : - - virtualNetworkSubscriptionId : The subscriptionId of the virtual network - - virtualNetworkName : The name of the virtual network - - subnetName : The name of the virtual network subnet + - virtualNetworkSubscriptionId : The subscriptionId of the virtual network + - virtualNetworkName : The name of the virtual network + - subnetName : The name of the virtual network subnet Sample Input :
-![alt text](./ReadMeImages/SetupVirtualNetwork1.png)
+```powershell +New-VnetForSubnetDelegation.ps1 ` +-virtualNetworkSubscriptionId "98159998-fb68-44c3-b7d8-22b6539499a2" ` +-virtualNetworkName "demoVirtualNetwork" ` +-subnetName "default" +``` Sample Output :
![alt text](./ReadMeImages/SetupVirtualNetwork2.png)
### 2. **Create Subnet Injection Enterprise Policy** This script creates a Subnet Injection enterprise policy
-Script name : CreateSubnetInjectionEnterprisePolicy.ps1
+Script name : New-SubnetInjectionEnterprisePolicy.ps1
Input parameters : - - subscriptionId : The subscriptionId where Subnet Injection enterprise policy needs to be created - - resourceGroup : The resource group where Subnet Injection enterprise policy needs to be created - - enterprisePolicyName : The name of the Subnet Injection enterprise policy resource - - enterprisePolicyLocation : The Azure geo where Subnet Injection enterprise policy needs to be created. Example: unitedstates, europe, australia.
- To get the complete supported locations for enterprise policy, below command can be used:
+ - subscriptionId : The subscriptionId where Subnet Injection enterprise policy needs to be created + - resourceGroup : The resource group where Subnet Injection enterprise policy needs to be created + - enterprisePolicyName : The name of the Subnet Injection enterprise policy resource + - enterprisePolicyLocation : The Azure geo where Subnet Injection enterprise policy needs to be created. Example: unitedstates, europe, australia.
+ >[NOTE] To get the complete supported locations for enterprise policy, use the command below:
((Get-AzResourceProvider -ProviderNamespace Microsoft.PowerPlatform).ResourceTypes | Where-Object ResourceTypeName -eq enterprisePolicies).Locations - - primaryVnetId : The ARM resource ID of the primary virtual network used for Subnet Injection - - primarySubnetName : The name of the subnet in the primary virtual network that will be used for Subnet Injection - - secondaryVnetId : The ARM resource ID of the secondary virtual network used for Subnet Injection - - secondarySubnetName : The name of the subnet in the secondary virtual network that will be used for Subnet Injection + - vnetId1 : The ARM resource ID of the first virtual network used for Subnet Injection + - subnetName1 : The name of the subnet in the first virtual network that will be used for Subnet Injection + - vnetId2 : The ARM resource ID of the second virtual network used for Subnet Injection + - subnetName2 : The name of the subnet in the second virtual network that will be used for Subnet Injection Sample Input :
-![alt text](./ReadMeImages/CreateSubnetInjectionEnterprisePolicy1.png)
+```powershell +New-SubnetInjectionEnterprisePolicy.ps1 ` +-subscriptionId "98159998-fb68-44c3-b7d8-22b6539499a2" ` +-resourceGroup "enterprisePolicy-snet-delegation" ` +-enterprisePolicyName "vnetEP1" ` +-enterprisePolicyLocation "unitedstates" ` +-vnetId1 "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.Network/virtualNetworks/westus-vnet" ` +-subnetName1 "wus-delegated-snet" ` +-vnetId2 "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.Network/virtualNetworks/eastus-vnet" ` +-subnetName "eus-delegated-snet" ` +``` Sample Output :
![alt text](./ReadMeImages/CreateSubnetInjectionEnterprisePolicy2.png)
### 3. **Get Subnet Injection Enterprise Policy By ResourceId** The script gets a Subnet Injection enterprise policy by ARM resourceId
-Script name : GetSubnetInjectionEnterprisePolicyByResourceId.ps1
+Script name : Get-SubnetInjectionEnterprisePolicyByResourceId.ps1
Input parameter : - - enterprisePolicyArmId : The ARM resource ID of the Subnet Injection Enterprise Policy + - enterprisePolicyArmId : The ARM resource ID of the Subnet Injection Enterprise Policy Sample Input :
-![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePolicyByResourceId1.png)
+```powershell +Get-SubnetInjectionEnterprisePolicyByResourceId.ps1 ` +-enterprisePolicyArmId "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.PowerPlatform/enterprisePolicies/vnetEP1" +``` Sample Output :
![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePolicyByResourceId2.png)
### 4. **Get Subnet Injection Enterprise Policies in Subscription** The script gets all Subnet Injection enterprise policies in an Azure subscription
-Script name : GetSubnetInjectionEnterprisePoliciesInSubscription.ps1
+Script name : Get-SubnetInjectionEnterprisePoliciesInSubscription.ps1
Input parameter : - - subscriptionId: : The Azure subscription Id + - subscriptionId: : The Azure subscription Id Sample Input :
-![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePoliciesInSubscription1.png)
+```powershell +Get-SubnetInjectionEnterprisePoliciesInSubscription.ps1 ` +-subscriptionId "98159998-fb68-44c3-b7d8-22b6539499a2" +``` Sample Output :
![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePoliciesInSubscription2.png)
### 5. **Get Subnet Injection Enterprise Policies in Resource Group** The script gets all Subnet Injection enterprise policies in an Azure resource group
-Script name : GetSubnetInjectionEnterprisePoliciesInResourceGroup.ps1
+Script name : Get-SubnetInjectionEnterprisePoliciesInResourceGroup.ps1
Input parameters : - - subscriptionId : The Azure subscription Id - - resourceGroup : The Azure resource group + - subscriptionId : The Azure subscription Id + - resourceGroup : The Azure resource group Sample Input :
-![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePoliciesInResourceGroup1.png)
+```powershell +Get-SubnetInjectionEnterprisePoliciesInResourceGroup.ps1 ` +-subscriptionId "98159998-fb68-44c3-b7d8-22b6539499a2" ` +-resourceGroup "enterprisePolicy-snet-delegation" +``` Sample Output :
![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePoliciesInResourceGroup2.png)
### 6. **Update Subnet Injection Enterprise Policy** -This script updates a Subnet Injection Enterprise Policy. The updates allowed are for primary/secondary virtual network Id and/or primary/secondary subnet name.
+This script updates a Subnet Injection Enterprise Policy. The updates allowed are for either of the virtual network Ids and subnet names.
If you are changing only some of the allowed parameter values, provide “N/A” when prompted for the parameters that you don’t want to change.
**If the enterprise policy is associated with one or more environments, the update operation will fail, and the script will return an error.**
-Script name : UpdateSubnetInjectionEnterprisePolicy.ps1
+Script name : Update-SubnetInjectionEnterprisePolicy.ps1
Input parameters : - - subscriptionId : The Azure subscription Id of the Subnet Injection Enterprise Policy - - resourceGroup : The Azure resource group of the Subnet Injection Enterprise Policy - - enterprisePolicyName : The name of the Subnet Injection enterprise policy that needs to be updated - - primaryVnetId : The ARM resource ID of the primary virtual network if it needs to be updated. Provide "N/A" if update is not required for the primary virtual network Id - - primarySubnetName: The name of the subnet in the primary virtual network if it needs to be updated. Provide "N/A" if update is not required for name of the subnet in the primary virtual network - - secondaryVnetId : The ARM resource ID of the secondary virtual network if it needs to be updated. Provide "N/A" if update is not required for the secondary virtual network Id - - secondarySubnetName: The name of the subnet in the secondary virtual network if it needs to be updated. Provide "N/A" if update is not required for name of the subnet in the secondary virtual network + - subscriptionId : The Azure subscription Id of the Subnet Injection Enterprise Policy + - resourceGroup : The Azure resource group of the Subnet Injection Enterprise Policy + - enterprisePolicyName : The name of the Subnet Injection enterprise policy that needs to be updated + - vnetId1 : The ARM resource ID of the first virtual network if it needs to be updated. Provide "N/A" if update is not required for the first virtual network Id + - subnetName1 : The name of the subnet in the first virtual network if it needs to be updated. Provide "N/A" if update is not required for name of the subnet in the first virtual network + - vnetId2 : The ARM resource ID of the second virtual network if it needs to be updated. Provide "N/A" if update is not required for the second virtual network Id + - subnetName2 : The name of the subnet in the second virtual network if it needs to be updated. Provide "N/A" if update is not required for name of the subnet in the second virtual network Sample Input :
-![alt text](./ReadMeImages/UpdateSubnetInjectionEnterprisePolicy1.png)
+```powershell +Update-SubnetInjectionEnterprisePolicy.ps1 ` +-subscriptionId "98159998-fb68-44c3-b7d8-22b6539499a2" ` +-resourceGroup "enterprisePolicy-snet-delegation" ` +-enterprisePolicyName "vnetEP1" ` +-vnetId1 "N/A" ` +-subnetName1 "N/A" ` +-vnetId2 "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.Network/virtualNetworks/eastus-vnet" ` +-subnetName2 "new-eus-delegated-snet" +``` Sample Output :
![alt text](./ReadMeImages/UpdateSubnetInjectionEnterprisePolicy2.png)
@@ -271,38 +305,49 @@ Sample Output :
### 7. **Set Subnet Injection for an environment** This script applies a Subnet Injection enterprise policy to a given Power Platform environment.
The script adds the environment to the enterprise policy and optionally polls for the operation outcome.
-Script name : NewSubnetInjection.ps1
+Script name : New-SubnetInjection.ps1
Input parameters : - - environmentId : The Power Platform environment ID - - policyArmId : The ARM ID of the Subnet Injection Enterprise Policy + - environmentId : The Power Platform environment ID + - policyArmId : The ARM ID of the Subnet Injection Enterprise Policy Sample Input :
-![alt text](./ReadMeImages/NewSubnetInjection1.png)
+```powershell +New-SubnetInjection.ps1 ` +-environmentId "03ec85eb-f8f3-4f26-9d8e-683479431def" ` +-policyArmId "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.PowerPlatform/enterprisePolicies/vnetEP1" +``` Sample Output :
![alt text](./ReadMeImages/NewSubnetInjection2.png)
### 8. **Get Subnet Injection for an environment** This script returns the Subnet Injection enterprise policy if applied to a given Power Platform environment.
-Script name : GetSubnetInjectionEnterprisePolicyForEnvironment.ps1
+Script name : Get-SubnetInjectionEnterprisePolicyForEnvironment.ps1
Input parameter : - - environmentId : The Power Platform environment ID + - environmentId : The Power Platform environment ID Sample Input :
-![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePolicyForEnvironment1.png)
+```powershell +Get-SubnetInjectionEnterprisePolicyForEnvironment.ps1 ` +-environmentId "03ec85eb-f8f3-4f26-9d8e-683479431def" +``` Sample Output :
![alt text](./ReadMeImages/GetSubnetInjectionEnterprisePolicyForEnvironment2.png)
### 9. **Remove Subnet Injection from an environment** The script removes the Subnet Injection enterprise policy from an environment,
-Script name : RevertSubnetInjection.ps1
+Script name : Remove-SubnetInjection.ps1
Input parameters : - - environmentId : The Power Platform environment ID - - policyArmId: The ARM ID of the Subnet Injection Enterprise Policy + - environmentId : The Power Platform environment ID + - policyArmId: The ARM ID of the Subnet Injection Enterprise Policy Sample Input :
-![alt text](./ReadMeImages/RevertSubnetInjection1.png)
+```powershell +Remove-SubnetInjection.ps1 ` +-environmentId "03ec85eb-f8f3-4f26-9d8e-683479431def" ` +-policyArmId "/subscriptions/98159998-fb68-44c3-b7d8-22b6539499a2/resourceGroups/enterprisePolicy-snet-delegation/Providers/Microsoft.PowerPlatform/enterprisePolicies/vnetEP1" +``` Sample Output :
![alt text](./ReadMeImages/RevertSubnetInjection2.png)
diff --git a/powershell/enterprisePolicies/SubnetInjection/CreateSubnetInjectionEnterprisePolicy.ps1 b/powershell/enterprisePolicies/SubnetInjection/CreateSubnetInjectionEnterprisePolicy.ps1 deleted file mode 100644 index d94ffd93..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/CreateSubnetInjectionEnterprisePolicy.ps1 +++ /dev/null @@ -1,101 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" -. "$PSScriptRoot\ValidateVnetLocationForEnterprisePolicy.ps1" - - -function CreateSubnetInjectionEnterprisePolicy -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy subscription" - )] - [string]$subscriptionId, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy resource group" - )] - [string]$resourceGroup, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy name" - )] - [string]$enterprisePolicyName, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy location" - )] - [string]$enterprisePolicylocation, - - [Parameter( - Mandatory=$true, - HelpMessage="Primary virtual network Id" - )] - [string]$primaryVnetId, - - [Parameter( - Mandatory=$true, - HelpMessage="Primary subnet name" - )] - [string]$primarySubnetName, - - [Parameter( - Mandatory=$true, - HelpMessage="Secondary virtual network Id" - )] - [string]$secondaryVnetId, - - [Parameter( - Mandatory=$true, - HelpMessage="Secondary subnet name" - )] - [string]$secondarySubnetName - - ) - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - Write-Host "Error Logging In..." -ForegroundColor Red - return - } - - Write-Host "Logged In..." -ForegroundColor Green - Write-Host "Creating Enterprise policy..." -ForegroundColor Green - - $primaryVnet = ValidateAndGetVnet -vnetId $primaryVnetId -enterprisePolicylocation $enterprisePolicylocation - if ($primaryVnet -eq $null) - { - Write-Host "Subnet Injection Enterprise policy not created" -ForegroundColor Red - return - } - - $secondaryVnet = ValidateAndGetVnet -vnetId $secondaryVnetId -enterprisePolicylocation $enterprisePolicylocation - if ($secondaryVnet -eq $null) - { - Write-Host "Subnet Injection Enterprise policy not created" -ForegroundColor Red - return - } - - $body = GenerateEnterprisePolicyBody -policyType "vnet" -policyLocation $enterprisePolicyLocation -policyName $enterprisePolicyName -primaryVnetId $primaryVnetId -primarySubnetName $primarySubnetName -secondaryVnetId $secondaryVnetId -secondarySubnetName $secondarySubnetName - - $result = PutEnterprisePolicy $resourceGroup $body - if ($result -eq $false) - { - Write-Host "Subnet Injection Enterprise policy not created" -ForegroundColor Red - return - } - Write-Host "Subnet Injection Enterprise policy created" -ForegroundColor Green - - $policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" - $policy = GetEnterprisePolicy $policyArmId - $policyString = $policy | ConvertTo-Json -Depth 7 - Write-Host "Policy created" - Write-Host $policyString - -} -CreateSubnetInjectionEnterprisePolicy \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInResourceGroup.ps1 b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInResourceGroup.ps1 new file mode 100644 index 00000000..7448afde --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInResourceGroup.ps1 @@ -0,0 +1,28 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The subscriptionId")] + [string]$SubscriptionId, + + [Parameter(Mandatory, HelpMessage="The resource group")] + [string]$ResourceGroup +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +$policies = Get-EnterprisePoliciesInResourceGroup -SubscriptionId $SubscriptionId -ResourceGroup $ResourceGroup -PolicyType [PolicyType]::NetworkInjection +$policies | Select-Object -Property ResourceId, Location, Name \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInSubscription.ps1 b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInSubscription.ps1 new file mode 100644 index 00000000..c415ecf7 --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePoliciesInSubscription.ps1 @@ -0,0 +1,25 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The subscriptionId")] + [string]$subscriptionId +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +$policies = Get-EnterprisePoliciesInSubscription -SubscriptionId $subscriptionId -PolicyType [PolicyType]::NetworkInjection +$policies | Select-Object -Property ResourceId, Location, Name \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyByResourceId.ps1 b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyByResourceId.ps1 new file mode 100644 index 00000000..3460f249 --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyByResourceId.ps1 @@ -0,0 +1,26 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The Policy Id")] + [string]$enterprisePolicyArmId +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +$policy = Get-EnterprisePolicy -PolicyArmId $enterprisePolicyArmId +$policyString = $policy | ConvertTo-Json -Depth 7 +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyForEnvironment.ps1 b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyForEnvironment.ps1 new file mode 100644 index 00000000..0158673f --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Get-SubnetInjectionEnterprisePolicyForEnvironment.ps1 @@ -0,0 +1,28 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +Get-EnterprisePolicyForEnvironment -PolicyType [PolicyType]::NetworkInjection -EnvironmentId $EnvironmentId -Endpoint $Endpoint \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInResourceGroup.ps1 b/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInResourceGroup.ps1 deleted file mode 100644 index d2d30d77..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInResourceGroup.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" - -function GetSubnetInjectionEnterprisePoliciesInResourceGroup -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The subscriptionId" - )] - [string]$subscriptionId, - - [Parameter( - Mandatory=$true, - HelpMessage="The resource group" - )] - [string]$resourceGroup - ) - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - $policies = GetEnterprisePoliciesInResourceGroup $subscriptionId "NetworkInjection" $resourceGroup - $policies | Select-Object -Property ResourceId, Location, Name - -} -GetSubnetInjectionEnterprisePoliciesInResourceGroup \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInSubscription.ps1 b/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInSubscription.ps1 deleted file mode 100644 index 7455395b..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePoliciesInSubscription.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" - -function GetSubnetInjectionEnterprisePoliciesInSubscription -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The subscriptionId" - )] - [string]$subscriptionId - ) - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - $policies = GetEnterprisePoliciesInSubscription $subscriptionId "NetworkInjection" - $policies | Select-Object -Property ResourceId, Location, Name - -} -GetSubnetInjectionEnterprisePoliciesInSubscription \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyByResourceId.ps1 b/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyByResourceId.ps1 deleted file mode 100644 index c784e4ac..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyByResourceId.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" - -function GetSubnetInjectionEnterprisePolicyByResourceId -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy Id" - )] - [string]$enterprisePolicyArmId - ) - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - $policy = GetEnterprisePolicy $enterprisePolicyArmId - $policyString = $policy | ConvertTo-Json -Depth 7 - Write-Host $policyString - -} -GetSubnetInjectionEnterprisePolicyByResourceId \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyForEnvironment.ps1 b/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyForEnvironment.ps1 deleted file mode 100644 index eb701dd1..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/GetSubnetInjectionEnterprisePolicyForEnvironment.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" - -function GetSubnetInjectionEnterprisePolicyForEnvironment -{ - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - GetEnterprisePolicyForEnvironment -policyType vnet -environmentId $environmentId -endpoint $endpoint -} -GetSubnetInjectionEnterprisePolicyForEnvironment \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjection.ps1 b/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjection.ps1 new file mode 100644 index 00000000..d00872ba --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjection.ps1 @@ -0,0 +1,32 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +New-PolicyToEnvLink -PolicyType [PolicyType]::NetworkInjection -EnvironmentId $EnvironmentId -PolicyArmId $PolicyArmId -Endpoint $Endpoint \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjectionEnterprisePolicy.ps1 b/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjectionEnterprisePolicy.ps1 new file mode 100644 index 00000000..c7fab4dc --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/New-SubnetInjectionEnterprisePolicy.ps1 @@ -0,0 +1,92 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The Policy subscription")] + [string]$SubscriptionId, + + [Parameter(Mandatory,HelpMessage="The Policy resource group")] + [string]$ResourceGroup, + + [Parameter(Mandatory, HelpMessage="The Policy name")] + [string]$EnterprisePolicyName, + + [Parameter(Mandatory, HelpMessage="The Policy location")] + [string]$EnterprisePolicyLocation, + + [Parameter(Mandatory, HelpMessage="Virtual network Id 1")] + [string]$VnetId1, + + [Parameter(Mandatory, HelpMessage="Subnet name 1")] + [string]$SubnetName1, + + [Parameter(Mandatory=$false, HelpMessage="Virtual network Id 2")] + [string]$VnetId2, + + [Parameter(Mandatory=$false, HelpMessage="Subnet name 2")] + [string]$SubnetName2 +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +Write-Host "Creating Enterprise policy..." -ForegroundColor Green + +[VnetInformation[]] $vnetInformation + +$Vnet1 = Get-Vnet -VnetId $VnetId1 -EnterprisePolicyLocation $EnterprisePolicyLocation +if ($null -eq $Vnet1) +{ + Write-Error "There was an issue retrieving or validating the Vnet." +} + +$vnetInformation += [VnetInformation] @{ + VnetId = $VnetId1 + SubnetName = $SubnetName1 +} + +if((Get-SupportedVnetRegionsForPowerPlatformRegion -PowerPlatformRegion $EnterprisePolicyLocation).Count -eq 2) +{ + if([string]::IsNullOrWhiteSpace($VnetId2) -and [string]::IsNullOrWhiteSpace($SubnetNam2)) + { + throw "The region [$EnterprisePolicyLocation] requires that information for 2 subnets be provided." + } + + $Vnet2 = Get-Vnet -VnetId $VnetId2 -EnterprisePolicyLocation $EnterprisePolicyLocation + if ($null -eq $Vnet2) + { + Write-Error "There was an issue retrieving or validating the Vnet." + } + + $vnetInformation += [VnetInformation] @{ + VnetId = $VnetId2 + SubnetName = $SubnetName2 + } +} + +$body = New-EnterprisePolicyBody -PolicyType [PolicyType]::NetworkInjection -PolicyLocation $EnterprisePolicyLocation -PolicyName $EnterprisePolicyName -VnetInformation $vnetInformation + +$result = Set-EnterprisePolicy -ResourceGroup $ResourceGroup -Body $body +if (-not($result)) +{ + Write-Error "Subnet Injection Enterprise policy not created" +} +Write-Host "Subnet Injection Enterprise policy created" -ForegroundColor Green + +$policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$EnterprisePolicyName" +$policy = Get-EnterprisePolicy -PolicyArmId $policyArmId +$policyString = $policy | ConvertTo-Json -Depth 7 +Write-Host "Policy created" +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/New-VnetForSubnetDelegation.ps1 b/powershell/enterprisePolicies/SubnetInjection/New-VnetForSubnetDelegation.ps1 new file mode 100644 index 00000000..628a41ec --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/New-VnetForSubnetDelegation.ps1 @@ -0,0 +1,54 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The subscription where the subnet is located")] + [string]$SubscriptionId, + + [Parameter(Mandatory, HelpMessage="The name of the virtual network the subnet belongs to")] + [ValidateNotNullOrEmpty()] + [String]$VirtualNetworkName, + + [Parameter(Mandatory, HelpMessage="The name of the subnet to delegate")] + [ValidateNotNullOrEmpty()] + [String]$SubnetName +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +Set-AzContext -Subscription $SubscriptionID | Out-Null + +Write-Host "Getting virtual network $VirtualNetworkName" -ForegroundColor Green +$virtualNetwork = Get-AzVirtualNetwork -Name $VirtualNetworkName +if ($null -eq $virtualNetwork.Name) +{ + Write-Error "Virtual network not retrieved" +} +Write-Host "Virtual network retrieved" -ForegroundColor Green + +Write-Host "Getting virtual network subnet $SubnetName" -ForegroundColor Green +$subnet = Get-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $virtualNetwork +if ($null -eq $subnet.Name) +{ + Write-Error "Virtual network subnet not retrieved" +} +Write-Host "Virtual network subnet retrieved" -ForegroundColor Green + +Write-Host "Adding delegation for Microsoft.PowerPlatform/enterprisePolicies to subnet $subnet.Name in vnet $VirtualNetworkName" -ForegroundColor Green +$subnet = Add-AzDelegation -Name "Microsoft.PowerPlatform/enterprisePolicies" -ServiceName "Microsoft.PowerPlatform/enterprisePolicies" -Subnet $subnet +Set-AzVirtualNetwork -VirtualNetwork $virtualNetwork + +Write-Host "Added delegation for Microsoft.PowerPlatform/enterprisePolicies to subnet $subnet in vnet $VirtualNetworkName" -ForegroundColor Green \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/NewSubnetInjection.ps1 b/powershell/enterprisePolicies/SubnetInjection/NewSubnetInjection.ps1 deleted file mode 100644 index cd604f7f..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/NewSubnetInjection.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" - -function NewSubnetInjection -{ - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - LinkPolicyToEnv -policyType vnet -environmentId $environmentId -policyArmId $policyArmId -endpoint $endpoint -} -NewSubnetInjection \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Remove-SubnetInjection.ps1 b/powershell/enterprisePolicies/SubnetInjection/Remove-SubnetInjection.ps1 new file mode 100644 index 00000000..754d5152 --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Remove-SubnetInjection.ps1 @@ -0,0 +1,32 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String]$EnvironmentId, + + [Parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [String]$PolicyArmId, + + [Parameter(Mandatory=$false)] + [BAPEndpoint]$Endpoint = "prod" +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +Remove-PolicyToEnvLink -PolicyType [PolicyType]::NetworkInjection -EnvironmentId $EnvironmentId -PolicyArmId $PolicyArmId -Endpoint $Endpoint diff --git a/powershell/enterprisePolicies/SubnetInjection/RevertSubnetInjection.ps1 b/powershell/enterprisePolicies/SubnetInjection/RevertSubnetInjection.ps1 deleted file mode 100644 index d7810c74..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/RevertSubnetInjection.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnvironmentEnterprisePolicyOperations.ps1" - - -function RevertSubnetInjection -{ - param( - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$environmentId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$policyArmId, - - [Parameter(Mandatory=$false)] - [ValidateSet("tip1", "tip2", "prod")] - [String]$endpoint - - ) - - if (![bool]$endpoint) { - $endpoint = "prod" - } - - UnLinkPolicyFromEnv -policyType vnet -environmentId $environmentId -policyArmId $policyArmId -endpoint $endpoint -} -RevertSubnetInjection \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/SetupVnetForSubnetDelegation.ps1 b/powershell/enterprisePolicies/SubnetInjection/SetupVnetForSubnetDelegation.ps1 deleted file mode 100644 index fe670d44..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/SetupVnetForSubnetDelegation.ps1 +++ /dev/null @@ -1,54 +0,0 @@ -# Load thescript -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" - -function SetupVnetForSubnetDelegation -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy subscription" - )] - [string]$virtualNetworkSubscriptionId, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$virtualNetworkName, - - [Parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [String]$subnetName - ) - - Write-Host "Logging In..." -ForegroundColor Green - AzureLogin - Write-Host "Logged In" -ForegroundColor Green - - $setSubscription = Set-AzContext -Subscription $virtualNetworkSubscriptionId - - Write-Host "Getting virtual network $virtualNetworkName" -ForegroundColor Green - $virtualNetwork = Get-AzVirtualNetwork -Name $virtualNetworkName - if ($null -eq $virtualNetwork.Name) - { - Write-Host "Virtual network not reterieved" -ForegroundColor Red - return - } - Write-Host "Virtual network reterieved" -ForegroundColor Green - - Write-Host "Getting virtual network subnet $subnetName" -ForegroundColor Green - $subnet = Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $virtualNetwork - if ($null -eq $subnet.Name) - { - Write-Host "Virtual network subnet not reterieved" -ForegroundColor Red - return - } - Write-Host "Virtual network subnet reterieved" -ForegroundColor Green - - Write-Host "Adding delegation for Microsoft.PowerPlatform/enterprisePolicies to subnet $subnet.Name in vnet $virtualNetworkName" -ForegroundColor Green - $subnet = Add-AzDelegation -Name "Microsoft.PowerPlatform/enterprisePolicies" -ServiceName "Microsoft.PowerPlatform/enterprisePolicies" -Subnet $subnet - Set-AzVirtualNetwork -VirtualNetwork $virtualNetwork - - Write-Host "Added delegation for Microsoft.PowerPlatform/enterprisePolicies to subnet $subnet in vnet $virtualNetworkName" -ForegroundColor Green - - -} -SetupVnetForSubnetDelegation \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/Test-VnetForDelegation.ps1 b/powershell/enterprisePolicies/SubnetInjection/Test-VnetForDelegation.ps1 new file mode 100644 index 00000000..e69de29b diff --git a/powershell/enterprisePolicies/SubnetInjection/Update-SubnetInjectionEnterprisePolicy.ps1 b/powershell/enterprisePolicies/SubnetInjection/Update-SubnetInjectionEnterprisePolicy.ps1 new file mode 100644 index 00000000..62f45254 --- /dev/null +++ b/powershell/enterprisePolicies/SubnetInjection/Update-SubnetInjectionEnterprisePolicy.ps1 @@ -0,0 +1,106 @@ +<# +SAMPLE CODE NOTICE + +THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, +OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. +THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. +NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. +#> + +param( + [Parameter(Mandatory, HelpMessage="The Policy subscription")] + [ValidateNotNullOrEmpty()] + [string]$SubscriptionId, + + [Parameter(Mandatory, HelpMessage="The Policy resource group")] + [ValidateNotNullOrEmpty()] + [string]$ResourceGroup, + + [Parameter(Mandatory, HelpMessage="The Policy name")] + [ValidateNotNullOrEmpty()] + [string]$EnterprisePolicyName, + + [Parameter(Mandatory, HelpMessage="The id of the virtual network that should be updated", ParameterSetName="UpdateVnet")] + [ValidateNotNullOrEmpty()] + [string]$ExistingVnetIdToUpdate, + + [Parameter(Mandatory, HelpMessage="The virtual network Id", ParameterSetName="UpdateVnet")] + [Parameter(Mandatory, HelpMessage="The virtual network Id", ParameterSetName="AddMissingVnet")] + [ValidateNotNullOrEmpty()] + [string]$VnetId, + + [Parameter(Mandatory, HelpMessage="The subnet name", ParameterSetName="UpdateVnet")] + [Parameter(Mandatory, HelpMessage="The subnet name", ParameterSetName="AddMissingVnet")] + [ValidateNotNullOrEmpty()] + [string]$SubnetName, + + [Parameter(ParameterSetName="AddMissingVnet")] + [switch]$AddMissingVnet +) + +$ErrorActionPreference = "Stop" + +Import-Module "$PSScriptRoot\..\Common\EnterprisePolicies" -Force + +if (-not(Connect-Azure)) +{ + return +} + +$policyArmId = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$EnterprisePolicyName" +$policy = Get-EnterprisePolicy -PolicyArmId $policyArmId +if ($null -eq $policy) +{ + Write-Error "Enterprise Policy $policyArmId not found" +} + +$Vnet = Get-Vnet -VnetId $VnetId -EnterprisePolicyLocation $policy.Location +if ($null -eq $Vnet) +{ + Write-Error "There was an issue retrieving or validating the Vnet." +} + +if($AddMissingVnet) +{ + if($policy.properties.networkInjection.virtualNetworks.Count -ge (Get-SupportedVnetRegionsForPowerPlatformRegion).Count) + { + Write-Error "Unable to do add additional vnet as the limit has been reached. If you want to update an existing Vnet don't include the -AddMissingVnet switch." + } + + Write-Host "Adding new vnet with Id [$VnetId] and subnet with name [$SubnetName]" +} +else +{ + if (-not($policy.properties.networkInjection.virtualNetworks | Where-Object { $_.id -eq $ExistingVnetIdToUpdate} )) + { + Write-Error "There is no vnet with id [$ExistingVnetIdToUpdate] in the enterprise policy $EnterprisePolicyName. If you want to add an additional Vnet use the -AddMissingVnet switch." + } + + $policy.properties.networkInjection.virtualNetworks = $policy.properties.networkInjection.virtualNetworks | Where-Object { $_.id -ne $ExistingVnetIdToUpdate} + + if($ExistingVnetIdToUpdate -eq $VnetId) + { + Write-Host "Updating the subnet name [$SubnetName] for vnet with id [$VnetId]" + } + else + { + Write-Host "Replacing vnet [$ExistingVnetIdToUpdate] with new vnet with Id [$VnetId] and subnet with name [$SubnetName]" + } +} + +$policy.properties.networkInjection.virtualNetworks += @{ + "id" = $VnetId + "subnet" = @{ + "name" = $SubnetName + } +} + +$updatedPolicy = Update-EnterprisePolicy -Policy $policy +if ($null -eq $updatedPolicy.ResourceId) +{ + Write-Host "Enterprise Policy not updated" + return +} +$policyString = $updatedPolicy | ConvertTo-Json -Depth 7 +Write-Host "Enterprise Policy updated" +Write-Host $policyString \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/UpdateSubnetInjectionEnterprisePolicy.ps1 b/powershell/enterprisePolicies/SubnetInjection/UpdateSubnetInjectionEnterprisePolicy.ps1 deleted file mode 100644 index d5187e07..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/UpdateSubnetInjectionEnterprisePolicy.ps1 +++ /dev/null @@ -1,138 +0,0 @@ -# Load the environment script -. "$PSScriptRoot\..\Common\EnterprisePolicyOperations.ps1" -. "$PSScriptRoot\ValidateVnetLocationForEnterprisePolicy.ps1" - - -function UpdateSubnetInjectionEnterprisePolicy -{ - param( - [Parameter( - Mandatory=$true, - HelpMessage="The Policy subscription" - )] - [string]$subscriptionId, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy resource group" - )] - [string]$resourceGroup, - - [Parameter( - Mandatory=$true, - HelpMessage="The Policy name" - )] - [string]$enterprisePolicyName, - - [Parameter( - Mandatory=$true, - HelpMessage="Primary virtual network Id, enter N/A if no update is required for this field" - )] - [string]$primaryVnetId, - - [Parameter( - Mandatory=$true, - HelpMessage="Primary subnet name, enter N/A if no update is required for this field" - )] - [string]$primarySubnetName, - - [Parameter( - Mandatory=$true, - HelpMessage="Secondary virtual network Id, enter N/A if no update is required for this field" - )] - [string]$secondaryVnetId, - - [Parameter( - Mandatory=$true, - HelpMessage="Secondary subnet name, enter N/A if no update is required for this field" - )] - [string]$secondarySubnetName - ) - - if ($vnetId -eq "N/A" -and $subnetName -eq "N/A") - { - Write-Host "No change given as input..." -ForegroundColor Green - return - } - - Write-Host "Logging In..." -ForegroundColor Green - $connect = AzureLogin - if ($false -eq $connect) - { - return - } - - Write-Host "Logged In..." -ForegroundColor Green - - $policyArmId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.PowerPlatform/enterprisePolicies/$enterprisePolicyName" - $policy = GetEnterprisePolicy $policyArmId - if ($policy -eq $null) - { - Write-Host "Enterprise Policy $policyArmId not found" -ForegroundColor Red - return - } - if ($primaryVnetId -ne "N/A") - { - Write-Host "Updating primaryVnetId as $primaryVnetId" -ForegroundColor Green - - $primaryVnet = ValidateAndGetVnet -vnetId $primaryVnetId -enterprisePolicylocation $policy.Location - if ($primaryVnet -eq $null) - { - Write-Host "Enterprise Policy not updated" -ForegroundColor Red - return - } - $policy.properties.networkInjection.virtualNetworks[0].id = $primaryVnetId - } - if ($primarySubnetName -ne "N/A") - { - Write-Host "Updating primarySubnetName as $primarySubnetName" -ForegroundColor Green - $policy.properties.networkInjection.virtualNetworks[0].subnet.name = $primarySubnetName - } - - if ($secondaryVnetId -ne "N/A") - { - Write-Host "Updating secondaryVnetId as $secondaryVnetId" -ForegroundColor Green - - $secondaryVnet = ValidateAndGetVnet -vnetId $secondaryVnetId -enterprisePolicylocation $policy.Location - if ($secondaryVnet -eq $null) - { - Write-Host "Enterprise Policy not updated" -ForegroundColor Red - return - } - if ($policy.properties.networkInjection.virtualNetworks.length -lt 2) - { - Write-Host "There is no secondary vnet in enterprise policy $enterprisePolicyName. Adding a new secondaryVnet $secondaryVnetId" -ForegroundColor Green - if ($secondarySubnetName -eq "N/A") - { - Write-Host "As there is no secondary vnet in enterprise policy $enterprisePolicyName, please provide a value for secondarySubnetName. Currently provided value is $secondarySubnetName" -ForegroundColor Red - return - } - $policy.properties.networkInjection.virtualNetworks += @{ - "id" = $secondaryVnetId - "subnet" = @{ - "name" = $secondarySubnetName - } - } - } - else - { - $policy.properties.networkInjection.virtualNetworks[1].id = $secondaryVnetId - } - } - if ($secondarySubnetName -ne "N/A") - { - Write-Host "Updating secondarySubnetName as $secondarySubnetName" -ForegroundColor Green - $policy.properties.networkInjection.virtualNetworks[1].subnet.name = $secondarySubnetName - } - - $updatedPolicy = UpdateEnterprisePolicy $policy - if ($updatedPolicy.ResourceId -eq $null) - { - Write-Host "Enterprise Policy not updated" - return - } - $policyString = $updatedPolicy | ConvertTo-Json -Depth 7 - Write-Host "Enterprise Policy updated" - Write-Host $policyString -} -UpdateSubnetInjectionEnterprisePolicy \ No newline at end of file diff --git a/powershell/enterprisePolicies/SubnetInjection/ValidateVnetLocationForEnterprisePolicy.ps1 b/powershell/enterprisePolicies/SubnetInjection/ValidateVnetLocationForEnterprisePolicy.ps1 deleted file mode 100644 index 5dcd5b8e..00000000 --- a/powershell/enterprisePolicies/SubnetInjection/ValidateVnetLocationForEnterprisePolicy.ps1 +++ /dev/null @@ -1,52 +0,0 @@ -$supportedVnetLocations = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" -$supportedVnetLocations.Add("centraluseuap", "eastus|westus") -$supportedVnetLocations.Add("eastus2euap", "eastus|westus") -$supportedVnetLocations.Add("unitedstateseuap", "eastus|westus") -$supportedVnetLocations.Add("unitedstates", "eastus|westus") -$supportedVnetLocations.Add("southafrica", "southafricanorth|southafricawest") -$supportedVnetLocations.Add("uk", "uksouth|ukwest") -$supportedVnetLocations.Add("japan", "japaneast|japanwest") -$supportedVnetLocations.Add("india", "centralindia|southindia") -$supportedVnetLocations.Add("france", "francecentral|francesouth") -$supportedVnetLocations.Add("europe", "westeurope|northeurope") -$supportedVnetLocations.Add("germany", "germanynorth|germanywestcentral") -$supportedVnetLocations.Add("switzerland", "switzerlandnorth|switzerlandwest") -$supportedVnetLocations.Add("canada", "canadacentral|canadaeast") -$supportedVnetLocations.Add("brazil", "brazilsouth|southcentralus") -$supportedVnetLocations.Add("australia", "australiasoutheast|australiaeast") -$supportedVnetLocations.Add("asia", "eastasia|southeastasia") -$supportedVnetLocations.Add("uae", "uaecentral|uaenorth") -$supportedVnetLocations.Add("korea", "koreasouth|koreacentral") -$supportedVnetLocations.Add("norway", "norwaywest|norwayeast") -$supportedVnetLocations.Add("singapore", "southeastasia") -$supportedVnetLocations.Add("sweden", "swedencentral") - -function ValidateAndGetVnet($vnetId, $enterprisePolicylocation) { - - $vnetResource = Get-AzResource -ResourceId $vnetId - if ($vnetResource.ResourceId -eq $null) - { - Write-Host "Error getting virtual network for $vnetId `n" -ForegroundColor Red - return $null - } - - $vnetLocation = $vnetResource.Location - if ($supportedVnetLocations.ContainsKey($enterprisePolicylocation) -eq $false) - { - Write-Host "The location $enterprisePolicylocation of enterprise policy is not supported`n" -ForegroundColor Red - $supportedEnterprisePolicyLocationsString = $supportedVnetLocations.Keys -join "," - Write-Host "The supported enterprise policy locations are $supportedEnterprisePolicyLocationsString`n" -ForegroundColor Red - return $null - - } - $vnetLocationsAllowed = $supportedVnetLocations[$enterprisePolicylocation].Split("|") - if ($vnetLocationsAllowed.Contains($vnetLocation)) - { - return $vnetResource - } - - Write-Host "The location $vnetLocation of vnet $vnetId is not supported for enterprise policy location $enterprisePolicylocation`n" -ForegroundColor Red - $vnetLocationsAllowedString = $vnetLocationsAllowed -join "," - Write-Host "The supported vnet location for enterprise policy location $enterprisePolicylocation are $vnetLocationsAllowedString`n" -ForegroundColor Red - return $null -} \ No newline at end of file