HEX
Server: Apache
System: Linux server2.voipitup.com.au 4.18.0-553.109.1.lve.el8.x86_64 #1 SMP Thu Mar 5 20:23:46 UTC 2026 x86_64
User: posscale (1027)
PHP: 8.2.30
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/__pycache__/win_dsc.cpython-310.pyc
o

�N�g0n�@s�dZddlZddlZddlZddlZddlZddlmZm	Z	e�
e�ZdZ
dd�Zd d	d
�Z						d!dd
�Z						d!dd�Zd"dd�Zdd�Zd#dd�Zdd�Zdd�Zdd�Zdd�Z											d$dd�ZdS)%a�
Module for working with Windows PowerShell DSC (Desired State Configuration)

This module is Alpha

This module applies DSC Configurations in the form of PowerShell scripts or
MOF (Managed Object Format) schema files.

Use the ``psget`` module to manage PowerShell resources.

The idea is to leverage Salt to push DSC configuration scripts or MOF files to
the Minion.

:depends:
    - PowerShell 5.0
�N)�CommandExecutionError�SaltInvocationErrorZdsccCsdtjj��s
t�d�dStdd�}|dst�d�dStjj�|dd	d
�r0t�d�dSt	S)
z8
    Set the system module of the kernel is Windows
    �&DSC: Only available on Windows systems)Frzcmd.shell_info�
powershellZ	installed�DSC: Requires PowerShell)Fr�version�<z5.0�#DSC: Requires PowerShell 5 or later)Fr	)
�salt�utils�platformZ
is_windows�log�debug�__salt__ZversionsZcompare�__virtualname__)Zpowershell_info�r�H/opt/saltstack/salt/lib/python3.10/site-packages/salt/modules/win_dsc.py�__virtual__!s


r�FcCs�d|��vr
|�d|��}t�d|�td|d|d|d�}d|vr%|d=d	|vs/|d	d
kr8td|��|d��|d
dkrBd|d
<z
tjjj|d
dd�}Wn
t	y\td|d��wt�
d|�|S)z�
    Execute the desired PowerShell command and ensure that it returns data
    in json format and load that into python. Either return a dict or raise a
    CommandExecutionError.
    zconvertto-jsonz | ConvertTo-Json -Depth �DSC: %s�cmd.run_allrT)�shell�cwd�python_shell�ignore_retcode�pid�retcoderzIssue executing PowerShell ��info�stdout�z{}F)�strictzNo JSON results from PowerShellzDSC: Returning "%s")�lowerr
rrrr
r�json�loads�
ValueErrorr)�cmdrZ
json_depthr�results�retrrr�_pshell8s.��r)�basec		Cs<t|||||||d�}|�d�rtj�|d�}t|�SdS)ax
    Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
    apply it. The PowerShell script can be cached from the master using the
    ``source`` option. If there is more than one config within the PowerShell
    script, the desired configuration can be applied by passing the name in the
    ``config`` option.

    This command would be the equivalent of running ``dsc.compile_config``
    followed by ``dsc.apply_config``.

    Args:

        path (str): The local path to the PowerShell script that contains the
            DSC Configuration. Required.

        source (str): The path to the script on ``file_roots`` to cache at the
            location specified by ``path``. The source file will be cached
            locally and then executed. If source is not passed, the config
            script located at ``path`` will be compiled. Optional.

        config_name (str): The name of the Configuration within the script to
            apply. If the script contains multiple configurations within the
            file a ``config_name`` must be specified. If the ``config_name`` is
            not specified, the name of the file will be used as the
            ``config_name`` to run. Optional.

        config_data (str): Configuration data in the form of a hash table that
            will be passed to the ``ConfigurationData`` parameter when the
            ``config_name`` is compiled. This can be the path to a ``.psd1``
            file containing the proper hash table or the PowerShell code to
            create the hash table.

            .. versionadded:: 2017.7.0

        config_data_source (str): The path to the ``.psd1`` file on
            ``file_roots`` to cache at the location specified by
            ``config_data``. If this is specified, ``config_data`` must be a
            local path instead of a hash table.

            .. versionadded:: 2017.7.0

        script_parameters (str): Any additional parameters expected by the
            configuration script. These must be defined in the script itself.
            Note that these are passed to the script (the outermost scope), and
            not to the dsc configuration inside the script (the inner scope).

            .. versionadded:: 2017.7.0

        salt_env (str): The salt environment to use when copying the source.
            Default is 'base'

    Returns:
        bool: True if successfully compiled and applied, otherwise False

    CLI Example:

    To compile a config from a script that already exists on the system:

    .. code-block:: bash

        salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1

    To cache a config script to the system from the master and compile it:

    .. code-block:: bash

        salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1

    To cache a config script to the system from the master and compile it, passing in `script_parameters`:

    .. code-block:: bash

        salt '*' dsc.run_config path=C:\\DSC\\WebsiteConfig.ps1 source=salt://dsc/configs/WebsiteConfig.ps1 script_parameters="-hostname 'my-computer' -ip '192.168.1.10' -DnsArray '192.168.1.3','192.168.1.4','1.1.1.1'"
    )�path�source�config_name�config_data�config_data_source�script_parameters�salt_env�ExistsZFullNameF)�compile_config�get�osr+�dirname�apply_config)	r+r,r-r.r/r0r1r(Zconfig_pathrrr�
run_config]sS�

r8cCs�|r#t�d|�td|||dd�}|s#d|��}t�d|�t|��|rFt�d|�td|||dd�}|sFd|��}t�d|�t|��tj�|�s[|�d�}t�d|�t|��|durktj�tj�	|��d	}tj�
|�}	|g}
|r{|
�|�|
�d
�d�|
�}
t
|
|	�}|r�|�d�r�t�d
|�|Sd|g}
|r�|
�|�|
�d|g�|r�|
�d|g�|
�d
�d�|
�}
t
|
|	�}|r�|�d�r�t�d
|�|Sd|��}|d|��7}t�d|�t|��)a1	
    Compile a config from a PowerShell script (``.ps1``)

    Args:

        path (str): Path (local) to the script that will create the ``.mof``
            configuration file. If no source is passed, the file must exist
            locally. Required.

        source (str): Path to the script on ``file_roots`` to cache at the
            location specified by ``path``. The source file will be cached
            locally and then executed. If source is not passed, the config
            script located at ``path`` will be compiled. Optional.

        config_name (str): The name of the Configuration within the script to
            apply. If the script contains multiple configurations within the
            file a ``config_name`` must be specified. If the ``config_name`` is
            not specified, the name of the file will be used as the
            ``config_name`` to run. Optional.

        config_data (str): Configuration data in the form of a hash table that
            will be passed to the ``ConfigurationData`` parameter when the
            ``config_name`` is compiled. This can be the path to a ``.psd1``
            file containing the proper hash table or the PowerShell code to
            create the hash table.

            .. versionadded:: 2017.7.0

        config_data_source (str): The path to the ``.psd1`` file on
            ``file_roots`` to cache at the location specified by
            ``config_data``. If this is specified, ``config_data`` must be a
            local path instead of a hash table.

            .. versionadded:: 2017.7.0

        script_parameters (str): Any additional parameters expected by the
            configuration script. These must be defined in the script itself.

            .. versionadded:: 2017.7.0

        salt_env (str): The salt environment to use when copying the source.
            Default is 'base'

    Returns:
        dict: A dictionary containing the results of the compilation

    CLI Example:

    To compile a config from a script that already exists on the system:

    .. code-block:: bash

        salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1

    To cache a config script to the system from the master and compile it:

    .. code-block:: bash

        salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1
    �DSC: Caching %szcp.get_fileT)r+�destZsaltenv�makedirszFailed to cache r�
 not foundNrz�| Where-Object FullName -match '(?<!\.meta)\.mof$' | Select-Object -Property FullName, Extension, Exists, @{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) -Format g}}� r2zDSC: Compile Config: %s�.�;z-ConfigurationDatazFailed to compile config: z
Returned: )r
rr�errorrr5r+�exists�splitext�basenamer6�append�joinr)r4�extend)r+r,r-r.r/r0r1�cached_filesr@rr&r(rrrr3�spE�
�


�



�



r3cCs"|}|r^tj�tj�|��}tj�tj�|��}|��|��kr-|�d|��}t�d|�tj�tj�|��}t�d|�t	d|||�}|sVd|��}t�
d|�t|��tj�|d�}tj�|�ss|�d�}t�
d|�t|��d	|�d
�}	t
|	�d}	t
|	�}
t�d|
�|
d
kp�|
ikS)a�
    Run an compiled DSC configuration (a folder containing a .mof file). The
    folder can be cached from the salt master using the ``source`` option.

    Args:

        path (str): Local path to the directory that contains the .mof
            configuration file to apply. Required.

        source (str): Path to the directory that contains the .mof file on the
            ``file_roots``. The source directory will be copied to the path
            directory and then executed. If the path and source directories
            differ, the source directory will be applied. If source is not
            passed, the config located at ``path`` will be applied. Optional.

        salt_env (str): The salt environment to use when copying your source.
            Default is 'base'

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    To apply a config that already exists on the system

    .. code-block:: bash

        salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration

    To cache a configuration from the master and apply it:

    .. code-block:: bash

        salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration salt://dsc/configs/WebSiteConfiguration

    �\zDSC: %s appended to the path.r9z
cp.get_dirzFailed to copy rrr<zStart-DscConfiguration -Path "z" -Wait -Forcez4$status = Get-DscConfigurationStatus; $status.StatuszDSC: Apply Config: %sZSuccess)r5r+rC�normpathr"r
rr6rrr@rrAr))r+r,r1�config�	path_nameZsource_name�	dest_pathrGr@r&r(rrrr7\s2(

r7c
Cs�d}zt|dd�}Wnty"}zd|jdvrtd���d}~wwt�}|s,td��d|vrC|�d�}|�d	�}|�|||i�n!|D]}d|vrc|�d�}|�d	�}|�|i�||�||�qE|sjtd
��|S)a

    Get the current DSC Configuration

    Returns:
        dict: A dictionary representing the DSC Configuration on the machine

    Raises:
        CommandExecutionError: On failure

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.get_config
    z<Get-DscConfiguration | Select-Object * -ExcludeProperty Cim*T�r�$Current configuration does not exist�stderr�Not ConfiguredNZConfigurationNameZ
ResourceIdzUnable to parse config)r)rr�dict�pop�
setdefault)r&Z
raw_config�excrJr-Zresource_id�itemrrr�
get_config�s4��



�rVc
Cs,d}t�d�zt|�Wn)ty6}z|jddkr#td|jd��t�d|jd�WYd	}~nd	}~wwd
}t�d�zt|�Wn)tym}z|jddkrZtd|jd��t�d|jd�WYd	}~nd	}~ww|srd
Sdd�}d�t�dd��}||�d��||�d��||�d��d
S)a�
    Remove the current DSC Configuration. Removes current, pending, and previous
    dsc configurations.

    .. versionadded:: 2017.7.5

    Args:
        reset (bool):
            Attempts to reset the DSC configuration by removing the following
            from ``C:\Windows\System32\Configuration``:

            - File: DSCStatusHistory.mof
            - File: DSCEngineCache.mof
            - Dir: ConfigurationStatus

            Default is False

            .. warning::
                ``remove_config`` may fail to reset the DSC environment if any
                of the files in the ``ConfigurationStatus`` directory are in
                use. If you wait a few minutes and run again, it may complete
                successfully.

    Returns:
        bool: True if successful

    Raises:
        CommandExecutionError: On failure

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.remove_config True
    zStop-DscConfigurationz#DSC: Stopping Running Configurationrrz Failed to Stop DSC ConfigurationrrrNzHRemove-DscConfigurationDocument -Stage Current, Pending, Previous -ForcezDSC: Removing Configurationz"Failed to remove DSC ConfigurationTcSsJtj�|�r!t�d|�td|�s#d|��}t�d|�t|��dSdS)NzDSC: Removing %s�file.removezFailed to remove r)r5r+rAr
rrr@r)r+r@rrr�_remove_fs_objs
�z%remove_config.<locals>._remove_fs_objz{}\System32\ConfigurationZ
SystemRootz
C:\Windowsz\DSCStatusHistory.mofz\DSCEngineCache.mofz\ConfigurationStatus)r
rr)r�formatr5�getenv)�resetr&rTrXZdsc_config_dirrrr�
remove_config�sD%
���
���
�r\c
CsHd}z	t|dd�WdSty#}zd|jdvrtd���d}~ww)a�
    Reapplies the previous configuration.

    .. versionadded:: 2017.7.5

    .. note::
        The current configuration will be come the previous configuration. If
        run a second time back-to-back it is like toggling between two configs.

    Returns:
        bool: True if successfully restored

    Raises:
        CommandExecutionError: On failure

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.restore_config
    zRestore-DscConfigurationTrMz'A previous configuration does not existrOz Previous Configuration Not FoundN�r)rr)r&rTrrr�restore_config4s���r^c
CsVd}zt|dd�}Wnty"}zd|jdvrtd���d}~ww|s)td��dS)z�
    Tests the current applied DSC Configuration

    Returns:
        bool: True if successfully applied, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.test_config
    zTest-DscConfigurationTrMrNrOrPNr]�r&�resultrTrrr�test_configTs
��rac
CsVd}zt|dd�}Wnty"}zd|jdvrtd���d}~ww|s)td��|S)a

    Get the status of the current DSC Configuration

    Returns:
        dict: A dictionary representing the status of the current DSC
            Configuration on the machine

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.get_config_status
    z�Get-DscConfigurationStatus | Select-Object -Property HostName, Status, MetaData, @{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, Type, Mode, RebootRequested, NumberofResourcesTrMzNo status information availablerOrPNr]r_rrr�get_config_statusms���rbcCsd}t|�S)a	
    Get the current Local Configuration Manager settings

    Returns:
        dict: A dictionary representing the Local Configuration Manager settings
            on the machine

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.get_lcm_config
    aGet-DscLocalConfigurationManager | Select-Object -Property ConfigurationModeFrequencyMins, LCMState, RebootNodeIfNeeded, ConfigurationMode, ActionAfterReboot, RefreshMode, CertificateID, ConfigurationID, RefreshFrequencyMins, AllowModuleOverwrite, DebugMode, StatusRetentionTimeInDays )r))r&rrr�get_lcm_config�s�rccCs~t�dd�t�d���}d}|d7}|d7}|r-|dvr%d�|�}
t|
��|d	|�d
�7}|rDt|t�s=d�|�}
t|
��|d�|�7}|rV|d
vrNtd��|d|�d
�7}|rit|t�satd��|d|�d�7}|dur�t|t�svtd��|r{d}nd}|d|�d�7}|r�|dvr�td��|d|�d�7}|dur�|dkr�d}|d|�d
�7}|dur�|dkr�d}|d|�d
�7}|dur�t|t�s�td��|r�d}nd}|d |�d�7}|	d!ur�|	dur�d"}	|	d#vr�td$��|d%|	�d
�7}|
�rt|
t�s�td&��|d'�|
�7}|d(7}|d)|�d*�7}t|�d+�|�}td,|d-d.d/�}td0|�d1��|d2�s7t	�
d3�d.St	�d4|�d!S)5aG
    For detailed descriptions of the parameters see:
    https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig

    config_mode (str): How the LCM applies the configuration. Valid values
        are:

        - ApplyOnly
        - ApplyAndMonitor
        - ApplyAndAutoCorrect

    config_mode_freq (int): How often, in minutes, the current configuration
        is checked and applied. Ignored if config_mode is set to ApplyOnly.
        Default is 15.

    refresh_mode (str): How the LCM gets configurations. Valid values are:

        - Disabled
        - Push
        - Pull

    refresh_freq (int): How often, in minutes, the LCM checks for updated
        configurations. (pull mode only) Default is 30.

    reboot_if_needed (bool): Reboot the machine if needed after a
        configuration is applied. Default is False.

    action_after_reboot (str): Action to take after reboot. Valid values
        are:

        - ContinueConfiguration
        - StopConfiguration

    certificate_id (guid): A GUID that specifies a certificate used to
        access the configuration: (pull mode)

    configuration_id (guid): A GUID that identifies the config file to get
        from a pull server. (pull mode)

    allow_module_overwrite (bool): New configs are allowed to overwrite old
        ones on the target node.

    debug_mode (str): Sets the debug level. Valid values are:

        - None
        - ForceModuleImport
        - All

    status_retention_days (int): Number of days to keep status of the
        current config.

    .. note::
        Either ``config_mode_freq`` or ``refresh_freq`` needs to be a
        multiple of the other. See documentation on MSDN for more details.

    Returns:
        bool: True if successful, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.set_lcm_config ApplyOnly
    ZTEMPz{}\tempZWINDIRzConfiguration SaltConfig {z    Node localhost {z#        LocalConfigurationManager {)Z	ApplyOnlyZApplyAndMonitorZApplyAndAutoCorrectzXconfig_mode must be one of ApplyOnly, ApplyAndMonitor, or ApplyAndAutoCorrect. Passed {}z!            ConfigurationMode = "z";z.config_mode_freq must be an integer. Passed {}z0            ConfigurationModeFrequencyMins = {};)ZDisabledZPushZPullz3refresh_mode must be one of Disabled, Push, or Pullz            RefreshMode = "zrefresh_freq must be an integerz#            RefreshFrequencyMins = r?Nz(reboot_if_needed must be a boolean valuez$truez$falsez!            RebootNodeIfNeeded = )ZContinueConfigurationZStopConfigurationzMaction_after_reboot must be one of ContinueConfiguration or StopConfigurationz!            ActionAfterReboot = "�"r z            CertificateID = "z            ConfigurationID = "z.allow_module_overwrite must be a boolean valuez#            AllowModuleOverwrite = F�None)reZForceModuleImportZAllzQdebug_mode must be one of None, ForceModuleImport, ResourceScriptBreakAll, or Allz            DebugMode = "z(status_retention_days must be an integerz+            StatusRetentionTimeInDays = {};z        }}};zSaltConfig -OutputPath "z\SaltConfig"z6Set-DscLocalConfigurationManager -Path "{}\SaltConfig"rrT)rrrWz\SaltConfigrz$DSC: LCM config applied successfullyz)DSC: Failed to apply LCM config. Error %s)r5rZrYr�
isinstance�int�boolr)rr
rr@)Zconfig_modeZconfig_mode_freqZrefresh_freqZreboot_if_neededZaction_after_rebootZrefresh_modeZcertificate_idZconfiguration_idZallow_module_overwriteZ
debug_modeZstatus_retention_daysZtemp_dirr&r@r(rrr�set_lcm_config�s�M�
���

�
�
�


ri)NrF)NNNNNr*)Nr*)F)NNNNNNNNNFN)�__doc__�loggingr5Zsalt.utils.jsonr
Zsalt.utils.platformZsalt.utils.versionsZsalt.exceptionsrr�	getLogger�__name__r
rrr)r8r3r7rVr\r^rarbrcrirrrr�<module>sZ

'
�f
�
O
2W �