- Learning PowerShell DSC(Second Edition)
- James Pogran
- 415字
- 2021-07-02 18:31:19
Idempotence
Idempotence is an important concept, sometimes confusing, that we will touch on many times throughout this book. Idempotence is defined as an operation that has no additional effect if it is called more than once with the same input. Put another way, it is an operation that can be executed as many times as desired, and it will only change the system state if, and only if, it is not what the desired state is. For example, a PowerShell function looks for the x state and guarantees that it will only change the state of the system if it is not x.
It may seem silly to state something as obvious as this. If you feel this way, think of an MSI installer that installs version 1.1.1.0 of an imaginary software product. When you run the MSI, it only ever installs the software if it isn't already present on the system or if the version present is older than the current version. No matter how many times you execute the MSI, it will only change the system if version 1.1.1.0 is not on the system. This is idempotency. The MSI will only ever change the system state if it is not the desired state, no matter how many times you run it.
Idempotent operations are often used in network protocols or API design between dependent systems and are used in DSC by DSC resources. DSC resources are required to be idempotent in that they do not change the system if the system is in the state that the resource expects it to be in. For example, a DSC resource that operates on Windows Services will only try to start a given service if it is stopped, not if it is started. Another example is the DSC file resource, as that will change a file only if the contents do not match the expected string. By requiring idempotency, DSC resources can be run as many times as you want without ever performing an unexpected change.
When you install a piece of software on a machine that already has that software installed on it, you don't want there to be two copies of the software after you're done. You want the installer to be smart enough to detect the version of the currently installed software and then examine the version that you're attempting to install and ultimately decide that the versions match and no installation needs to be done. That is idempotency in a nutshell.