### Example Initial Build Steps Source: https://github.com/azure/guestconfiguration/blob/main/README.md Steps to perform an initial build of the GuestConfiguration repository, including installing required modules, building, importing, and running tests. ```powershell ./build.ps1 -tasks noop -RequiredModules ``` ```powershell ./build.ps1 -tasks build ``` ```powershell Import-Module GuestConfiguration -Force ``` ```powershell ./build.ps1 -tasks test ``` ```powershell ./build.ps1 -tasks test -PesterScript ./Tests/Unit/Public/foo.tests.ps1 ``` -------------------------------- ### Build GuestConfiguration Repository Source: https://github.com/azure/guestconfiguration/blob/main/README.md Commands to build the GuestConfiguration repository. Ensure you have the necessary modules installed before building. ```powershell ./build.ps1 -tasks build ``` ```powershell ./build.ps1 -tasks noop ``` ```powershell ./build.ps1 -tasks noop -RequiredModules ``` ```powershell ./build.ps1 -tasks test ``` ```powershell ./build.ps1 -tasks test -PesterScript [Insert Path to Script] ``` ```powershell ./build.ps1 -tasks test, build ``` -------------------------------- ### Install and Import GuestConfiguration Module Source: https://context7.com/azure/guestconfiguration/llms.txt Installs the GuestConfiguration module from the PowerShell Gallery and imports it into the current session. Requires PowerShell 7.1.3+ on Windows or 7.2 preview 6+ on Linux. ```powershell Install-Module -Name GuestConfiguration -Repository PSGallery Import-Module GuestConfiguration ``` -------------------------------- ### Install GuestConfiguration Module Source: https://github.com/azure/guestconfiguration/blob/main/README.md Install the GuestConfiguration module from the PowerShell Gallery using PowerShellGet. This module is required for managing guest configurations. ```powershell Install-Module -Name GuestConfiguration -Repository PSGallery ``` -------------------------------- ### Start-GuestConfigurationPackageRemediation Source: https://context7.com/azure/guestconfiguration/llms.txt Applies a Guest Configuration package to the local machine in Set mode. The package must have been built with `-Type AuditAndSet`. Returns a compliance report. ```APIDOC ## Start-GuestConfigurationPackageRemediation Applies a Guest Configuration package to the **local machine** in Set mode, actively modifying machine state to match the desired configuration. The package must have been built with `-Type AuditAndSet`. Returns the same compliance-report object as `Get-GuestConfigurationPackageComplianceStatus`, where `complianceStatus` should be `True` after a successful remediation. ### Method ```powershell Start-GuestConfigurationPackageRemediation ``` ### Parameters #### Path - **Path** (string) - Required - Path to the Guest Configuration package zip file. #### Parameter - **Parameter** (array) - Optional - An array of hashtables, where each hashtable defines a runtime parameter for the package. ### Request Example ```powershell # Simple remediation $result = Start-GuestConfigurationPackageRemediation -Path ./packages/EnforceWindowsTimeZone.zip # Remediation with runtime parameters $params = @( @{ ResourceType = 'MyFile'; ResourceId = 'EnsureFileExists'; ResourcePropertyName = 'Ensure'; ResourcePropertyValue = 'Present' }, @{ ResourceType = 'MyFile'; ResourceId = 'EnsureFileExists'; ResourcePropertyName = 'Path'; ResourcePropertyValue = 'C:\required\config.txt' } ) $result = Start-GuestConfigurationPackageRemediation -Path ./packages/EnforceFilePresence.zip -Parameter $params ``` ### Response #### Success Response Returns an object with the following properties: - **complianceStatus** (boolean) - True if the machine is compliant after remediation. - **resources** (array) - An array of resource compliance details. #### Response Example ```json { "complianceStatus": true, "resources": [ { "complianceStatus": true, "reasons": [] } ] } ``` ``` -------------------------------- ### Create Guest Configuration Package Source: https://github.com/azure/guestconfiguration/blob/main/source/en-US/about_Guestconfiguration.help.txt Use this command to create a content package (.zip) from a compiled DSC configuration (.mof) file. The -Force parameter overwrites existing packages. ```powershell New-GuestConfigurationPackage -Path . -Configuration MyPolicy.mof -Name MyPolicy -Force ``` -------------------------------- ### Sign Guest Configuration Package (Linux) Source: https://context7.com/azure/guestconfiguration/llms.txt On Linux, this command generates a SHA-256 hash file for a Guest Configuration package and signs it with a GPG key. The signed package is output as `_signed.zip`. Ensure GPG keys are generated and exported prior to signing. ```bash # bash: generate keys # gpg --gen-key # gpg --output ./certs/public.gpg --export your@email.com ``` -------------------------------- ### Create Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Creates a Guest Configuration package from a .mof file. This package can be used for auditing or setting configurations on machines. Ensure the output path exists. ```powershell $pkg = New-GuestConfigurationPackage ` -Name 'AuditNTPService' ` -Configuration ./mof/localhost.mof ` -Version '1.0.0' ` -Type 'AuditAndSet' ` -Path ./packages ` -Force ``` -------------------------------- ### GuestConfiguration Branching Workflow Source: https://github.com/azure/guestconfiguration/wiki/Home Illustrates the recommended workflow for managing changes and releases in the GuestConfiguration project, from feature branches to production. ```text - feature/name | - PR to prerelease Evaluated by test automation (mock'd Azure cmdlets Changes made by author if needed Reviewed by maintainers Approved, merge/push Evaluated by private builds with full integration tests Minor fixes made if needed Release to PowerShell Gallery (Wait minimum 1 week for feedback) If changes are required, update minor version and re-publish to prerelease | - PR to master Approved, merge/push Evaluated by private builds with full integration tests (same tests as prerelease, should never be an issue) Release to PowerShell Gallery ``` -------------------------------- ### Create Guest Configuration Package with Extra Files Source: https://context7.com/azure/guestconfiguration/llms.txt Creates a Guest Configuration package that includes additional files, such as scripts or data files, alongside the DSC configuration. Use the FilesToInclude parameter to specify these files. ```powershell # ── Package with extra files ─────────────────────────────────── $pkgExtra = New-GuestConfigurationPackage ` -Name 'AuditWithFiles' ` -Configuration ./mof/localhost.mof ` -FilesToInclude @('./scripts/helper.ps1', './data/') ` -Path ./packages ` -Force ``` -------------------------------- ### Create AuditAndSet Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Creates a Guest Configuration package that supports both auditing and remediation (AuditAndSet). This package can enforce desired states and includes a frequency setting in minutes for checks. ```powershell # ── AuditAndSet package (supports remediation) ───────────────────────────────── $pkgSet = New-GuestConfigurationPackage ` -Name 'EnforceWindowsTimeZone' ` -Configuration ./mof/localhost.mof ` -Version '1.0.0' ` -Type 'AuditAndSet' ` -FrequencyMinutes 30 ` -Path ./packages ` -Force ``` -------------------------------- ### Create Linux Guest Configuration Package with InSpec Source: https://context7.com/azure/guestconfiguration/llms.txt Creates a Guest Configuration package for Linux systems, incorporating a Chef InSpec profile for compliance checks. The InSpec profile directory must follow a specific layout. ```powershell # ── Linux package with Chef InSpec profile ───────────────────────────────────── # InSpec profile directory layout: # ./inspec-profiles/ # linux-path/ # inspec.yml # controls/ # linux-path.rb $pkgLinux = New-GuestConfigurationPackage ` -Name 'AuditLinuxPath' ` -Configuration ./mof/InSpec_Config.mof ` -Version '1.0.0' ` -Type 'Audit' ` -ChefInspecProfilePath ./inspec-profiles ` -Path ./packages ` -Force ``` -------------------------------- ### Sign Guest Configuration Package (Windows) Source: https://context7.com/azure/guestconfiguration/llms.txt Signs a Guest Configuration package on Windows using an X.509 code-signing certificate and Authenticode. This process creates a catalog file (.cat) and outputs a signed package. A self-signed certificate can be used for testing purposes. ```powershell $cert = New-SelfSignedCertificate ` -Type 'CodeSigningCert' ` -DnsName 'GCEncryptionCertificate' ` -HashAlgorithm 'SHA256' $pwd = ConvertTo-SecureString -String 'Password1234' -Force -AsPlainText $cert | Export-PfxCertificate -FilePath C:\certs\GCPrivateKey.pfx -Password $pwd $cert | Export-Certificate -FilePath C:\certs\GCPublicKey.cer -Force Import-PfxCertificate ` -FilePath C:\certs\GCPrivateKey.pfx ` -Password $pwd ` -CertStoreLocation 'Cert:\LocalMachine\My' $signingCert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq 'CN=GCEncryptionCertificate' } $signed = Protect-GuestConfigurationPackage ` -Path ./packages/AuditWindowsTimeZone.zip ` -Certificate $signingCert ` -Verbose # Verify signature $sig = Get-AuthenticodeSignature -FilePath ( [System.IO.Path]::ChangeExtension($signed.Path, '.cat')) $sig.SignerCertificate.Thumbprint -eq $signingCert.Thumbprint # True ``` -------------------------------- ### Check Guest Configuration Package Compliance Source: https://context7.com/azure/guestconfiguration/llms.txt Use this cmdlet to check the compliance status of a Guest Configuration package on a machine. It supports runtime parameter overrides for flexible configuration. Non-compliance is indicated by a false complianceStatus and detailed reasons are provided. ```powershell $params = @( @{ ResourceType = 'Service'; ResourceId = 'windowsService'; ResourcePropertyName = 'Name'; ResourcePropertyValue = 'WinRM' }, @{ ResourceType = 'Service'; ResourceId = 'windowsService'; ResourcePropertyName = 'State'; ResourcePropertyValue = 'Running' } ) $result = Get-GuestConfigurationPackageComplianceStatus ` -Path ./packages/AuditWindowsService.zip ` -Parameter $params if (-not $result.complianceStatus) { Write-Warning "Machine is NON-COMPLIANT. Reasons:" $result.resources.reasons | ForEach-Object { Write-Warning " $" } } ``` -------------------------------- ### Create Guest Configuration Policy Definition Source: https://context7.com/azure/guestconfiguration/llms.txt Creates a Guest Configuration policy definition using the uploaded package's content URI. This policy can then be published to Azure Policy. ```powershell $policy = New-GuestConfigurationPolicy ` -DisplayName 'Enforce NTP Service Running' ` -Description 'Ensures the Windows Time service is running on all VMs.' ` -PolicyId (New-Guid) ` -PolicyVersion '1.0.0' ` -ContentUri $uri ` -Platform 'Windows' ` -Mode 'ApplyAndAutoCorrect' ` -Path ./policyDefinitions ``` -------------------------------- ### Compile DSC Configuration to .mof Source: https://context7.com/azure/guestconfiguration/llms.txt Compiles a Desired State Configuration (DSC) configuration into a Managed Object Format (.mof) file. This is the first step in creating a Guest Configuration package. ```powershell Configuration AuditNTPService { Import-DscResource -ModuleName 'PSDesiredStateConfiguration' Node localhost { Service NTPService { Name = 'w32tm' State = 'Running' } } } AuditNTPService -OutputPath ./mof ``` -------------------------------- ### Sign Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Signs a Guest Configuration package using GPG. The public key must be deployed to target Linux machines. ```powershell # gpg --output ./certs/private.gpg --export-secret-key your@email.com $signed = Protect-GuestConfigurationPackage ` -Path ./packages/AuditLinuxPath.zip ` -PrivateGpgKeyPath ./certs/private.gpg ` -PublicGpgKeyPath ./certs/public.gpg ` -Verbose # The public key must be deployed to target Linux machines at: # /usr/local/share/ca-certificates/gc/pub_keyring.gpg ``` -------------------------------- ### Create Audit-Only Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Creates an audit-only Guest Configuration package from a compiled DSC configuration MOF file. The package includes the MOF, DSC module dependencies, and metadata. Use this for compliance checks without remediation. ```powershell # ── Step 1: Write and compile a DSC configuration ────────────────────────────── Configuration AuditWindowsTimeZone { Import-DscResource -ModuleName 'ComputerManagementDsc' -ModuleVersion '8.2.0' Node localhost { TimeZone TimeZoneExample { IsSingleInstance = 'Yes' TimeZone = 'Pacific Standard Time' } } } AuditWindowsTimeZone -OutputPath ./mof # ── Step 2: Build an Audit-only package ──────────────────────────────────────── $pkg = New-GuestConfigurationPackage ` -Name 'AuditWindowsTimeZone' ` -Configuration ./mof/localhost.mof ` -Version '1.0.0' ` -Type 'Audit' ` -Path ./packages ` -Force ``` -------------------------------- ### Check Local Compliance Status of Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Runs a Guest Configuration package against the local machine to validate its compliance status before publishing. This uses the GC worker agent and returns a detailed compliance report. ```powershell # ── Basic compliance check ───────────────────────────────────────────────────── $result = Get-GuestConfigurationPackageComplianceStatus ` -Path ./packages/AuditWindowsTimeZone.zip $result.complianceStatus # True / False $result.assignmentName # AuditWindowsTimeZone $result.startTime # 5/9/2022 11:42:10 PM $result.endTime # 5/9/2022 11:42:12 PM # Inspect per-resource detail $result.resources | ForEach-Object { [PSCustomObject]@{ Resource = $_.properties.ResourceID ComplianceStatus = $_.complianceStatus Reasons = $_.reasons -join '; ' } } # ── Compliance check with runtime parameters ─────────────────────────────────── ``` -------------------------------- ### Upload Package to Azure Blob Storage Source: https://context7.com/azure/guestconfiguration/llms.txt Uploads a Guest Configuration package to Azure Blob Storage using Az.Storage module. Requires an existing storage account. ```powershell # ── Prerequisite: upload the package to Azure Blob Storage ──────────────────── # (requires Az.Storage module and an existing storage account) $ctx = (Get-AzStorageAccount -ResourceGroupName 'myRG' -Name 'mySA').Context Set-AzStorageBlobContent ` -Container 'guestconfig' ` -File './packages/AuditWindowsTimeZone.zip' ` -Blob 'AuditWindowsTimeZone.zip' ` -Context $ctx $sasToken = New-AzStorageBlobSASToken ` -Container 'guestconfig' ` -Blob 'AuditWindowsTimeZone.zip' ` -Permission 'r' ` -ExpiryTime (Get-Date).AddYears(1) ` -Context $ctx ` -FullUri # $sasToken is the ContentUri value ``` -------------------------------- ### Protect-GuestConfigurationPackage Source: https://context7.com/azure/guestconfiguration/llms.txt Signs a Guest Configuration package to guarantee integrity. On Windows, it uses Authenticode. On Linux, it uses GPG. ```APIDOC ## Protect-GuestConfigurationPackage Signs a Guest Configuration package to guarantee integrity. On **Windows**, it creates a catalog file (`.cat`) and signs it using an X.509 code-signing certificate via Authenticode. On **Linux**, it generates a SHA-256 hash file and signs it with a GPG key. The signed package is output as `_signed.zip` beside the original. ### Method ```powershell Protect-GuestConfigurationPackage ``` ### Parameters #### Path - **Path** (string) - Required - Path to the Guest Configuration package zip file. #### Certificate - **Certificate** (X509Certificate2) - Required (Windows) - The code-signing certificate to use for signing. ### Request Example ```powershell # Windows: sign with a self-signed certificate (testing only) $cert = New-SelfSignedCertificate -Type 'CodeSigningCert' -DnsName 'GCEncryptionCertificate' -HashAlgorithm 'SHA256' $pwd = ConvertTo-SecureString -String 'Password1234' -Force -AsPlainText $cert | Export-PfxCertificate -FilePath 'C:\certs\GCPrivateKey.pfx' -Password $pwd $signingCert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq 'CN=GCEncryptionCertificate' } $signed = Protect-GuestConfigurationPackage -Path './packages/AuditWindowsTimeZone.zip' -Certificate $signingCert -Verbose # Linux: sign with GPG keys (requires GPG setup) # gpg --output ./certs/public.gpg --export your@email.com ``` ### Response #### Success Response Returns an object with the following properties: - **Name** (string) - The name of the signed package. - **Path** (string) - The full path to the generated signed package. #### Response Example ```json { "Name": "AuditWindowsTimeZone", "Path": "C:\\packages\\AuditWindowsTimeZone_signed.zip" } ``` ``` -------------------------------- ### Sign Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Signs a Guest Configuration package using a local certificate. This ensures the integrity and authenticity of the package, a requirement for deployment in production environments. ```powershell $cert = Get-ChildItem Cert:\[LocalMachine](https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-childitem?view=powershell-7.5#parameters)\[My](https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-childitem?view=powershell-7.5#parameters) | Where-Object { $_.Subject -eq 'CN=GCEncryptionCertificate' } $signed = Protect-GuestConfigurationPackage -Path $pkg.Path -Certificate $cert ``` -------------------------------- ### Generate Auto-Remediation Policy with Parameters Source: https://context7.com/azure/guestconfiguration/llms.txt Generates a DeployIfNotExists Azure Policy definition with parameters for enforcing a Windows service state. Supports auto-correction. ```powershell # ── Auto-remediation policy (DeployIfNotExists) with parameters ─────────────── $policyParams = @( @{ Name = 'ServiceName' DisplayName = 'Windows Service Name' Description = 'Name of the Windows service to audit.' ResourceType = 'Service' ResourceId = 'windowsService' ResourcePropertyName = 'Name' DefaultValue = 'WinRM' AllowedValues = @('WinRM', 'WSearch', 'wscsvc') }, @{ Name = 'ServiceState' DisplayName = 'Windows Service State' Description = 'Expected state of the Windows service.' ResourceType = 'Service' ResourceId = 'windowsService' ResourcePropertyName = 'State' DefaultValue = 'Running' AllowedValues = @('Running', 'Disabled') } ) $policy = New-GuestConfigurationPolicy ` -DisplayName 'Enforce Windows Service State' ` -Description 'Enforces the running state of a specified Windows service.' ` -PolicyId (New-Guid) ` -PolicyVersion '1.0.0' ` -ContentUri $sasToken ` -Platform 'Windows' ` -Mode 'ApplyAndAutoCorrect' ` -Parameter $policyParams ` -Tag @{ Environment = 'Production'; Owner = 'OpsTeam' } ` -Path ./policyDefinitions New-AzPolicyDefinition -Name $policy.PolicyId -Policy $policy.Path ``` -------------------------------- ### Remediate Guest Configuration Package Source: https://context7.com/azure/guestconfiguration/llms.txt Applies a Guest Configuration package in Set mode to enforce compliance. The package must be built with '-Type AuditAndSet'. Successful remediation should result in a complianceStatus of True. Resource-specific reasons for remediation failure are available. ```powershell $result = Start-GuestConfigurationPackageRemediation ` -Path ./packages/EnforceWindowsTimeZone.zip $result.complianceStatus # True after successful apply ``` ```powershell $params = @( @{ ResourceType = 'MyFile'; ResourceId = 'EnsureFileExists'; ResourcePropertyName = 'Ensure'; ResourcePropertyValue = 'Present' }, @{ ResourceType = 'MyFile'; ResourceId = 'EnsureFileExists'; ResourcePropertyName = 'Path'; ResourcePropertyValue = 'C:\required\config.txt' } ) $result = Start-GuestConfigurationPackageRemediation ` -Path ./packages/EnforceFilePresence.zip ` -Parameter $params if ($result.complianceStatus) { Write-Host "Remediation succeeded. Machine is now compliant." } else { Write-Warning "Remediation did not fully succeed. Review resource reasons:" $result.resources | Where-Object { -not $_.complianceStatus } | ForEach-Object { $_.reasons | ForEach-Object { Write-Warning " $" } } } ``` -------------------------------- ### Test Package Compliance Locally Source: https://context7.com/azure/guestconfiguration/llms.txt Tests the compliance status of a Guest Configuration package locally before deployment. This helps in validating the package's behavior without Azure resources. ```powershell $compliance = Get-GuestConfigurationPackageComplianceStatus -Path $pkg.Path Write-Host "Local compliance: $($compliance.complianceStatus)" ``` -------------------------------- ### Publish Policy to Azure Policy Source: https://context7.com/azure/guestconfiguration/llms.txt Publishes the created Guest Configuration policy definition to Azure Policy. This makes the policy available for assignment to Azure resources. ```powershell $azPolicy = New-AzPolicyDefinition -Name $policy.PolicyId -Policy $policy.Path Write-Host "Published policy: $($azPolicy.ResourceId)" ``` -------------------------------- ### Upload Signed Package to Azure Blob Storage Source: https://context7.com/azure/guestconfiguration/llms.txt Uploads the signed Guest Configuration package to Azure Blob Storage and generates a SAS token for access. This makes the package accessible for policy creation. ```powershell $ctx = (Get-AzStorageAccount -ResourceGroupName 'myRG' -Name 'mySA').Context Set-AzStorageBlobContent -Container 'gc' -File $signed.Path -Blob 'AuditNTPService_signed.zip' -Context $ctx $uri = New-AzStorageBlobSASToken -Container 'gc' -Blob 'AuditNTPService_signed.zip' ` -Permission 'r' -ExpiryTime (Get-Date).AddYears(1) -Context $ctx -FullUri ``` -------------------------------- ### Remediate Non-Compliant Package Source: https://context7.com/azure/guestconfiguration/llms.txt Remediates a non-compliant Guest Configuration package if it is of type 'AuditAndSet'. This step actively applies the configuration to bring the machine into compliance. ```powershell if (-not $compliance.complianceStatus) { $remediation = Start-GuestConfigurationPackageRemediation -Path $pkg.Path Write-Host "Post-remediation status: $($remediation.complianceStatus)" ``` -------------------------------- ### Generate Audit-Only Policy Source: https://context7.com/azure/guestconfiguration/llms.txt Generates an AuditIfNotExists Azure Policy definition from a Guest Configuration package. The policy audits the time zone on Windows VMs. ```powershell # ── Audit-only policy (AuditIfNotExists) ────────────────────────────────────── $policy = New-GuestConfigurationPolicy ` -DisplayName 'Audit Windows Time Zone' ` -Description 'Audits the time zone configured on Windows VMs.' ` -PolicyId (New-Guid) ` -PolicyVersion '1.0.0' ` -ContentUri $sasToken ` -Platform 'Windows' ` -Mode 'Audit' ` -Path ./policyDefinitions # Publish to Azure New-AzPolicyDefinition ` -Name $policy.PolicyId ` -Policy $policy.Path ``` -------------------------------- ### Generate Linux Policy Targeting Azure VMs Source: https://context7.com/azure/guestconfiguration/llms.txt Generates an Azure Policy definition for Linux VMs using a user-assigned managed identity for content download. Excludes Azure Arc machines. ```powershell # ── Linux policy targeting only Azure VMs (user-assigned managed identity) ──── $policy = New-GuestConfigurationPolicy ` -DisplayName 'Audit Linux Path' ` -Description 'Audits that /tmp exists on Linux VMs.' ` -PolicyId (New-Guid) ` -PolicyVersion '1.0.0' ` -ContentUri 'https://mystorage.blob.core.windows.net/gc/AuditLinuxPath.zip' ` -LocalContentPath ./packages/AuditLinuxPath.zip ` -ManagedIdentityResourceId '/subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/' ` -Platform 'Linux' ` -ExcludeArcMachines ` -Path ./policyDefinitions # ── Output file name convention ─────────────────────────────────────────────── # Audit mode → _AuditIfNotExists.json # Apply modes → _DeployIfNotExists.json ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.