зеркало из
1
0
Форкнуть 0

Check parameter default value type matches type #311 (#624)

This commit is contained in:
Bernie White 2021-01-31 20:26:29 +10:00 коммит произвёл GitHub
Родитель 09f58bed02
Коммит 9c19dbef4e
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
14 изменённых файлов: 180 добавлений и 17 удалений

11
.vscode/tasks.json поставляемый
Просмотреть файл

@ -75,16 +75,9 @@
},
{
"label": "Rule docs",
"detail": "Generate rule table of contents.",
"detail": "Generate rule and baseline documentation.",
"type": "shell",
"command": "Invoke-Build BuildRuleDocs",
"problemMatcher": []
},
{
"label": "Baseline docs",
"detail": "Generate baseline documentation.",
"type": "shell",
"command": "Invoke-Build BuildBaselineDocs",
"command": "Invoke-Build BuildDocs",
"problemMatcher": []
},
{

Просмотреть файл

@ -4,6 +4,9 @@
What's changed since pre-release v1.0.0-B2101016:
- New rules:
- All resources:
- Check parameter default value type matches type. [#311](https://github.com/Microsoft/PSRule.Rules.Azure/issues/311)
- General improvements:
- Renamed `Export-AzTemplateRuleData` to `Export-AzRuleTemplateData`. [#596](https://github.com/Microsoft/PSRule.Rules.Azure/issues/596)
- New name `Export-AzRuleTemplateData` aligns with prefix of other cmdlets.

Просмотреть файл

@ -4,7 +4,7 @@ Includes all Azure rules.
## Rules
The following rules are included within `Azure.All`. This baseline includes a total of 186 rules.
The following rules are included within `Azure.All`. This baseline includes a total of 187 rules.
Name | Synopsis | Severity
---- | -------- | --------
@ -150,6 +150,7 @@ Name | Synopsis | Severity
[Azure.Storage.UseEncryption](Azure.Storage.UseEncryption.md) | Storage Service Encryption (SSE) should be enabled. | Important
[Azure.Storage.UseReplication](Azure.Storage.UseReplication.md) | Storage Accounts not using geo-replicated storage (GRS) may be at risk. | Important
[Azure.Template.LocationDefault](Azure.Template.LocationDefault.md) | Set the default value for the location parameter within an ARM template to resource group location. | Awareness
[Azure.Template.ParameterDataTypes](Azure.Template.ParameterDataTypes.md) | Set the parameter default value to a value of the same type. | Important
[Azure.Template.ParameterFile](Azure.Template.ParameterFile.md) | Use ARM template parameter files that are valid. | Important
[Azure.Template.ParameterMetadata](Azure.Template.ParameterMetadata.md) | Set metadata descriptions in Azure Resource Manager (ARM) template for each parameter. | Awareness
[Azure.Template.Resources](Azure.Template.Resources.md) | Each Azure Resource Manager (ARM) template file should deploy at least one resource. | Awareness

Просмотреть файл

@ -4,7 +4,7 @@ Default baseline for Azure rules.
## Rules
The following rules are included within `Azure.Default`. This baseline includes a total of 184 rules.
The following rules are included within `Azure.Default`. This baseline includes a total of 185 rules.
Name | Synopsis | Severity
---- | -------- | --------
@ -148,6 +148,7 @@ Name | Synopsis | Severity
[Azure.Storage.UseEncryption](Azure.Storage.UseEncryption.md) | Storage Service Encryption (SSE) should be enabled. | Important
[Azure.Storage.UseReplication](Azure.Storage.UseReplication.md) | Storage Accounts not using geo-replicated storage (GRS) may be at risk. | Important
[Azure.Template.LocationDefault](Azure.Template.LocationDefault.md) | Set the default value for the location parameter within an ARM template to resource group location. | Awareness
[Azure.Template.ParameterDataTypes](Azure.Template.ParameterDataTypes.md) | Set the parameter default value to a value of the same type. | Important
[Azure.Template.ParameterFile](Azure.Template.ParameterFile.md) | Use ARM template parameter files that are valid. | Important
[Azure.Template.ParameterMetadata](Azure.Template.ParameterMetadata.md) | Set metadata descriptions in Azure Resource Manager (ARM) template for each parameter. | Awareness
[Azure.Template.Resources](Azure.Template.Resources.md) | Each Azure Resource Manager (ARM) template file should deploy at least one resource. | Awareness

Просмотреть файл

@ -4,7 +4,7 @@ Includes Azure features in preview.
## Rules
The following rules are included within `Azure.Preview`. This baseline includes a total of 186 rules.
The following rules are included within `Azure.Preview`. This baseline includes a total of 187 rules.
Name | Synopsis | Severity
---- | -------- | --------
@ -150,6 +150,7 @@ Name | Synopsis | Severity
[Azure.Storage.UseEncryption](Azure.Storage.UseEncryption.md) | Storage Service Encryption (SSE) should be enabled. | Important
[Azure.Storage.UseReplication](Azure.Storage.UseReplication.md) | Storage Accounts not using geo-replicated storage (GRS) may be at risk. | Important
[Azure.Template.LocationDefault](Azure.Template.LocationDefault.md) | Set the default value for the location parameter within an ARM template to resource group location. | Awareness
[Azure.Template.ParameterDataTypes](Azure.Template.ParameterDataTypes.md) | Set the parameter default value to a value of the same type. | Important
[Azure.Template.ParameterFile](Azure.Template.ParameterFile.md) | Use ARM template parameter files that are valid. | Important
[Azure.Template.ParameterMetadata](Azure.Template.ParameterMetadata.md) | Set metadata descriptions in Azure Resource Manager (ARM) template for each parameter. | Awareness
[Azure.Template.Resources](Azure.Template.Resources.md) | Each Azure Resource Manager (ARM) template file should deploy at least one resource. | Awareness

Просмотреть файл

@ -3,7 +3,7 @@ severity: Awareness
pillar: Reliability
category: Resource deployment
resource: All resources
online version: https://github.com/Microsoft/PSRule.Rules.Azure/blob/main/docs/rules/en/Azure.Template.Location.md
online version: https://github.com/Microsoft/PSRule.Rules.Azure/blob/main/docs/rules/en/Azure.Template.LocationDefault.md
---
# Default to resource group location

Просмотреть файл

@ -0,0 +1,64 @@
---
severity: Important
pillar: Reliability
category: Resource deployment
resource: All resources
online version: https://github.com/Microsoft/PSRule.Rules.Azure/blob/main/docs/rules/en/Azure.Template.ParameterDataTypes.md
---
# Default should match type
## SYNOPSIS
Set the parameter default value to a value of the same type.
## DESCRIPTION
Azure Resource Manager (ARM) template support parameters with a range of types, including:
- `bool`
- `int`
- `string`
- `array`
- `object`
- `secureString`
- `secureObject`
When including a `defaultValue`, the default value should match the same type at the `type` property.
For example:
```json
{
"boolParam": {
"type": "bool",
"defaultValue": false
},
"intParam": {
"type": "int",
"defaultValue": 5
},
"stringParam": {
"type": "string",
"defaultValue": "test-rg"
},
"arrayParam": {
"type": "array",
"defaultValue": [ 1, 2, 3 ]
},
"objectParam": {
"type": "object",
"defaultValue": {
"one": "a",
"two": "b"
}
}
}
```
## RECOMMENDATION
Consider updating the parameter default value to a value of the same type.
## LINKS
- [Data types](https://docs.microsoft.com/azure/azure-resource-manager/templates/template-syntax#data-types)

Просмотреть файл

@ -180,6 +180,7 @@ Name | Synopsis | Severity
Name | Synopsis | Severity
---- | -------- | --------
[Azure.Template.LocationDefault](Azure.Template.LocationDefault.md) | Set the default value for the location parameter within an ARM template to resource group location. | Awareness
[Azure.Template.ParameterDataTypes](Azure.Template.ParameterDataTypes.md) | Set the parameter default value to a value of the same type. | Important
## Security

Просмотреть файл

@ -11,6 +11,7 @@ Name | Synopsis | Severity
[Azure.Resource.AllowedRegions](Azure.Resource.AllowedRegions.md) | Resources should be deployed to allowed regions. | Awareness
[Azure.Resource.UseTags](Azure.Resource.UseTags.md) | Azure resources should be tagged using a standard convention. | Awareness
[Azure.Template.LocationDefault](Azure.Template.LocationDefault.md) | Set the default value for the location parameter within an ARM template to resource group location. | Awareness
[Azure.Template.ParameterDataTypes](Azure.Template.ParameterDataTypes.md) | Set the parameter default value to a value of the same type. | Important
[Azure.Template.ParameterFile](Azure.Template.ParameterFile.md) | Use ARM template parameter files that are valid. | Important
[Azure.Template.ParameterMetadata](Azure.Template.ParameterMetadata.md) | Set metadata descriptions in Azure Resource Manager (ARM) template for each parameter. | Awareness
[Azure.Template.Resources](Azure.Template.Resources.md) | Each Azure Resource Manager (ARM) template file should deploy at least one resource. | Awareness

Просмотреть файл

@ -310,6 +310,9 @@ task Analyze Build, PSScriptAnalyzer, {
Invoke-ScriptAnalyzer -Path out/modules/PSRule.Rules.Azure;
}
# Synopsis: Build documentation
task BuildDocs BuildRuleDocs, BuildBaselineDocs
# Synopsis: Build table of content for rules
task BuildRuleDocs Build, PSRule, PSDocs, {
Import-Module (Join-Path -Path $PWD -ChildPath out/modules/PSRule.Rules.Azure) -Force;

Просмотреть файл

@ -38,4 +38,5 @@
AssessmentUnhealthy = "An assessment is reporting one or more issues."
AssessmentNotFound = "The results for a valid assessment was not found."
HealthProbeNotDedicated = "The health probe '{0}' used the default path '/'."
ParameterDefaultTypeMismatch = "The default value for '{0}' is not {1}."
}

Просмотреть файл

@ -93,6 +93,45 @@ Rule 'Azure.Template.LocationDefault' -Type 'System.IO.FileInfo','.json' -If { (
}
}
# Synopsis: Set the parameter default value to a value of the same type.
Rule 'Azure.Template.ParameterDataTypes' -Type 'System.IO.FileInfo','.json' -If { (IsTemplateFile) } -Tag @{ release = 'GA'; ruleSet = '2021_03'; } {
$jsonObject = $PSRule.GetContent([System.IO.FileInfo]$TargetObject.FullName);
$parameters = @($jsonObject.parameters.PSObject.Properties);
if ($parameters.Length -eq 0) {
return $Assert.Pass();
}
foreach ($parameter in $parameters) {
if (!$Assert.HasField($parameter.Value, 'defaultValue').Result) {
# No defaultValue
$Assert.Pass();
}
elseif ($parameter.Value.defaultValue -is [string] -and $parameter.Value.defaultValue.StartsWith('[') -and $parameter.Value.defaultValue.EndsWith(']')) {
# Is function
$Assert.Pass();
}
elseif ($parameter.Value.type -eq 'bool') {
Write-Debug -Message "Parameter default value is '$($parameter.Value.defaultValue.GetType().Name)'";
$Assert.Create($parameter.Value.defaultValue -is [bool], ($LocalizedData.ParameterDefaultTypeMismatch -f $parameter.Name, $parameter.Value.type));
}
elseif ($parameter.Value.type -eq 'int') {
Write-Debug -Message "Parameter default value is '$($parameter.Value.defaultValue.GetType().Name)'";
$Assert.Create($parameter.Value.defaultValue -is [int] -or $parameter.Value.defaultValue -is [long], ($LocalizedData.ParameterDefaultTypeMismatch -f $parameter.Name, $parameter.Value.type));
}
elseif ($parameter.Value.type -eq 'array') {
Write-Debug -Message "Parameter default value is '$($parameter.Value.defaultValue.GetType().Name)'";
$Assert.Create($parameter.Value.defaultValue -is [array], ($LocalizedData.ParameterDefaultTypeMismatch -f $parameter.Name, $parameter.Value.type));
}
elseif ($parameter.Value.type -eq 'string' -or $parameter.Value.type -eq 'secureString') {
Write-Debug -Message "Parameter default value is '$($parameter.Value.defaultValue.GetType().Name)'";
$Assert.Create($parameter.Value.defaultValue -is [string], ($LocalizedData.ParameterDefaultTypeMismatch -f $parameter.Name, $parameter.Value.type));
}
elseif ($parameter.Value.type -eq 'object' -or $parameter.Value.type -eq 'secureObject') {
Write-Debug -Message "Parameter default value is '$($parameter.Value.defaultValue.GetType().Name)'";
$Assert.Create($parameter.Value.defaultValue -is [PSObject], ($LocalizedData.ParameterDefaultTypeMismatch -f $parameter.Name, $parameter.Value.type));
}
}
}
#endregion Template
#region Parameters

Просмотреть файл

@ -6,9 +6,7 @@
#
[CmdletBinding()]
param (
)
param ()
# Setup error handling
$ErrorActionPreference = 'Stop';
@ -31,6 +29,7 @@ Describe 'Azure.Template' -Tag 'Template' {
WarningAction = 'SilentlyContinue'
ErrorAction = 'Stop'
}
It 'Azure.Template.TemplateFile' {
$dataPath = Join-Path -Path $here -ChildPath 'Resources.Template*.json';
$result = Get-Item -Path $dataPath | Invoke-PSRule @invokeParams -Name 'Azure.Template.TemplateFile';
@ -117,7 +116,7 @@ Describe 'Azure.Template' -Tag 'Template' {
$ruleResult.Length | Should -Be 1;
$ruleResult.TargetName | Should -BeLike "*Resources.Empty.Template.json";
$ruleResult.Reason | Should -BeLike "The parameter '*' was not used within the template.";
$ruleResult.Reason.Length | Should -Be 4;
$ruleResult.Reason.Length | Should -Be 11;
# Pass
$ruleResult = @($filteredResult | Where-Object { $_.Outcome -eq 'Pass' });
@ -183,6 +182,34 @@ Describe 'Azure.Template' -Tag 'Template' {
$targetNames | Should -BeIn 'Resources.Template3.json';
}
It 'Azure.Template.ParameterDataTypes' {
$dataPath = @(
(Join-Path -Path $here -ChildPath 'Resources.Empty.Template.json')
(Join-Path -Path $here -ChildPath 'Resources.Template3.json')
(Join-Path -Path $here -ChildPath 'Resources.Template4.json')
);
$result = Invoke-PSRule @invokeParams -InputPath $dataPath -Outcome All -Format None -Name 'Azure.Template.ParameterDataTypes';
$filteredResult = $result | Where-Object { $_.RuleName -eq 'Azure.Template.ParameterDataTypes' };
# Fail
$ruleResult = @($filteredResult | Where-Object { $_.Outcome -eq 'Fail' });
$ruleResult | Should -Not -BeNullOrEmpty;
$ruleResult.Length | Should -Be 1;
$targetNames = $ruleResult | ForEach-Object { $_.TargetName.Split([char[]]@('\', '/'))[-1] };
$targetNames | Should -BeIn 'Resources.Empty.Template.json';
$ruleResult[0].Reason.Length | Should -Be 3;
$ruleResult[0].Reason[0] | Should -BeLike "The default value for 'notStringParam' is not string.";
$ruleResult[0].Reason[1] | Should -BeLike "The default value for 'notBoolParam' is not bool.";
$ruleResult[0].Reason[2] | Should -BeLike "The default value for 'notArrayParam' is not array.";
# Pass
$ruleResult = @($filteredResult | Where-Object { $_.Outcome -eq 'Pass' });
$ruleResult | Should -Not -BeNullOrEmpty;
$ruleResult.Length | Should -Be 2;
$targetNames = $ruleResult | ForEach-Object { $_.TargetName.Split([char[]]@('\', '/'))[-1] };
$targetNames | Should -BeIn 'Resources.Template3.json', 'Resources.Template4.json';
}
It 'Azure.Template.ParameterFile' {
$dataPath = Join-Path -Path $here -ChildPath 'Resources.Parameters*.json';
$result = Get-Item -Path $dataPath | Invoke-PSRule @invokeParams -Name 'Azure.Template.ParameterFile';

Просмотреть файл

@ -36,6 +36,34 @@
"metadata": {
"description": "A location to deploy resources."
}
},
"notStringParam": {
"type": "string",
"defaultValue": 0
},
"notBoolParam": {
"type": "bool",
"defaultValue": 0
},
"intParam": {
"type": "int",
"defaultValue": 0
},
"arrayParam": {
"type": "array",
"defaultValue": []
},
"arrayParamFn": {
"type": "array",
"defaultValue": "[createArray('a', 'b', 'c')]"
},
"notArrayParam": {
"type": "array",
"defaultValue": ""
},
"objectParam": {
"type": "object",
"defaultValue": {}
}
},
"variables": {