Code Monkey home page Code Monkey logo

ps-rule's Introduction

PSRule

Validate infrastructure as code (IaC) and DevOps repositories using rules. PSRule allows you to analyze a repository with pre-built rules or create your own. Analysis can be performed from input files or the repository structure.

To learn about PSRule and how to write your own rules see Getting started.

Usage

To get the latest stable release use:

- name: Run PSRule analysis
  uses: microsoft/ps-rule@latest

To get the latest stable release by major version use:

- name: Run PSRule analysis
  uses: microsoft/ps-rule@v2

To get a specific release use (recommended):

- name: Run PSRule analysis
  uses: microsoft/[email protected]

To get the latest bits use:

- name: Run PSRule analysis
  uses: microsoft/ps-rule@main

To use the latest action with an older version of PSRule, you can use the version parameter. For example:

- name: Run PSRule analysis
  uses: microsoft/[email protected]
  with:
    version: '1.11.1'

For a list of changes please see the change log.


The recommended approach is to pin to the latest specific release. Pinning to a specific release reduces the risk of new releases breaking your pipeline. You can easily update to the latest release by changing the version number. At such time, you can test the new release in a feature branch before merging to main.

Using microsoft/ps-rule@main is not recommended for production workflows. The main branch is under active development and may be unstable. Use microsoft/ps-rule@main to try latest updates ahead of a stable release and provide feedback.


Inputs

- name: Run PSRule analysis
  uses: microsoft/ps-rule@main
  with:
    inputType: repository, inputPath                             # Optional. Determines the type of input to use for PSRule.
    inputPath: string                                            # Optional. The path PSRule will look for files to validate.
    modules: string                                              # Optional. A comma separated list of modules to use for analysis.
    source: string                                               # Optional. A path containing rules to use for analysis.
    baseline: string                                             # Optional. The name of a PSRule baseline to use.
    conventions: string                                          # Optional. A comma separated list of conventions to use.
    option: string                                               # Optional. The path to an options file.
    outcome: Fail, Pass, Error, Processed, Problem, All          # Optional. Filters output to include results with the specified outcome.
    outputFormat: None, Yaml, Json, NUnit3, Csv, Markdown, Sarif # Optional. The format to use when writing results to disk.
    outputPath: string                                           # Optional. The file path to write results to.
    path: string                                                 # Optional. The working directory PSRule is run from.
    prerelease: boolean                                          # Optional. Determine if a pre-release module version is installed.
    repository: string                                           # Optional. The name of the PowerShell repository where PSRule modules are installed from.
    summary: boolean                                             # Optional. Determines if a job summary is written.
    version: string                                              # Optional. The specific version of PSRule to use.

inputType

Determines the type of input to use for PSRule either repository or inputPath. Defaults to repository.

When set to:

  • repository - The structure of the repository within inputPath will be analyzed.
  • inputPath - Supported file formats within inputPath will be read as objects.

inputPath

The path PSRule will look for input files. You can still use this parameter even when inputType is set to repository.

This must be a relative path from the path input parameter. Defaults to repository root.

Note: Avoid using a relative path starting with /, as a leading slash indicates root on Linux.

modules

A comma separated list of modules to use for analysis.

Modules are additional packages that can be installed from the PowerShell Gallery. PSRule will install the latest stable version from the PowerShell Gallery automatically by default. Available modules.

To install pre-release module versions, use prerelease: true.

source

An path containing rules to use for analysis. Defaults to .ps-rule/.

Use this option to include rules that have not been packaged as a module.

baseline

The name of a PSRule baseline to use. Baselines can be used from modules or specified in a separate file.

  • To use a baseline included in a module use modules: with baseline:.
  • To use a baseline specified in a separate file use source: with baseline:.

conventions

A comma separated list of conventions to use. Conventions can be used from modules or specified in a separate file.

  • To use a convention included in a module use modules: with conventions:.
  • To use a convention specified in a separate file use source: with conventions:.

For example: conventions: Monitor.LogAnalytics.Import

option

The path to an options file. By default, ps-rule.yaml will be used if it exists. Configure this parameter to use a different file.

outcome

Filters output to include results with the specified outcome. Supported outcomes are Fail, Pass, Error, Processed, Problem, All. Defaults to Processed.

outputFormat

The output format to write result to disk. Supported formats are Yaml, Json, NUnit3, Csv, Markdown, Sarif. Defaults to None.

outputPath

The file path to write results to when outputFormat is configured.

path

The working directory PSRule is run from. Defaults to repository root.

Options specified in ps-rule.yaml from this directory will be used unless overridden by inputs.

prerelease

Determine if a pre-release module versions are installed. When set to true the latest pre-release or stable module version is installed.

If this input is not configured, invalid, or set to false only stable module versions will be installed.

repository

The name of the PowerShell repository where PSRule modules are installed from. By default this is the PowerShell Gallery.

When configured, PowerShell modules are installed from this repository. Before calling the ps-rule action, register and authenticate to the repository if required.

For example, to register a local repository use:

Register-PSRepository -SourceLocation \\server\share -Name Local -InstallationPolicy Trusted;

For details PowerShell repositories see Working with Private PowerShellGet Repositories.

summary

Determines if a job summary is written. By default, a job summary is generated and attached to the workflow run. When set to false the job summary is skipped.

version

The specific version of PSRule to use. By default, the latest stable version of PSRule will be used. When set:

  • The specific version of PSRule will be installed and imported for use.
  • If a pre-release version is specified, prerelease: true must also be specified.
  • If the version is not found, an error will be thrown.

Using the action

To use PSRule:

  1. See Creating a workflow file.
  2. Reference microsoft/[email protected]. For example:
name: CI
on: [push]
jobs:
  analyze:
    name: Analyze repository
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@v3

    - name: Run PSRule analysis
      uses: microsoft/[email protected]
  1. Create rules within the .ps-rule/ directory. For example:
# Example .ps-rule/GitHub.Community.Rule.ps1

# Synopsis: Check for recommended community files
Rule 'GitHub.Community' -Type 'PSRule.Data.RepositoryInfo' {
    $Assert.FilePath($TargetObject, 'FullName', @('LICENSE'));
    $Assert.FilePath($TargetObject, 'FullName', @('CODE_OF_CONDUCT.md'));
    $Assert.FilePath($TargetObject, 'FullName', @('CONTRIBUTING.md'));
    $Assert.FilePath($TargetObject, 'FullName', @('README.md'));
    $Assert.FilePath($TargetObject, 'FullName', @('.github/CODEOWNERS'));
    $Assert.FilePath($TargetObject, 'FullName', @('.github/PULL_REQUEST_TEMPLATE.md'));
}
  1. Run the workflow.

Support

This project uses GitHub Issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates.

  • For new issues, file your bug or feature request as a new issue.
  • For help, discussion, and support questions about using this project, join or start a discussion.

Support for this project/ product is limited to the resources listed above.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Maintainers

License

This project is licensed under the MIT License.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

ps-rule's People

Contributors

armaanmcleod avatar berniewhite avatar dependabot[bot] avatar github-actions[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ps-rule's Issues

Add support for output using SARIF format

The latest PSRule version v2.0.0-B2201161 supports SARIF as an output format. We need to update the action validation set to permit Sarif to be used as an output format.

Add release branches

Related to microsoft/PSRule#1431


Currently the PSRule action support specific releases:

- name: Run PSRule analysis
  uses: microsoft/[email protected]

Or latest commit:

- name: Run PSRule analysis
  uses: microsoft/ps-rule@main

However we should provide some additional options to provide even more flexibility such as:

  • microsoft/ps-rule@v2 - The latest stable release >= 2.0.0 and < 3.0.0
  • microsoft/ps-rule@latest - The latest stable release.

When PSRule v3 is available microsoft/ps-rule@v3.

Fail action when module installation fails

Description of the issue

If a module fails to install, an PowerShell error will be generated in output but this doesn't stop the pipeline.

If the module is not installed, included rules can not be run.

Expected behaviour

If any module fails to install, the action should error.

Failing to install a module could be a transient issue.

Error output

> Checking module: PSRule.Rules.MSFT.OSS
  - Installing module
Install-Package: /opt/microsoft/powershell/7/Modules/PowerShellGet/PSModule.psm1:9711
Line |
9711 |  … talledPackages = PackageManagement\Install-Package @PSBoundParameters
     |                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | No match was found for the specified search criteria and
     | module name 'PSRule.Rules.MSFT.OSS'. Try Get-PSRepository to
     | see all available registered module repositories.

Get-Package: /opt/microsoft/powershell/7/Modules/PowerShellGet/PSModule.psm1:9445
Line |
9445 |          PackageManagement\Get-Package @PSBoundParameters | Microsoft. …
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | No match was found for the specified search criteria and
     | module names 'PSRule.Rules.MSFT.OSS'.

  - Failed to install

Action version:

  • Version: 1.5.0

Path issue calling powershell.ps1

Description of the issue

Problem with pathing from recent PR #146.

Error output

/home/runner/work/_actions/Microsoft/ps-rule/mainpowershell.ps1: /home/runner/work/_temp/f38679bf-c3f0-43d2-9d4c-208a6552bd8b.ps1:2
Line |
   2 |  /home/runner/work/_actions/Microsoft/ps-rule/mainpowershell.ps1 -Inpu …
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The term
     | '/home/runner/work/_actions/Microsoft/ps-rule/mainpowershell.ps1' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Action version:

  • Version: main

Add job summaries

PSRule v2.6.0 introduced support for write job summaries. You can configure this using the Output.JobSummaryPath option.

We should automatically write job summaries by default when using the GitHub action and provide an input to disable.

Planning to upgrade logo on GitHub Marketplace to Microsoft logo by end of May 2021

InputPath is relative

Update documentation to make it clear that inputPath is a relative path, because it is appended to path. A fully qualified path will fail.

Add support for using baselines

PSRule provides an ability to use a baseline to configure binding and rule sets.

Currently this option is not exposed as a configurable input for this action.

Add outcome filtering parameter

Currently output from PSRule can be filtered to a specific set of outcomes by setting Output.Outcome through an environment variable or ps-rule.yaml.

However this is common case that a parameter to configure directly on the action can be provided.

Expose more rule error output in CI

Is your feature request related to a problem? Please describe.

Continuing from https://github.com/microsoft/PSRule/discussions/962

As shown here:

Screenshot 2022-02-06 215200

Sometimes it would be useful to show more error output here to understand what the issue is.

Describe the solution you'd like

Catch the specific exception type in https://github.com/microsoft/ps-rule/blob/main/powershell.ps1#L181.

Describe alternatives you've considered

Other solutions:

  • Add all exception messages with $_.Exception.Message inside the error message: https://github.com/microsoft/ps-rule/blob/main/powershell.ps1#L182. May not want to do this because some messages should not be shown in CI, such as the Pipeline Stopped... exception.
  • Add a CI option to expose full exception message. Could be useful if customer wants to set this option in ps-rule.yaml to control the verbosity of the output.

Additional context

Should be included for Azure Pipelines as well.

Allow choice of PSRule version to install

Currently the PSRule version is directly tied to the version of the action.

Moving forward with PSRule v2. In the short term we need to test PSRule v2 preview versions. But longer term, giving a choice of PSRule version would be helpful.

Assertion failed with newer version

Description of the issue

When a module installs a newer version of PSRule then currently supported by PSRule action an error occurs.

Expected behaviour

PSRule action should allow a newer version of PSRule module to be installed.

Error output

One or more assertions failed.

Action version:

  • Version: 2.0.0

Referencing PSRule main branch

Is your feature request related to a problem? Please describe.

The current PSRule release is 3 weeks old.
I wish to test a recent change in the main branch.

I tried using both of these syntaxes, however the first continued to reference 2.7.0 and the second failed. Apologies if this is documented somewhere that i didn't spot.

      - name: PSRule for Azure - Well Architected
        #uses: microsoft/[email protected]
        uses: microsoft/ps-rule@main
        continue-on-error: true #Setting this whilst PSRule gets bedded in, in this project
        with:
          modules: 'PSRule.Rules.Azure'
          inputPath: "${{ env.ParamFilePath }}"
      - name: PSRule for Azure - Well Architected
        #uses: microsoft/[email protected]
        uses: microsoft/ps-rule@main
        continue-on-error: true #Setting this whilst PSRule gets bedded in, in this project
        with:
          modules: 'PSRule.Rules.Azure'
          inputPath: "${{ env.ParamFilePath }}"
          version: 'main' #Assume this relates to the repo tag

Describe the solution you'd like

An easy way to use the version in main

Describe alternatives you've considered

None

Additional context

https://github.com/Azure/AKS-Construction/blob/gb-wellarchfixup/.github/workflows/ByoVnetCI.yml

Switch to using File input format for repository scans

Currently the inputType of repository uses custom code to scan the repository for files.

PSRule v0.20.0 introduces a similar process natively within the engine. It also observes file exclusions from .gitignore and the Input.PathIgnore option.

We should update to use this feature.

References

PSRule change log

Allow installation of modules from other sources

Currently rules modules can be installed from the PowerShell Gallery. There isn't a way currently to use a private feed, however this would be helpful for internal publishing within an organization.

Import of pre-release version

Description of the issue

When running with a pre-release version of PSRule, errors importing the module. However the module is still imported and run.

Expected behaviour

Resolve issue parsing pre-release Sem Version string to Import-Module cmdlet.

Error output

Error: An error occured importing module 'PSRule'.

Action version:

  • Version: main - pre-v2

Add support for conventions

Conventions provide additional extensibility for PSRule, we should allow these to be specified from the assert task.

Add support for alternative option file

Currently PSRule will automatically detect and use ps-rule.yaml for options from the current working path when the action is run.

In some cases it may be desirable to have an options file for different use cases. While Assert-PSRule exposes an -Option parameter that can be set to an alternative file path, it is not currently exposed as an option that can be set in the pipeline.

Adding an additional parameter to set the option file would be useful for some use cases.

Rule Files Not Found

Description of the issue

When using the current release of PSRule my rules are no longer found/detected in the .ps-rule directory nested in my .github directory.

Expected behaviour

*.Rule.ps1 files should be detected.

To Reproduce

Steps to reproduce the issue:

  • Nest .ps-rule directory under .gitlab directory
Working

Rule file is detected

    - name: Checkout
      uses: actions/checkout@v2
 
    - name: Check GitHub Community Rules
      uses: Microsoft/[email protected]
      with:
        source: .github/.ps-rule/
Not Working

Rule file is NOT detected

    - name: Checkout
      uses: actions/checkout@v2
 
    - name: Check GitHub Community Rules
      uses: Microsoft/ps-rule@main
      with:
        source: .github/.ps-rule/

Error output

Capture any error messages and or run output.

2020-09-18T16:57:34.2793671Z [info] Using Action: Microsoftps-rule
2020-09-18T16:57:34.2882599Z [info] Using PWD: /github/workspace
2020-09-18T16:57:34.2883150Z [info] Using Path: /github/workspace
2020-09-18T16:57:34.2884218Z [info] Using Source: /github/workspace/.github/.ps-rule/
2020-09-18T16:57:34.2884795Z [info] Using InputType: repository
2020-09-18T16:57:34.2885291Z [info] Using InputPath: /github/workspace
2020-09-18T16:57:34.2886346Z [info] Using OutputFormat: Json
2020-09-18T16:57:34.2887120Z [info] Using OutputPath: ./rule-analysis.txt
2020-09-18T16:57:34.3332291Z 
2020-09-18T16:57:34.3333830Z ---
2020-09-18T16:57:35.0057504Z     ____  _____ ____        __
2020-09-18T16:57:35.0057871Z    / __ \/ ___// __ \__  __/ /__
2020-09-18T16:57:35.0058130Z   / /_/ /\__ \/ /_/ / / / / / _ \
2020-09-18T16:57:35.0071629Z  / ____/___/ / _, _/ /_/ / /  __/
2020-09-18T16:57:35.0071961Z /_/    /____/_/ |_|\__,_/_/\___/
2020-09-18T16:57:35.0072134Z 
2020-09-18T16:57:35.0096588Z Using PSRule v0.20.0
2020-09-18T16:57:35.0096815Z 
2020-09-18T16:57:35.1181542Z ##[warning]Target object '.github/.ps-rule/GitHub.Community.Rule.ps1' has not been processed because no matching rules were found.
2020-09-18T16:57:35.1186964Z 
2020-09-18T16:57:35.1187351Z Rules processed: 0, failed: 0, errored: 0

Action version:

  • Version: 0.3.0 (Broken)
  • Version: 0.2.0 (Working)

Additional context

  • Rule Directory
    • REPO/.github/.ps-rule
  • Rules Used
    • GitHub.Community.Rule.ps1 (From Example)

This format has previously worked for me on other repositories in the past by targeting main but now I have to explicitly target v0.2.0 to have it work correctly as expected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.