Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
eriqua committed Sep 21, 2023
2 parents 4990762 + d373237 commit 8ea2de1
Show file tree
Hide file tree
Showing 2 changed files with 318 additions and 11 deletions.
25 changes: 14 additions & 11 deletions avm/res/cognitive-services/account/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,8 @@ param networkAcls object = {}
@description('Optional. Configuration details for private endpoints. For security reasons, it is recommended to use private endpoints whenever possible.')
param privateEndpoints privateEndpointType

@allowed([
''
'CanNotDelete'
'ReadOnly'
])
@description('Optional. Specify the type of lock.')
param lock string = ''
@description('Optional. The lock settings of the service.')
param lock lockType

@description('Optional. Array of role assignment objects that contain the \'roleDefinitionIdOrName\' and \'principalId\' to define RBAC role assignments on this resource. In the roleDefinitionIdOrName attribute, you can provide either the display name of the role definition, or its fully qualified ID in the following format: \'/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11\'.')
param roleAssignments roleAssignmentType
Expand Down Expand Up @@ -236,11 +231,11 @@ resource cognitiveService 'Microsoft.CognitiveServices/accounts@2022-12-01' = {
}
}

resource cognitiveService_lock 'Microsoft.Authorization/locks@2020-05-01' = if (!empty(lock)) {
name: '${cognitiveService.name}-${lock}-lock'
resource cognitiveService_lock 'Microsoft.Authorization/locks@2020-05-01' = if (!empty(lock ?? {}) && lock.?kind != 'None') {
name: lock.?name ?? 'lock-${name}'
properties: {
level: any(lock)
notes: lock == 'CanNotDelete' ? 'Cannot delete resource or child resources.' : 'Cannot modify the resource or child resources.'
level: lock.?kind ?? ''
notes: lock.?kind == 'CanNotDelete' ? 'Cannot delete resource or child resources.' : 'Cannot delete or modify the resource or child resources.'
}
scope: cognitiveService
}
Expand Down Expand Up @@ -465,3 +460,11 @@ type customerManagedKeyType = {
@description('Optional. User assigned identity to use when fetching the customer managed key. Required if no system assigned identity is available for use.')
userAssignedIdentityResourceId: string?
}?

type lockType = {
@description('Optional. Specify the name of lock.')
name: string?

@description('Optional. Specify the type of lock.')
kind: ('CanNotDelete' | 'ReadOnly' | 'None')?
}?
304 changes: 304 additions & 0 deletions avm/utilities/pipelines/tools/Test-ModuleLocally.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
<#
.SYNOPSIS
This function helps with testing a module locally
.DESCRIPTION
This function helps with testing a module locally. Use this function To perform Pester testing for a module and then attempting to deploy it. It also allows you to use your own
subscription Id, principal Id, tenant ID and other parameters that need to be tokenized.
.PARAMETER TemplateFilePath
Mandatory. Path to the Bicep/ARM module that is being tested
.PARAMETER ModuleTestFilePath
Optional. Path to the template file/folder that is to be tested with the template file. Defaults to the module's default '.test' folder. Will be used if the DeploymentTest/ValidationTest switches are set.
.PARAMETER PesterTest
Optional. A switch parameter that triggers a Pester test for the module
.PARAMETER ValidateOrDeployParameters
Optional. An object consisting of the components that are required when using the Validate test or DeploymentTest switch parameter. Mandatory if the DeploymentTest/ValidationTest switches are set.
.PARAMETER DeploymentTest
Optional. A switch parameter that triggers the deployment of the module
.PARAMETER ValidationTest
Optional. A switch parameter that triggers the validation of the module only without deployment
.PARAMETER SkipParameterFileTokens
Optional. A switch parameter that enables you to skip the search for local custom parameter file tokens.
.PARAMETER AdditionalTokens
Optional. A hashtable parameter that contains custom tokens to be replaced in the paramter files for deployment
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
ModuleTestFilePath = 'C:\network\route-table\.test\parameters.json'
PesterTest = $false
DeploymentTest = $false
ValidationTest = $true
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run a Test-Az*Deployment using a specific parameter-template combination with the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
ModuleTestFilePath = 'C:\network\route-table\.test\common\main.test.bicep'
PesterTest = $false
DeploymentTest = $false
ValidationTest = $true
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run a Test-Az*Deployment using a test file with the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
DeploymentTest = $false
ValidationTest = $true
ValidateOrDeployParameters = @{
Location = 'westeurope'
ResourceGroupName = 'validation-rg'
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
RemoveDeployment = $false
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for a given template and a Test-Az*Deployment using each test file in the module's default test folder ('.test') in combination with the template and the provided tokens
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for the given template file
.EXAMPLE
$TestModuleLocallyInput = @{
TemplateFilePath = 'C:\network\route-table\main.bicep'
PesterTest = $true
ValidateOrDeployParameters = @{
SubscriptionId = '00000000-0000-0000-0000-000000000000'
ManagementGroupId = '00000000-0000-0000-0000-000000000000'
}
AdditionalTokens = @{
tenantId = '00000000-0000-0000-0000-000000000000'
}
}
Test-ModuleLocally @TestModuleLocallyInput -Verbose
Run all Pester tests for the given template file including tests for the use of tokens
.NOTES
- Make sure you provide the right information in the 'ValidateOrDeployParameters' parameter for this function to work.
- Ensure you have the ability to perform the deployment operations using your account (if planning to test deploy)
#>
function Test-ModuleLocally {

[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[string] $TemplateFilePath,

[Parameter(Mandatory = $false)]
[string] $ModuleTestFilePath = (Join-Path (Split-Path $TemplateFilePath -Parent) '.test'),

[Parameter(Mandatory = $false)]
[string] $PesterTestFilePath = 'utilities/pipelines/staticValidation/module.tests.ps1',

[Parameter(Mandatory = $false)]
[Psobject] $ValidateOrDeployParameters = @{},

[Parameter(Mandatory = $false)]
[hashtable] $AdditionalTokens = @{},

[Parameter(Mandatory = $false)]
[switch] $PesterTest,

[Parameter(Mandatory = $false)]
[switch] $DeploymentTest,

[Parameter(Mandatory = $false)]
[switch] $ValidationTest
)

begin {
$repoRootPath = (Get-Item $PSScriptRoot).Parent.Parent
$ModuleName = Split-Path (Split-Path $TemplateFilePath -Parent) -Leaf
$utilitiesFolderPath = Split-Path $PSScriptRoot -Parent
Write-Verbose "Running local tests for [$ModuleName]"
# Load Tokens Converter Scripts
. (Join-Path $utilitiesFolderPath 'pipelines' 'tokensReplacement' 'Convert-TokensInFileList.ps1')
# Load Modules Validation / Deployment Scripts
. (Join-Path $utilitiesFolderPath 'pipelines' 'resourceDeployment' 'New-TemplateDeployment.ps1')
. (Join-Path $utilitiesFolderPath 'pipelines' 'resourceDeployment' 'Test-TemplateDeployment.ps1')
}
process {

# Find Test Parameter Files
# -------------------------
if ((Get-Item -Path $ModuleTestFilePath) -is [System.IO.DirectoryInfo]) {
$moduleTestFiles = (Get-ChildItem -Path $ModuleTestFilePath -File).FullName
}
else {
$moduleTestFiles = @($ModuleTestFilePath)
}

# Construct Token Configuration Input
$tokenConfiguration = @{
FilePathList = $moduleTestFiles
Tokens = @{}
TokenPrefix = '#_'
TokenSuffix = '_#'
}

# Add Other Parameter File Tokens (For Testing)
$AdditionalTokens.Keys | ForEach-Object {
$tokenConfiguration.Tokens[$PSItem] = $AdditionalTokens.$PSItem
}

################
# PESTER Tests #
################
if ($PesterTest) {
Write-Verbose "Pester Testing Module: $ModuleName"

# Construct Pester Token Configuration Input
$PesterTokenConfiguration = @{
FilePathList = $moduleTestFiles
Tokens = $enforcedTokenList
TokenPrefix = $GlobalVariablesObject | Select-Object -ExpandProperty tokenPrefix
TokenSuffix = $GlobalVariablesObject | Select-Object -ExpandProperty tokenSuffix
}

try {
Invoke-Pester -Configuration @{
Run = @{
Container = New-PesterContainer -Path (Join-Path $repoRootPath $PesterTestFilePath) -Data @{
repoRootPath = $repoRootPath
moduleFolderPaths = Split-Path $TemplateFilePath -Parent
tokenConfiguration = $PesterTokenConfiguration
}
}
Output = @{
Verbosity = 'Detailed'
}
}
}
catch {
$PSItem.Exception.Message
}
}

#################################
# Validation & Deployment tests #
#################################

if (($ValidationTest -or $DeploymentTest) -and $ValidateOrDeployParameters) {

# Invoke Token Replacement Functionality and Convert Tokens in Parameter Files
$null = Convert-TokensInFileList @tokenConfiguration

# Deployment & Validation Testing
# -------------------------------
$functionInput = @{
TemplateFilePath = $TemplateFilePath
location = $ValidateOrDeployParameters.Location
resourceGroupName = $ValidateOrDeployParameters.ResourceGroupName
subscriptionId = $ValidateOrDeployParameters.SubscriptionId
managementGroupId = $ValidateOrDeployParameters.ManagementGroupId
Verbose = $true
}

try {
# Validate template
# -----------------
if ($ValidationTest) {
# Loop through test files
foreach ($moduleTestFile in $moduleTestFiles) {
Write-Verbose ('Validating module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)) -Verbose
if ((Split-Path $moduleTestFile -Extension) -eq '.json') {
Test-TemplateDeployment @functionInput -ParameterFilePath $moduleTestFile
}
else {
$functionInput['TemplateFilePath'] = $moduleTestFile
Test-TemplateDeployment @functionInput
}
}
}

# Deploy template
# ---------------
if ($DeploymentTest) {
$functionInput['retryLimit'] = 1 # Overwrite default of 3
# Loop through test files
foreach ($moduleTestFile in $moduleTestFiles) {
Write-Verbose ('Deploy Module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)) -Verbose
if ((Split-Path $moduleTestFile -Extension) -eq '.json') {
if ($PSCmdlet.ShouldProcess(('Module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)), 'Deploy')) {
New-TemplateDeployment @functionInput -ParameterFilePath $moduleTestFile
}
}
else {
$functionInput['TemplateFilePath'] = $moduleTestFile
if ($PSCmdlet.ShouldProcess(('Module [{0}] with test file [{1}]' -f $ModuleName, (Split-Path $moduleTestFile -Leaf)), 'Deploy')) {
New-TemplateDeployment @functionInput
}
}
}
}

}
catch {
Write-Error $_
}
finally {
# Restore test files
# ------------------
if (($ValidationTest -or $DeploymentTest) -and $ValidateOrDeployParameters) {
# Replace Values with Tokens For Repo Updates
Write-Verbose 'Restoring Tokens'
$null = Convert-TokensInFileList @tokenConfiguration -SwapValueWithName $true
}
}
}
}
end {
}
}

0 comments on commit 8ea2de1

Please sign in to comment.