### Install Dependencies for PowerShell Gallery Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Installs the NuGet package provider and the PowerShellGet module if they are not already installed or meet the minimum version requirements. ```powershell # Install dependencies for connecting to PowerShell Gallery if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Force -Scope CurrentUser; } if ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction SilentlyContinue)) { Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber; } ``` -------------------------------- ### PSRule Configuration Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md An example of a PSRule configuration file (ps-rule.yaml) that sets various options. ```yaml # PSRule example configuration # # Configures the repository repository: url: https://github.com/microsoft/PSRule baseRef: main # Configure required module versions requires: PSRule.Rules.Azure: '>=1.1.0' # Configure convention options convention: include: - 'Convention1' # Configure execution options execution: hashAlgorithm: SHA256 duplicateResourceId: Warn languageMode: ConstrainedLanguage suppressionGroupExpired: Error restrictScriptSource: ModuleOnly # Configure include options include: module: - 'PSRule.Rules.Azure' path: [ ] # Configures input options input: format: Yaml ignoreGitPath: false ignoreObjectSource: true ignoreRepositoryCommon: false ignoreUnchangedPath: true objectPath: items pathIgnore: - '*.Designer.cs' targetType: - Microsoft.Compute/virtualMachines - Microsoft.Network/virtualNetworks # Configures outcome logging options logging: limitDebug: - Rule1 - Rule2 limitVerbose: - Rule1 - Rule2 ruleFail: Error rulePass: Information output: as: Summary banner: Minimal csvDetailedColumns: - RuleName - TargetName - Outcome - Synopsis culture: - en-US encoding: UTF8 footer: RuleCount format: Json jobSummaryPath: reports/summary.md outcome: Fail sarifProblemsOnly: false style: GitHubActions # Overrides the severity level for rules override: level: Rule1: Error Rule2: Warning # Configure rule suppression suppression: storageAccounts.UseHttps: targetName: - TestObject1 - TestObject3 # Configure baseline options binding: field: id: - ResourceId - AlternativeId ignoreCase: false nameSeparator: '::' targetName: - ResourceName - AlternateName targetType: - ResourceType - kind useQualifiedName: true configuration: appServiceMinInstanceCount: 2 rule: include: - rule1 - rule2 includeLocal: true exclude: - rule3 - rule4 tag: severity: - Critical - Warning ``` -------------------------------- ### Example YAML Baselines Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Baseline.md Two example YAML baselines demonstrating rule inclusion and configuration of allowed locations. ```yaml --- # Synopsis: This is an example baseline apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Baseline metadata: name: Baseline1 spec: rule: include: - Rule1 - Rule2 configuration: allowedLocations: - 'Australia East' - 'Australia South East' --- # Synopsis: This is an example baseline apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Baseline metadata: name: Baseline2 spec: rule: include: - Rule1 - Rule3 configuration: allowedLocations: - 'Australia East' ``` -------------------------------- ### Example JSON Baselines Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Baseline.md Two example JSON baselines demonstrating rule inclusion and configuration of allowed locations. ```json [ { // Synopsis: This is an example baseline "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Baseline", "metadata": { "name": "Baseline1" }, "spec": { "rule": { "include": [ "Rule1", "Rule2" ] }, "configuration": { "allowedLocations": [ "Australia East", "Australia South East" ] } } }, { // Synopsis: This is an example baseline "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Baseline", "metadata": { "name": "Baseline2" }, "spec": { "rule": { "include": [ "Rule1", "Rule3" ] }, "configuration": { "allowedLocations": [ "Australia East" ] } } } ] ``` -------------------------------- ### Install PSRule Tool Source: https://github.com/microsoft/psrule/blob/main/src/PSRule.CommandLine/README.md Installs the PSRule command-line tool globally. ```shell dotnet install tool -g Microsoft.PSRule.Tool ``` -------------------------------- ### Install PSRule as a Global .NET Tool Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Install PSRule as a global tool using the .NET CLI. This is useful for installing PSRule on CI workers that do not natively support PowerShell. ```bash dotnet tool install -g Microsoft.PSRule.Tool ``` -------------------------------- ### Azure DevOps Pipeline Steps Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md An example of Azure DevOps pipeline steps that install dependencies, validate files using PSRule, and publish the test results. ```yaml steps: # Install dependencies - powershell: ./pipeline-deps.ps1 displayName: 'Install dependencies' # Validate templates - powershell: ./validate-files.ps1 displayName: 'Validate files' # Publish pipeline results - task: PublishTestResults@2 displayName: 'Publish PSRule results' inputs: testRunTitle: 'PSRule' testRunner: NUnit testResultsFiles: 'reports/rule-report.xml' mergeTestResults: true publishRunAttachments: true condition: succeededOrFailed() ``` -------------------------------- ### Rule with Recommend and Condition Example Source: https://github.com/microsoft/psrule/blob/main/docs/keywords/PSRule/en-US/about_PSRule_Keywords.md This example shows a rule that recommends using at least two instances for App Service Plans and checks if the current capacity meets this requirement. ```powershell # Synopsis: App Service Plan has multiple instances Rule 'appServicePlan.MinInstanceCount' -If { $TargetObject.ResourceType -eq 'Microsoft.Web/serverfarms' } { Recommend 'Use at least two (2) instances' $TargetObject.Sku.capacity -ge 2 } ``` -------------------------------- ### Install NuGet and PowerShellGet Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Installs the NuGet package provider and PowerShellGet module. These may be required to connect to the PowerShell Gallery. ```powershell Install-PackageProvider -Name NuGet -Scope CurrentUser -Force; Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber; ``` -------------------------------- ### PSRule Rule Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md An example of a PSRule rule that checks for the 'app.kubernetes.io/name' label on Deployments and Services. ```powershell Rule 'metadata.Name' -Type 'Deployment', 'Service' { Recommend $LocalizedData.RecommendNameLabel Exists "metadata.labels.'app.kubernetes.io/name'" # $LocalizedData.ReasonLabelMissing is set to 'The standard {0} label is not set.'. Reason ($LocalizedData.ReasonLabelMissing -f 'name') } ``` -------------------------------- ### Example YAML output from PSRule Source: https://github.com/microsoft/psrule/blob/main/docs/analysis-output.md An example of PSRule results serialized in YAML format. ```yaml - data: {} info: displayName: Local.PS.RequireTLS name: Local.PS.RequireTLS synopsis: An example rule to require TLS. level: Error outcome: Fail outcomeReason: Processed reason: - The field 'configure.supportsHttpsTrafficOnly' is set to 'False'. - The field 'configure.minTLSVersion' does not exist. ruleName: Local.PS.RequireTLS runId: 16b0534165ffb5279beeb1672a251fc1ff3124b6 source: - file: C:\Dev\Workspace\PSRule\docs\authoring\writing-rules\settings.json line: 2 position: 11 type: File targetName: 1fe7c0f476b11301402d5017d87424c36ff085a8 targetType: app1 time: 0 ``` -------------------------------- ### Install Specific Version of PSRule as Global .NET Tool Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Install a specific version of PSRule as a global tool using the .NET CLI. This allows for precise version control in your installations. ```bash dotnet tool install -g Microsoft.PSRule.Tool --version 3.0.0-B0203 ``` -------------------------------- ### Install NuGet Package Provider for Windows PowerShell Source: https://github.com/microsoft/psrule/blob/main/docs/troubleshooting.md Installs the NuGet package provider if it's not already present. Required for installing and checking module versions in non-interactive environments. ```powershell if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction Ignore)) { Install-PackageProvider -Name NuGet -Force -Scope CurrentUser; } ``` -------------------------------- ### Module File Structure Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Example directory structure for rules included in a module, showing culture-specific documentation within the module's structure, alongside the rule files and module manifest. ```text - Kubernetes.Rules/ - en/ - metadata.Name.md - en-US/ - metadata.Name.md - fr-FR/ - metadata.Name.md - rules/ - kubernetes.Rule.ps1 - Kubernetes.Rules.psd1 ``` -------------------------------- ### Example Selector Definition Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Selectors.md An example of a selector defined in a Selectors.Rule.yaml file. ```yaml # Example Selectors.Rule.yaml --- ``` -------------------------------- ### Install Pre-release PSRule for Current User Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Installs a pre-release version of PSRule for the current user. Ensure PowerShellGet is up-to-date. ```powershell Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser -AllowPrerelease ``` -------------------------------- ### Markdown Front Matter Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md An example of front matter annotations in a markdown help file, including the 'online version' annotation. ```yaml --- online version: https://github.com/microsoft/PSRule/blob/main/docs/scenarios/rule-docs/rule-docs.md --- ``` -------------------------------- ### Loose File Structure Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Example directory structure for loose rule files, showing culture-specific documentation in subdirectories alongside the rule file. ```text - .ps-rule/ - en/ - metadata.Name.md - en-US/ - metadata.Name.md - fr-FR/ - metadata.Name.md - kubernetes.Rule.ps1 ``` -------------------------------- ### Install PSRule and Validate Files Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Installs the PSRule module if necessary and then validates files using Assert-PSRule with specified parameters, including output format and path. ```powershell # Install PSRule module if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) { Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force; } # Validate files $assertParams = @{ Path = './.ps-rule/' Style = 'AzurePipelines' OutputFormat = 'NUnit3' OutputPath = 'reports/rule-report.xml' } $items = Get-ChildItem -Recurse -Path .\src\,\.\tests\ -Include *.ps1,*.psd1,*.psm1,*.yaml; $items | Assert-PSRule $assertParams -ErrorAction Stop; ``` -------------------------------- ### Markdown Synopsis Section Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Example of the SYNOPSIS section in a markdown help file. ```markdown ## SYNOPSIS Deployments and services must use the app.kubernetes.io/name label. ``` -------------------------------- ### Enable JSON and YAML formats Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/cli/run.md Example of enabling multiple formats for processing files and deserialized objects. ```bash --formats json yaml ``` -------------------------------- ### Get Specific Rule Help Source: https://github.com/microsoft/psrule/blob/main/docs/commands/PSRule/en-US/Get-PSRuleHelp.md Get rule documentation for the rule Azure.ACR.AdminUser. ```powershell Get-PSRuleHelp Azure.ACR.AdminUser; ``` -------------------------------- ### Install PSRule with dependency checks Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Installs PSRule and its dependencies (NuGet and PowerShellGet) with checks to avoid reinstallation. Ensures PSRule version 2.1.0 or higher is installed. ```powershell if ($Null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Scope CurrentUser -Force; } if ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion '2.2.1' -ErrorAction Ignore)) { Install-Module PowerShellGet -MinimumVersion '2.2.1' -Scope CurrentUser -Force -AllowClobber; } if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) { Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force; } ``` -------------------------------- ### YAML Rule Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Rules.md An example of a PSRule rule defined in YAML that checks for a standard load-balancer SKU on AKS clusters. ```yaml --- # Synopsis: Use a Standard load-balancer with AKS clusters. apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Rule metadata: name: 'Azure.AKS.StandardLB' tags: release: 'GA' ruleSet: '2020_06' spec: type: - Microsoft.ContainerService/managedClusters condition: field: 'Properties.networkProfile.loadBalancerSku' equals: 'standard' ``` -------------------------------- ### Install Pre-release PSRule for All Users Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Installs a pre-release version of PSRule for all users, requiring administrator or root permissions. Ensure PowerShellGet is up-to-date. ```powershell Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force Install-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers -AllowPrerelease ``` -------------------------------- ### JSON Rule Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Rules.md An example of a PSRule rule defined in JSON that checks for a standard load-balancer SKU on AKS clusters. ```jsonc [ { // Synopsis: Use a Standard load-balancer with AKS clusters. "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Rule", "metadata": { "name": "Azure.AKS.StandardLB", "tags": { "release": "GA", "ruleSet": "2020_06" } }, "spec": { "type": [ "Microsoft.ContainerService/managedClusters" ], "condition": { "field": "Properties.networkProfile.loadBalancerSku", "equals": "standard" } } } ] ``` -------------------------------- ### Install PSRule GitHub Action (Latest Stable) Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Use this action to install the latest stable version of PSRule in GitHub Actions. This will always use the most recent release. ```yaml - name: Analyze with PSRule uses: microsoft/ps-rule@latest ``` -------------------------------- ### Install PSRule for Current User Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Installs the PSRule module for the current user from the PowerShell Gallery. ```powershell Install-Module -Name 'PSRule' -Repository PSGallery -Scope CurrentUser ``` -------------------------------- ### Markdown Description Section Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Example of the DESCRIPTION section in a markdown help file, demonstrating paragraph separation. ```markdown ## DESCRIPTION Kubernetes defines a common set of labels that are recommended for tool interoperability. These labels should be used to consistently apply standard metadata. The `app.kubernetes.io/name` label should be used to specify the name of the application. ``` -------------------------------- ### Get PSRule Help Source: https://github.com/microsoft/psrule/blob/main/docs/commands/PSRule/en-US/Get-PSRuleHelp.md Get a list of rule help within the current path or loaded modules. ```powershell Get-PSRuleHelp; ``` -------------------------------- ### Example PSRule Selectors in JSONC Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Selectors.md This JSONC array demonstrates multiple PSRule selector definitions. ```jsonc // Example Selectors.Rule.jsonc [ { // Synopsis: Require the CustomValue field. "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Selector", "metadata": { "name": "RequireCustomValue" }, "spec": { "if": { "field": "CustomValue", "exists": true } } }, { // Synopsis: Require a Name or AlternativeName. "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Selector", "metadata": { "name": "RequireName" }, "spec": { "if": { "anyOf": [ { "field": "AlternateName", "exists": true }, { "field": "Name", "exists": true } ] } } }, { // Synopsis: Require a specific CustomValue "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Selector", "metadata": { "name": "RequireSpecificCustomValue" }, "spec": { "if": { "field": "CustomValue", "in": [ "Value1", "Value2" ] } } } ] ``` -------------------------------- ### Install PSRule GitHub Action (Specific Version) Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Use this action to install a specific version of PSRule in GitHub Actions. Pinning to a specific version is recommended to prevent breaking changes. ```yaml - name: Analyze with PSRule uses: microsoft/ps-rule@v2.9.0 ``` -------------------------------- ### APIVersion Assertion Examples Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Assert.md Demonstrates using the APIVersion assertion to validate date versions of a field. Includes examples for checking stable versions, including pre-releases, and applying version constraints. ```powershell Rule 'ValidStableAPIVersion' { $Assert.APIVersion($TargetObject, 'apiVersion') } ``` ```powershell Rule 'AnyValidAPIVersion' { $Assert.APIVersion($TargetObject, 'apiVersion', '', $True) } ``` ```powershell Rule 'MinimumAPIVersion' { $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01') } ``` ```powershell Rule 'MinimumAPIVersionWithPrerelease' { $Assert.APIVersion($TargetObject, 'apiVersion', '>=2015-10-01-0', $True) } ``` ```powershell Rule 'MinimumAPIVersionWithFlag' { $Assert.APIVersion($TargetObject, 'apiVersion', '@pre >=2015-10-01-0') } ``` -------------------------------- ### Object with nested resources (JSON) Source: https://github.com/microsoft/psrule/blob/main/docs/expressions/sub-selectors.md Example of an object with a nested 'resources' array, each containing 'properties', in JSON format. ```json { "name": "app1", "type": "Microsoft.Web/sites", "resources": [ { "name": "web", "type": "Microsoft.Web/sites/config", "properties": { "detailedErrorLoggingEnabled": true } } ] } ``` -------------------------------- ### Example JSON output from PSRule with 2 spaces indentation Source: https://github.com/microsoft/psrule/blob/main/docs/analysis-output.md An example of PSRule results serialized in JSON format with 2 spaces indentation. ```yaml [ { "data": {}, "info": { "displayName": "Local.PS.RequireTLS", "name": "Local.PS.RequireTLS", "synopsis": "An example rule to require TLS." }, "level": 1, "outcome": "Fail", "outcomeReason": "Processed", "reason": [ "The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.", "The field 'configure.minTLSVersion' does not exist." ], "ruleName": "Local.PS.RequireTLS", "runId": "3afadfed32e57f5283ad71c1aa496da822ff0c84", "source": [ { "file": "C:\\Dev\\Workspace\\PSRule\\docs\\authoring\\writing-rules\\settings.json", "line": 2, "position": 11, "type": "File" } ], "targetName": "1fe7c0f476b11301402d5017d87424c36ff085a8", "targetType": "app1", "time": 0 } ] ``` -------------------------------- ### Show PSRule CLI Version Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/cli/index.md Displays the installed version of the PSRule CLI. ```bash ps-rule --version ``` -------------------------------- ### PSRule Module Lock File Example Source: https://github.com/microsoft/psrule/blob/main/docs/updates/v3.0.md An example of the ps-rule.lock.json file used to manage module versions. This file pins modules to specific versions for reproducible builds. When present, PSRule uses these versions instead of the latest available. ```json { "version": 1, "modules": { "PSRule.Rules.MSFT.OSS": { "version": "1.1.0", "integrity": "sha512-4oEbkAT3VIQQlrDUOpB9qKkbNU5BMktvkDCriws4LgCMUiyUoYMcN0XovljAIW4FO0cmP7mP6A8Z7MPNGlgK7Q==" } } } ``` -------------------------------- ### Install PSRule GitHub Action (Latest Stable v2) Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Use this action to install the latest stable v2 version of PSRule in GitHub Actions. This ensures compatibility within the v2 release line. ```yaml - name: Analyze with PSRule uses: microsoft/ps-rule@v2 ``` -------------------------------- ### notStartsWith Expression Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Expressions.md The notStartsWith condition checks if an operand does not start with a specified string. This example shows how to use notStartsWith with a single string and an array of strings. ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Rule metadata: name: 'ExampleNotStartsWith' spec: condition: anyOf: - field: 'url' notStartsWith: 'http' - field: 'url' notStartsWith: - 'http://' - 'https://' ``` ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: 'ExampleNotStartsWith' spec: if: anyOf: - field: 'url' notStartsWith: 'http' - field: 'url' notStartsWith: - 'http://' - 'https://' ``` -------------------------------- ### Object with nested resources Source: https://github.com/microsoft/psrule/blob/main/docs/expressions/sub-selectors.md Example of an object with a nested 'resources' array, each containing 'properties'. ```yaml name: app1 type: Microsoft.Web/sites resources: - name: web type: Microsoft.Web/sites/config properties: detailedErrorLoggingEnabled: true ``` -------------------------------- ### StartsWith Expression Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Expressions.md Use the startsWith expression to check if an operand starts with a specified string. Supports case-sensitive comparison and type conversion. ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Rule metadata: name: 'ExampleStartsWith' spec: condition: anyOf: - field: 'url' startsWith: 'http' - field: 'url' startsWith: - 'http://' - 'https://' --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: 'ExampleStartsWith' spec: if: anyOf: - field: 'url' startsWith: 'http' - field: 'url' startsWith: - 'http://' - 'https://' ``` -------------------------------- ### Example Baseline with Rules and Configuration (JSON) Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Baseline.md Defines two PSRule baselines, TestBaseline1 and TestBaseline2, in JSON format. Each baseline includes rules to include and configuration settings. ```json [ { // Synopsis: This is an example baseline "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Baseline", "metadata": { "name": "TestBaseline1" }, "spec": { "rule": { "include": [ "WithBaseline" ] }, "configuration": { "key1": "value1" } } }, { // Synopsis: This is an example baseline "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "Baseline", "metadata": { "name": "TestBaseline2" }, "spec": { "rule": { "include": [ "WithBaseline" ] }, "configuration": { "key1": "value1" } } } ] ``` -------------------------------- ### Calling PSRule from Pester Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Use Invoke-PSRule within Pester tests to get validation results that can be asserted against. This example shows how to configure Invoke-PSRule with paths, output format, and output path, then asserts that no failures or errors occurred. ```powershell Describe 'Azure' { Context 'Resource templates' { It 'Use content rules' { $invokeParams = @{ Path = './.ps-rule/' OutputFormat = 'NUnit3' OutputPath = 'reports/rule-report.xml' } $items = Get-ChildItem -Recurse -Path.\src\,\tests\ -Include *.ps1,*.psd1,*.psm1,*.yaml; Invoke-PSRule @invokeParams -Outcome Fail,Error | Should -BeNullOrEmpty; } } } ``` -------------------------------- ### Install Latest PowerShellGet Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Installs the latest version of the PowerShellGet module for the current user. This may be required for installing pre-release module versions. ```powershell # Install the latest PowerShellGet version Install-Module -Name PowerShellGet -Repository PSGallery -Scope CurrentUser -Force ``` -------------------------------- ### Example Baseline with Rules and Configuration (YAML) Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Baseline.md Defines a PSRule baseline named TestBaseline1. Includes specific rules and custom configuration. ```yaml --- # Synopsis: This is an example baseline apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Baseline metadata: name: TestBaseline1 spec: rule: include: - 'WithBaseline' configuration: key1: value1 --- # Synopsis: This is an example baseline apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Baseline metadata: name: TestBaseline2 spec: rule: include: - 'WithBaseline' configuration: key1: value1 ``` -------------------------------- ### Example of pre-filtering with Where-Object Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Demonstrates pre-filtering objects using Where-Object before invoking PSRule. Only objects matching the condition are processed. ```powershell # Define objects to validate $items = @(); $items += [PSCustomObject]@{ Name = 'Fridge'; Type = 'Equipment'; Category = 'White goods'; }; $items += [PSCustomObject]@{ Name = 'Apple'; Type = 'Food'; Category = 'Produce'; }; $items += [PSCustomObject]@{ Name = 'Carrot'; Type = 'Food'; Category = 'Produce'; }; # Example of pre-filtering, only food items are sent to Invoke-PSRule $items | Where-Object { $_.Type -eq 'Food' } | Invoke-PSRule; ``` -------------------------------- ### Using YAML for PSRule Options Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Shows how to define PSRule options in a YAML formatted file. This allows for repeatable configurations to be loaded from disk. ```yaml output: format: Yaml ``` -------------------------------- ### Configure PSRule with Hashtable Source: https://github.com/microsoft/psrule/blob/main/docs/faq.md Configure PSRule cmdlets at runtime using a hashtable. This example sets output format, culture, and unprocessed object handling. ```powershell # With hashtable $items | Assert-PSRule -Option @{ 'Output.As' = 'Summary' 'Output.Culture' = 'en-AU' 'Execution.UnprocessedObject' = 'Ignore' 'Configuration.CUSTOM_VALUE' = 'Example' } ``` -------------------------------- ### Sample settings.json for testing Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/testing-infrastructure.md This JSON file represents a sample application configuration used for testing IaC rules. It includes settings for application type, version, and security configurations like `supportsHttpsTrafficOnly`. ```json { "type": "app1", "version": 1, "configure": { "supportsHttpsTrafficOnly": false } } ``` -------------------------------- ### Creating a PSRule Options File Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Shows how to use the `New-PSRuleOption` cmdlet to create a PSRule options file, specifying the path for the YAML file. ```powershell New-PSRuleOption -Path '.\myconfig.yaml'; ``` -------------------------------- ### Configure PSRule with YAML Source: https://github.com/microsoft/psrule/blob/main/docs/faq.md Configure PSRule using a YAML file. This example sets output format, culture, and unprocessed object handling. ```yaml # With YAML output: as: Summary culture: [ 'en-AU' ] execution: unprocessedObject: Ignore configuration: CUSTOM_VALUE: Example ``` -------------------------------- ### PSRule Rule Definition Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Docs.md Example of a PSRule rule definition with a synopsis comment. ```powershell # Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB Rule 'storageAccounts.UseHttps' -If { ResourceType 'Microsoft.Storage/storageAccounts' } { Recommend 'Storage accounts should only allow secure traffic' $TargetObject.Properties.supportsHttpsTrafficOnly } ``` -------------------------------- ### Configure PSRule with Environment Variables Source: https://github.com/microsoft/psrule/blob/main/docs/faq.md Configure PSRule using environment variables. This example sets unprocessed object handling, output format, culture, and a custom configuration value. ```bash # With environment variable in bash export PSRULE_EXECUTION_UNPROCESSEDOBJECT=Ignore export PSRULE_OUTPUT_AS=Summary export PSRULE_OUTPUT_CULTURE=en-AU export PSRULE_CONFIGURATION_CUSTOM_VALUE=Example ``` -------------------------------- ### Recommendation Section Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Use the `## RECOMMENDATION` heading to provide corrective actions for rule failures. Avoid URLs here; use the Links section for references. Blank lines separate paragraphs. ```text ## RECOMMENDATION Consider setting the recommended label `app.kubernetes.io/name` on deployment and service resources. ``` -------------------------------- ### Install PSRule for All Users Source: https://github.com/microsoft/psrule/blob/main/docs/setup/index.md Installs the PSRule module for all users, requiring administrator or root permissions. ```powershell Install-Module -Name 'PSRule' -Repository PSGallery -Scope AllUsers ``` -------------------------------- ### Obsolete Baseline Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Baseline.md An example of an obsolete baseline definition. Baselines can be marked as obsolete using annotations. ```yaml apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Baseline metadata: name: ObsoleteBaseline annotations: obsolete: true spec: { } ``` -------------------------------- ### Example JSON output from PSRule Source: https://github.com/microsoft/psrule/blob/main/docs/analysis-output.md An example of PSRule results serialized in JSON format without indentation. ```json [{"data":{},"info":{"displayName":"Local.PS.RequireTLS","name":"Local.PS.RequireTLS","synopsis":"An example rule to require TLS."},"level":1,"outcome":"Fail","outcomeReason":"Processed","reason":["The field 'configure.supportsHttpsTrafficOnly' is set to 'False'.","The field 'configure.minTLSVersion' does not exist."],"ruleName":"Local.PS.RequireTLS","runId":"df662aad3ae7adee6f35b9733c7aaa53dc4d6b96","source":[{"file":"C:\\Dev\\Workspace\\PSRule\\docs\\authoring\\writing-rules\\settings.json","line":2,"position":11,"type":"File"}],"targetName":"1fe7c0f476b11301402d5017d87424c36ff085a8","targetType":"app1","time":0}] ``` -------------------------------- ### Browse Online Rule Help Source: https://github.com/microsoft/psrule/blob/main/docs/commands/PSRule/en-US/Get-PSRuleHelp.md Browse to the online version of documentation for Azure.ACR.AdminUser using the default web browser. ```powershell Get-PSRuleHelp Azure.ACR.AdminUser -Online; ``` -------------------------------- ### Recommend Keyword Example Source: https://github.com/microsoft/psrule/blob/main/docs/keywords/PSRule/en-US/about_PSRule_Keywords.md The Recommend keyword provides a message suggesting how to resolve an issue and pass the rule. This recommendation is set once per rule and applies to all objects. ```powershell # Synopsis: Provide recommendation to resolve the issue Rule 'objectRecommend' { Recommend 'Use at least two (2) instances' $TargetObject.count -ge 2 } ``` -------------------------------- ### Including rules from an installed module with Assert-PSRule Source: https://github.com/microsoft/psrule/blob/main/docs/faq.md Use the -Module parameter with Assert-PSRule to include rules from an installed PSRule module. ```powershell # With input from the pipeline $items | Assert-PSRule -Module 'PSRule.Rules.Azure' # With input from file Assert-PSRule -Module 'PSRule.Rules.Azure' -InputPath 'src/' ``` -------------------------------- ### Configure PSRule with Options Object Source: https://github.com/microsoft/psrule/blob/main/docs/faq.md Configure PSRule cmdlets at runtime using a PSRuleOption object. This example sets output format, culture, and unprocessed object handling. ```powershell # With cmdlet $option = New-PSRuleOption -OutputAs Summary -OutputCulture 'en-AU' -ExecutionUnprocessedObject 'Ignore' -Configuration @{ CUSTOM_VALUE = 'example' } $items | Assert-PSRule -Option $option ``` -------------------------------- ### Invoke-Build Task for PSRule Installation Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Defines an Invoke-Build task to install the PSRule module, ensuring it meets the minimum version requirement. ```powershell # Synopsis: Install PSRule task PSRule { if ($Null -eq (Get-InstalledModule -Name PSRule -MinimumVersion '2.1.0' -ErrorAction SilentlyContinue)) { Install-Module -Name PSRule -Scope CurrentUser -MinimumVersion '2.1.0' -Force; } } ``` -------------------------------- ### Get rule summary Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/index.md Use the -As Summary parameter with Invoke-PSRule to get a summary of rule outcomes across all validated objects. ```powershell # Show rule summary $items | Invoke-PSRule -As Summary; ``` -------------------------------- ### Configure Azure Module Options Source: https://github.com/microsoft/psrule/blob/main/media/walkthroughs/getStarted/01_configureOptions.md Set configuration options for the PSRule.Rules.Azure module. This example shows how to enable expansion for Azure Template parameter files and Bicep files. ```yaml configuration: # Enable expansion of Azure Template parameter files. AZURE_PARAMETER_FILE_EXPANSION: true # Enable expansion of Azure Bicep files. AZURE_BICEP_FILE_EXPANSION: true ``` -------------------------------- ### Configure Kubernetes Resource Bindings Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/kubernetes-resources/kubernetes-resources.md Set TargetName and TargetType configuration options to bind Kubernetes resource properties. This example shows how to set options using a YAML configuration file. ```yaml binding: targetName: - metadata.name targetType: - kind ``` -------------------------------- ### Markdown Rule Display Name Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Example of setting the rule's display name using a level one heading in markdown. ```markdown # Use recommended name label ``` -------------------------------- ### Include Paths via YAML and Environment Variables Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Configure paths for automatic rule and resource inclusion using YAML configuration files or environment variables. ```yaml include: path: - custom-rules/ ``` ```bash export PSRULE_INCLUDE_PATH=.ps-rule/;custom-rules/ ``` ```yaml env: PSRULE_INCLUDE_PATH: .ps-rule/;custom-rules/ ``` ```yaml variables: - name: PSRULE_INCLUDE_PATH value: .ps-rule/;custom-rules/ ``` -------------------------------- ### Install or Update PowerShellGet Module Source: https://github.com/microsoft/psrule/blob/main/docs/troubleshooting.md Installs or updates the PowerShellGet module to at least version 2.2.1. Required for managing PowerShell modules, including PSRule. ```powershell if ($Null -eq (Get-InstalledModule -Name PowerShellGet -MinimumVersion 2.2.1 -ErrorAction Ignore)) { Install-Module PowerShellGet -MinimumVersion 2.2.1 -Scope CurrentUser -Force -AllowClobber; } ``` -------------------------------- ### notMatch Expression Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Expressions.md The notMatch condition checks if a field does not match a regular expression. This example shows how to use notMatch with a regular expression pattern. ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Rule metadata: name: 'ExampleNotMatch' spec: condition: field: 'Name' notMatch: '$(abc|efg)$' ``` ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: 'ExampleNotMatch' spec: if: field: 'Name' notMatch: '$(abc|efg)$' ``` -------------------------------- ### Install PSRule for the current user Source: https://github.com/microsoft/psrule/blob/main/docs/scenarios/validation-pipeline/validation-pipeline.md Installs PSRule for the current user context within a CI pipeline. Use `-Scope CurrentUser` to avoid administrator permissions. ```powershell Install-Module -Name PSRule -Scope CurrentUser -Force; ``` -------------------------------- ### Configure PSRule using Environment Variables (Bash) Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Configuration values can be specified using environment variables. Prefix the configuration value with PSRULE_CONFIGURATION_. ```bash export PSRULE_CONFIGURATION_LOCAL_APPSERVICEMININSTANCECOUNT=2 ``` -------------------------------- ### notWithinPath Expression Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Expressions.md The notWithinPath condition checks if a file path is not within a required path. This example shows how to use notWithinPath with source and case-sensitive options. ```yaml --- # Synopsis: Test notWithinPath with source apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: YamlSourceNotWithinPath spec: if: source: 'Template' notWithinPath: - "deployments/path/" ``` ```yaml --- # Synopsis: Test notWithinPath with source and case sensitive apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: YamlSourceNotWithinPathCaseSensitive spec: if: source: 'Template' notWithinPath: - "Deployments/Path/" caseSensitive: true ``` -------------------------------- ### notLike Expression Example Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Expressions.md The notLike condition checks if an operand does not match a wildcard pattern. This example shows how to use notLike with a single pattern and an array of patterns. ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Rule metadata: name: 'ExampleNotLike' spec: condition: anyOf: - field: 'url' notLike: 'http://*' - field: 'url' notLike: - 'http://' - 'https://' ``` ```yaml --- apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: Selector metadata: name: 'ExampleNotLike' spec: if: anyOf: - field: 'url' notLike: 'http://*' - field: 'url' notLike: - 'http://' - 'https://' ``` -------------------------------- ### Notes Section Example Source: https://github.com/microsoft/psrule/blob/main/docs/authoring/writing-rule-help.md Use the `## NOTES` heading for additional information, such as configuration options. Notes are excluded from YAML and JSON output but visible with `Get-PSRuleHelp -Full`. Blank lines separate paragraphs. ```text ## NOTES The Kubernetes recommended labels include: - `app.kubernetes.io/name` - `app.kubernetes.io/instance` - `app.kubernetes.io/version` - `app.kubernetes.io/component` - `app.kubernetes.io/part-of` - `app.kubernetes.io/managed-by` ``` -------------------------------- ### Example PSRule Rule for Storage Accounts Source: https://github.com/microsoft/psrule/blob/main/docs/specs/design-spec.md An example rule that checks if storage accounts are configured to only accept encrypted traffic. This rule targets objects of type 'Microsoft.Storage/storageAccounts'. ```powershell # Synopsis: Configure storage accounts to only accept encrypted traffic i.e. HTTPS/SMB Rule 'StorageAccounts.UseHttps' -Type 'Microsoft.Storage/storageAccounts' { $TargetObject.Properties.supportsHttpsTrafficOnly -eq $True } ``` -------------------------------- ### Configure Run.Description using YAML Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Sets the run/description property in YAML to define a custom description for output. ```yaml run: description: Custom run description. ``` -------------------------------- ### Example CSV Output Source: https://github.com/microsoft/psrule/blob/main/docs/analysis-output.md Example of detailed CSV output from PSRule analysis. This format includes columns like RuleName, TargetName, TargetType, Outcome, OutcomeReason, Synopsis, and Recommendation. ```csv RuleName,TargetName,TargetType,Outcome,OutcomeReason,Synopsis,Recommendation "Local.PS.RequireTLS","1fe7c0f476b11301402d5017d87424c36ff085a8","app1","Fail","Processed","An example rule to require TLS.", "Local.YAML.RequireTLS","1fe7c0f476b11301402d5017d87424c36ff085a8","app1","Fail","Processed","An example rule to require TLS.", "Local.JSON.RequireTLS","1fe7c0f476b11301402d5017d87424c36ff085a8","app1","Fail","Processed","An example rule to require TLS.", ``` -------------------------------- ### Setting PSRule Options with Set-PSRuleOption Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Illustrates how to use the `Set-PSRuleOption` cmdlet to configure options, such as 'OutputFormat', which can be stored in YAML or manually edited. ```powershell Set-PSRuleOption -OutputFormat Yaml; ``` -------------------------------- ### Example PSRule output Source: https://github.com/microsoft/psrule/blob/main/docs/quickstart/standalone-rule.md This is an example of the output generated by Invoke-PSRule, showing rule outcomes for different target objects. It includes passing and failing rules, as well as warnings for unprocessed objects. ```text TargetName: edgeupdate RuleName Outcome Recommendation -------- ------- -------------- PS.ServiceStarted Fail Automatic services should be running. Yaml.ServiceStarted Fail Automatic services should be running. Json.ServiceStarted Fail Automatic services should be running. TargetName: EventLog RuleName Outcome Recommendation -------- ------- -------------- PS.ServiceStarted Pass Automatic services should be running. Yaml.ServiceStarted Pass Automatic services should be running. Json.ServiceStarted Pass Automatic services should be running. WARNING: Target object 'TermService' has not been processed because no matching rules were found. ``` -------------------------------- ### Configure PSRule Convention.Include using Environment Variables (Bash) Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Specifies conventions to execute when the pipeline run using environment variables. Conventions are included by name and must be defined within files included in -Path or -Module. ```bash export PSRULE_CONVENTION_INCLUDE='Convention1;Convention2' ``` -------------------------------- ### Example Suppression Groups in JSONC Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_SuppressionGroups.md Example of defining suppression groups in a JSONC file. This includes suppressing specific rules based on object name or type, with an optional expiry date. ```jsonc // Example SuppressionGroups.Rule.jsonc [ { // Synopsis: Ignore test objects by name. "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "SuppressionGroup", "metadata": { "name": "SuppressWithTargetName" }, "spec": { "rule": [ "FromFile1", "FromFile2" ], "if": { "name": ".", "in": [ "TestObject1", "TestObject2" ] } } }, { // Synopsis: Ignore test objects by type. "apiVersion": "github.com/microsoft/PSRule/2025-01-01", "kind": "SuppressionGroup", "metadata": { "name": "SuppressWithTestType" }, "spec": { "expiresOn": "2030-01-01T00:00:00Z", "rule": [ "FromFile3", "FromFile5" ], "if": { "type": ".", "equals": "TestType" } } } ] ``` -------------------------------- ### Execute Conventions in Order Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Conventions.md Specifies multiple conventions to be executed in the order they are listed. This applies to Initialize, Begin, Process, and End blocks. ```powershell Assert-PSRule -Convention 'ExampleConvention1', 'ExampleConvention2'; ``` -------------------------------- ### Example Suppression Group in YAML Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_SuppressionGroups.md Example of defining suppression groups in a YAML file. This includes suppressing specific rules based on object name or type, with an optional expiry date. ```yaml # Example SuppressionGroups.Rule.yaml --- # Synopsis: Ignore test objects by name. apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: SuppressionGroup metadata: name: SuppressWithTargetName spec: rule: - 'FromFile1' - 'FromFile2' if: name: '.' in: - 'TestObject1' - 'TestObject2' --- # Synopsis: Ignore test objects by type. apiVersion: github.com/microsoft/PSRule/2025-01-01 kind: SuppressionGroup metadata: name: SuppressWithTestType spec: expiresOn: '2030-01-01T00:00:00Z' rule: - 'FromFile3' - 'FromFile5' if: type: '.' equals: 'TestType' ``` -------------------------------- ### Configure PSRule using YAML Source: https://github.com/microsoft/psrule/blob/main/docs/concepts/PSRule/en-US/about_PSRule_Options.md Configuration values can be specified using YAML. ```yaml configuration: LOCAL_APPSERVICEMININSTANCECOUNT: 2 ```