{"id":13599364,"url":"https://github.com/microsoft/Requirements","last_synced_at":"2025-04-10T12:32:24.562Z","repository":{"id":55475629,"uuid":"152165815","full_name":"microsoft/Requirements","owner":"microsoft","description":"PowerShell framework for declaratively defining and idempotently imposing system configurations","archived":true,"fork":false,"pushed_at":"2022-11-28T19:10:54.000Z","size":293,"stargazers_count":159,"open_issues_count":18,"forks_count":25,"subscribers_count":21,"default_branch":"master","last_synced_at":"2025-04-08T10:12:16.085Z","etag":null,"topics":["configuration-management","declarative","idempotency","logging","powershell","validation"],"latest_commit_sha":null,"homepage":null,"language":"PowerShell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microsoft.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null}},"created_at":"2018-10-09T00:51:55.000Z","updated_at":"2025-02-05T14:30:41.000Z","dependencies_parsed_at":"2023-01-22T17:15:24.054Z","dependency_job_id":null,"html_url":"https://github.com/microsoft/Requirements","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FRequirements","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FRequirements/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FRequirements/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2FRequirements/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microsoft","download_url":"https://codeload.github.com/microsoft/Requirements/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248217145,"owners_count":21066633,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["configuration-management","declarative","idempotency","logging","powershell","validation"],"created_at":"2024-08-01T17:01:02.965Z","updated_at":"2025-04-10T12:32:19.550Z","avatar_url":"https://github.com/microsoft.png","language":"PowerShell","funding_links":[],"categories":["PowerShell"],"sub_categories":[],"readme":"\n### Breaking changes\n\n#### v2.3\n\n* Requirement nesting is no longer supported.  Requirements are supposed to be atomic components of a system, and by definition, atomic components cannot contain other atomic components and still be atomic. Recommendation is to migrate to our [supported patterns](#patterns).\n* `Format-Callstack`, the formatter for nested Requirements, is no longer supported.  Recommendation is to migrate to [`Format-Verbose`](#format-verbose).\n* `Name` is no longer a supported property on Requirements.  Recommendation is to migrate to [namespaces](#managing-large-configurations-with-namespaces).\n\n-----\n\n* [Overview](#overview)\n  * [What is a Requirement](#what-is-a-requirement)\n  * [Why Requirements](#why-requirements)\n    * [Code against the Desired State](#code-against-the-desired-state)\n    * [Generically define Requirements](#generically-define-requirements)\n  * [Comparison to DSC](#comparison-to-dsc)\n* [Quickstart](#quickstart)\n  * [Defining Requirements](#defining-requirements)\n    * [Note: `Describe` the desired state, not the transition](#note-describe-the-desired-state-not-the-transition)\n  * [Enforcing the Configuration](#enforcing-the-configuration)\n* [Advanced Configurations](#advanced-configurations)\n  * [Types of Requirements](#types-of-requirements)\n    * [Standard Requirement](#standard-requirement)\n    * [Validation Requirements](#validation-requirements)\n    * [Idempotent `Set` Requirements](#idempotent-set-requirements)\n  * [Patterns](#patterns)\n    * [Avoiding state with selectors](#avoiding-state-with-selectors)\n    * [Reusable requirements](#reusable-requirements)\n    * [Defining Requirements with control flow](#defining-requirements-with-control-flow)\n    * [Managing large configurations with Namespaces](#managing-large-configurations-with-namespaces)\n    * [Isomorphic Enforcement](#isomorphic-enforcement)\n  * [Defining DSC Resources](#defining-dsc-resources)\n* [Formatting the logs](#formatting-the-logs)\n  * [`Format-Table`](#format-table)\n  * [`Format-Checklist`](#format-checklist)\n  * [`Format-Verbose`](#format-verbose)\n* [Contributing](#contributing)\n\n# Overview\n\nRequirements is a PowerShell Gallery module for declaratively describing a system as a set of \"requirements\", then idempotently setting each requirement to its desired state.\n\nThe background motivation and implementation design are discussed in detail in [Declarative Idempotency](https://itnext.io/declarative-idempotency-aaa07c6dd9a0?source=friends_link\u0026sk=f0464e8e29525b23aabe766bfb557dd7).\n\nTrevor Sullivan provides a good overview and (slightly outdated) tutorial [video](https://www.youtube.com/watch?v=efRnjlZKCGw) about Requirements.\n\n## What is a Requirement\n\nA \"Requirement\" is a single atomic component of a system configuration.  For a system to be in its desired state, all Requirements in the system must be in a desired state.\n\nA Requirement is an object defined by three properties:\n\n* `Describe` - A `string` that describes the desired state of the Requirement.\n* `Test` - A `scriptblock` that returns whether the Requirement is in its desired state.\n* `Set` - A `scriptblock` that can be run to put the Requirement into its desired state if it is not in a desired state.\n\n## Why Requirements\n\n### Code against the Desired State\n\nIn DevOps, you may be managing a fleet of servers, containers, cloud resources, files on disk, or many other kinds of components in a heterogeneous system.  Lets say you have *n* components in your system and every component is either in a `GOOD` or `BAD` state.  You have two options:\n\n* You can try and account for every possible configuration of your system and transition between those states, but then you will have *2**n* possible states to manage.\n* You can only account for the desired state of each individual component, so you will only have *n* states to account for.  Much simpler!\n\n### Generically define Requirements\n\nIf you only manage cloud resources, then try to use Terraform, ARM, or CloudFormation.  If you only manage kubernetes resources, then try and use Helm.  These are domain-specific frameworks for managing the desired state of resources and are best suited for their task.\n\nHowever, you will often find you have complex configurations, such as configurations that can only be described in PowerShell.  You may even have macroconfigurations that consist of one or more Terraform templates.  In this case you will probably want something more generic to glue your configurations together without sacrificing the declarative desired state paradigm.  This is where Requirements comes in.\n\n## Comparison to DSC\n\nDesired State Configurations allow you to declaratively describe a configuration, then let the local configuration manager handle with setting the configuration to its desired state.  This pattern from the outside may seem similar to Requirements, but there are crucial differences.\n\nDSC is optimized for handling *many* configurations *asynchronously*.  For example, applying a configuration in parallel to multiple nodes.  In contrast, Requirements applies a *single* configuration *synchronously*.  This enables usage in different scenarios, including:\n\n* CI/CD scripts\n* CLIs\n* Dockerfiles\n* Linux\n\nWhile Requirements supports DSC resources, it does not have a hard dependency on DSC's configuration manager, so if your Requirements do not include DSC resources they will work on any platform that PowerShell Core supports.\n\n# Quickstart\n\n## Defining Requirements\n\nThe easiest way to declare a requirement is to define it as a hashtable and let PowerShell's implicit casting handle the rest.\n\n```powershell\n$requirements = @(\n    @{\n        Describe = \"Resource 1 is present in the system\"\n        Test     = { $mySystem -contains 1 }\n        Set      = {\n            $mySystem.Add(1) | Out-Null\n            Start-Sleep 1\n        }\n    },\n    @{\n        Describe = \"Resource 2 is present in the system\"\n        Test     = { $mySystem -contains 2 }\n        Set      = {\n            $mySystem.Add(2) | Out-Null\n            Start-Sleep 1\n        }\n    },\n    @{\n        Describe = \"Resource 3 is present in the system\"\n        Test     = { $mySystem -contains 3 }\n        Set      = {\n            $mySystem.Add(3) | Out-Null\n            Start-Sleep 1\n        }\n    }\n)\n```\n\n### Note: `Describe` the desired state, not the transition\n\nOur `Describe` describes the *desired state* of the Requirement (ex: \"Resource 1 is present in the system\") and not the `Set` block's transitioning action (ex: \"Adding Resource 1 to the system\").  This is because the `Set` block is not called if the Requirement is already in its desired state, so if we used the latter `Describe` and Resource 1 was already present in the system, we would be inaccurately logging that the Requirement is modifying the system when it is actually taking no action.\n\nThe sooner you embrace the Desired State mindset, the less friction you will have writing Requirements and managing your complex system configurations.\n\n## Enforcing the Configuration\n\nOnce you have an array of Requirements, you can simply pipe the Requirements into `Invoke-Requirement` to put each Requirement into its desired state.\n\n```powershell\n$requirements | Invoke-Requirement\n```\n\nThe status of each Requirement will be logged to the output stream.  By default they are shown with `Format-List`, but you can pipe the results to `Format-Table`, or use one of the packaged formatters for Requirements-specific event formatting and filtering.\n\n# Advanced Configurations\n\n## Types of Requirements\n\nAs you learned [previously](#what-is-a-requirement), Requirements consist of `Describe`, `Test`, and `Set` properties.  There are 4 types of Requirements--one for every permutation of including or excluding `Test` and `Set`.  Note that `Describe` must always be present.\n\n### Standard Requirement\n\nThis is the kind you are already [familiar with](#what-is-a-requirement).  It includes both a `Test` and `Set`.\n\n### Validation Requirements\n\nIf you wish to assert that a precondition is met before continuing, you can leave out the `Set` block.  This is useful for [Defensive programming](https://itnext.io/defensive-powershell-with-validation-attributes-8e7303e179fd?source=friends_link\u0026sk=14765ca9554709a77f8af7d73612ef5b), or when a Requirement requires manual steps.\n\n```powershell\n@{\n    Describe = \"Azure CLI is authenticated\"\n    Test     = { az account }\n}\n```\n\n### Idempotent `Set` Requirements\n\nSometimes, your `Set` block is already idempotent and an associated `Test` block cannot be defined.  In this case, you can leave out the `Test` block.\n\n```powershell\n@{\n    Describe = \"Initial state of system is backed up\"\n    Set      = { Get-StateOfSystem | Out-File \"$BackupContainer/$(Get-Date -Format 'yyyyMMddhhmmss').log\" }\n}\n```\n\n## Patterns\n\nSome people have trouble managing large configurations with Requirements because they try and explicitly define a single array literal of Requirements; however, this is unnecessary and Requirements can be handled like any other PowerShell object.  Here are some examples of patterns for managing Requirements.\n\n### Avoiding state with selectors\n\nRequirements should strongly avoid maintaining internal state.  Requirements is for enforcing declarative programming, whereas maintaining state is an imperative loophole that breaks the declarative paradigm.\n\nInstead, use **selectors** to easily derive up-to-date properties of the system using unit-testable functions.\n\n```powershell\n\u003c#\n.SYNOPSIS\n  Gets the random storage account name from the environment in the cloud\n#\u003e\nfunction Select-StorageAccountName([string]$EnvName) { ... }\n\n\u003c#\n.SYNOPSIS\n  Returns a Requirement that ensures a storage ccount exists in Azure\n#\u003e\nfunction New-StorageAccountRequirement {\n    @{\n        Describe = \"Storage Account exists\"\n        Test     = { Test-StorageAccountExists (Select-StorageAccountName $env:EnvName) }\n        Set      = { New-StorageAccount (Select-StorageAccountName $env:EnvName) }\n    }\n}\n```\n\n### Reusable requirements\n\nYou can wrap Requirements in a parameterized function or script to avoid redifining Requirements--\n\n```powershell\nfunction New-ResourceGroupRequirement {\n    Param(\n        [string]$Name,\n        [string]$Location\n    )\n\n    New-RequirementGroup \"rg\" -ScriptBlock {\n        @{\n            Describe = \"Logged in to Azure\"\n            Test     = { Get-AzAccount }\n            Set      = { Connect-AzAccount }\n        }\n        @{\n            Describe = \"Resource Group '$Name' exists\"\n            Test     = { Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue }\n            Set      = { New-AzResourceGroup -Name $Name -Location $Location }\n        }\n    }\n}\n```\n\nThen call your function to generate the Requirement--\n\n```powershell\n$Name = \"my-rg\"\n$Location = \"West US 2\"\n\n\u0026 {\n    New-ResourceGroupRequirement -Name $Name -Location $Location\n    @{\n        Describe = \"Do something with the resource group\"\n        Test     = { ... }\n        Set      = { ... }\n    }\n} `\n| Invoke-Requirement `\n| Format-Table\n```\n\n### Defining Requirements with control flow\n\nUsing control flow statements, like `if` and `foreach`, can dramatically simplify your Requirement definitions.  Let's see if we can simiplify our [quickstart example](#defining-requirements).\n\n```powershell\nforeach ($resourceId in 1..3) {\n    @{\n        Describe = \"Resource $resourceId is present in the system\"\n        Test     = { $mySystem -contains $resourceId }.GetNewClosure()\n        Set      = { $mySystem.Add($resourceId) | Out-Null; Start-Sleep 1 }.GetNewClosure()\n    }\n}\n```\n\nNotice that we had to call `.GetNewClosure()` to capture the current value of `$resourceId` in the `scriptblock`--otherwise the value would be `3` or `$null` depending on where we invoked it.\n\nWhen you define Requirements with control flow in this manner, the Requirements are written to output.  As such, this logic should be wrapped in a script, function, or `scriptblock`.\n\n### Managing large configurations with Namespaces\n\nYou can group Requirements into namespaces for clearer logging.  To add a namespace to Requirements, use the `New-RequirementGroup` function.  You can nest namespaces as well.\n\n```powershell\nNew-RequirementGroup \"local\" {\n    New-RequirementGroup \"clis\" {\n        @{\n            Describe = \"az is installed\"\n            Test     = { ... }\n            Set      = { ... }\n        }\n        @{\n            Describe = \"kubectl is installed\"\n            Test     = { ... }\n            Set      = { ... }\n        }\n    }\n    New-RequirementGroup \"configs\" {\n        @{\n            Describe = \"cluster config is built\"\n            Test     = { ... }\n            Set      = { ... }\n        }\n    }\n}\nNew-RequirementGroup \"cloud\" {\n    @{\n        Describe = \"Terraform is deployed\"\n        Test     = { ... }\n        Set      = { ... }\n    }\n}\n```\n\nThe above example would result in the Requirements below.\n\n```\nNamespace     Describe\n---------     --------\nlocal:clis    az is installed\nlocal:clis    kubectl is installed\nlocal:configs cluster config is built\ncloud         Terraform is deployed\n```\n\n### Isomorphic Enforcement\n\nIsomorphic execution means that our Requirements are enforced the same regardless of what context they are enforced in.  You will want your Requirements to run in a CICD pipeline for safe deployment practices and run manually from your local machine for development purposes, but in both contexts the Requirements should run exactly the same.\n\nWe will accomplish this by implementing Separation of Concerns, separating our Requirement definitions from our execution logic:\n\n* `myrequirements.ps1`, which will return an array of Requirements.\n* `Invoke-Verbose.ps1`, which will be called in a CICD pipeline and write verbose status information to the output stream.\n\n    ```powershell\n    ./myrequirements.ps1 | Invoke-Requirement | Format-Verbose\n    ```\n\n* `Invoke-Checklist.ps1`, which will be called in a console and interactively write to the host.\n\n    ```powershell\n    ./myrequirements.ps1 | Invoke-Requirement | Format-Checklist\n    ```\n\n## Defining DSC Resources\n\nIf you're using Windows and PowerShell 5, you can use DSC resources with Requirements.\n\n```PowerShell\n$requirement = @{\n    Describe     = \"My Dsc Requirement\"\n    ResourceName = \"File\"\n    ModuleName   = \"PSDesiredStateConfiguration\"\n    Property     = @{\n        Contents        = \"Hello World\"\n        DestinationPath = \"C:\\myFile.txt\"\n        Force           = $true\n    }\n}\nNew-Requirement @requirement | Invoke-Requirement | Format-Checklist\n```\n\n# Formatting the logs\n\n`Invoke-Requirement` will output logging events for each step in a `Requirement`'s execution lifecycle.  You can capture these logs with `Format-Table` or `Format-List`, or\n\n```powershell\n$requirements | Invoke-Requirement | Format-Table\n```\n\n## `Format-Table`\n\nThese logs were using `-Autosize` parameter, which better formats the columns, but does not support outputting as a stream.\n\n```\n  Method Lifecycle Name       Date\n  ------ --------- ----       ----\n    Test     Start Resource 1 6/12/2019 12:00:25 PM\n    Test      Stop Resource 1 6/12/2019 12:00:25 PM\n     Set     Start Resource 1 6/12/2019 12:00:25 PM\n     Set      Stop Resource 1 6/12/2019 12:00:26 PM\nValidate     Start Resource 1 6/12/2019 12:00:26 PM\nValidate      Stop Resource 1 6/12/2019 12:00:26 PM\n    Test     Start Resource 2 6/12/2019 12:00:26 PM\n    Test      Stop Resource 2 6/12/2019 12:00:26 PM\n     Set     Start Resource 2 6/12/2019 12:00:26 PM\n...\n```\n\n## `Format-Checklist`\n\n`Format-Checklist` will present a live-updating checklist to the user.\n\n![Format-Checklist output](https://raw.githubusercontent.com/microsoft/requirements/master/imgs/checklist.png)\n\n## `Format-Verbose`\n\nUnlike `Format-Checklist`, `Format-Verbose` prints all log events and includes metadata.  For complex use cases, you can define nested `Requirement`s (`Requirement`s that contain more `Requirement`s in their `Set` block).  `Format-Verbose` will print the stack of `Requirement` names of each `Requirement` as its processed.\n\n![Format-Verbose output](https://raw.githubusercontent.com/microsoft/requirements/master/imgs/callstack.png)\n\n# Contributing\n\nThis project welcomes contributions and suggestions.  Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.microsoft.com.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2FRequirements","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicrosoft%2FRequirements","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2FRequirements/lists"}