%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /lib/python2.7/site-packages/salt/modules/
Upload File :
Create Path :
Current File : //lib/python2.7/site-packages/salt/modules/win_dsc.pyc

�
���^c@@sPdZddlmZmZmZddlZddlZddlZddl	Zddl
ZddlmZm
Z
eje�ZdZd�Zdded�Zdddddd	d
�Zdddddd	d�Zdd	d�Zd
�Zed�Zd�Zd�Zd�Zd�Zdddddddddedd�ZdS(u�
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
i(tabsolute_importtunicode_literalstprint_functionN(tCommandExecutionErrortSaltInvocationErrorudsccC@s�tjjj�s)tjd�tdfStdd�}|dsZtjd�tdfStjjj	|ddd�r�tjd	�td	fSt
S(
u8
    Set the system module of the kernel is Windows
    u&DSC: Only available on Windows systemsucmd.shell_infou
powershellu	installeduDSC: Requires PowerShelluversionu<u5.0u#DSC: Requires PowerShell 5 or later(tsalttutilstplatformt
is_windowstlogtdebugtFalset__salt__tversionstcomparet__virtualname__(tpowershell_info((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt__virtual__%s






ic
C@s/d|j�kr'dj||�}ntjd|�td|ddd|dtd	|�}d
|kru|d
=nd|ks�|ddkr�td
j|�d|��n|ddkr�d|d<ny#tjj	j
|ddt�}Wn#tk
rtdd|��nXtj
dj|��|S(u�
    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.
    uconvertto-jsonu{0} | ConvertTo-Json -Depth {1}uDSC: %sucmd.run_alltshellu
powershelltcwdtpython_shelltignore_retcodeupiduretcodeiuIssue executing PowerShell {0}tinfoustdoutuu{}tstrictuNo JSON results from PowerShelluDSC: Returning "{0}"(tlowertformatR	R
RtTrueRRRtjsontloadsRt
ValueErrorR(tcmdRt
json_depthRtresultstret((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt_pshell<s(	

#
ubasec	C@sjtd|d|d|d|d|d|d|�}|jd�rbtjj|d	�}t|�StSd
S(ux

    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.

            .. 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
    tpathtsourcetconfig_nametconfig_datatconfig_data_sourcetscript_parameterstsalt_envuExistsuFullNameN(tcompile_configtgettosR#tdirnametapply_configR(	R#R$R%R&R'R(R)R!tconfig_path((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt
run_config_sI	
c	C@s�|rxtjd|�tdd|d|d|dt�}|sxdj|�}tjdj|��t|��qxn|r�tjd|�tdd|d|d|dt�}|s�dj|�}tjdj|��t|��q�ntjj	|�s6d	j|�}tjdj|��t|��n|dkrgtjjtjj|��d
}ntjj
|�}	|g}
|r�|
j|�n|
jd�dj|
�}
t|
|	�}|r�|jd
�r�tjd|�|Snd|g}
|r|
j|�n|
jd|g�|r:|
j|�n|
jd�dj|
�}
t|
|	�}|r�|jd
�r�tjd|�|Sndj|�}|dj|�7}tjd|�t|��dS(u1	
    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
    uDSC: Caching %sucp.get_fileR#tdesttsaltenvtmakedirsuFailed to cache {0}uDSC: {0}u"{0}" not foundiu�| Select-Object -Property FullName, Extension, Exists, @{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) -Format g}}u uExistsuDSC: Compile Config: %su.u;uFailed to compile config: {0}u
Returned: {0}uDSC: %sN(R	RRRRterrorRR,R#texiststNonetsplitexttbasenameR-tappendtjoinR"R+textend(R#R$R%R&R'R(R)tcached_filesR4RRR!((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyR*�slC		%	

cC@s�|}|rtjjtjj|��}tjjtjj|��}|j�|j�kr�dj||�}tjd|�ntjjtjj|��}tj	d|�t
d|||�}|sdj|�}tjdj|��t|��qtjj|d�}ntjj
|�sbdj|�}tjdj|��t|��nd	j|�}	t|	�d
}	t|	�}
tj	d|
�|
dkp�|
ikS(
u�
    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 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

    u{0}\{1}uDSC: %s appended to the path.uDSC: Caching %su
cp.get_diruFailed to copy {0}uDSC: {0}iu
{0} not foundu/Start-DscConfiguration -Path "{0}" -Wait -Forceu4$status = Get-DscConfigurationStatus; $status.StatusuDSC: Apply Config: %suSuccess(R,R#R8tnormpathRRR	R
R-RRR4RR5R"(R#R$R)tconfigt	path_nametsource_namet	dest_pathR<R4RR!((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyR.Ls2(
cC@s�d}yt|dt�}Wn8tk
rV}d|jdkrPtd��n�nXt�}|r�d|dkr�i||dd<nxe|D]Z}i||d|d<x;|D]3}|d	kr�||||d|d|<q�q�Wq�Wn|S(
u

    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
    u<Get-DscConfiguration | Select-Object * -ExcludeProperty Cim*Ru$Current configuration does not existustderruNot ConfigureduConfigurationNameiu
ResourceId(uConfigurationNameu
ResourceId(R"RRRtdict(Rt
raw_configtexcR>titemtkey((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt
get_config�s"	

,cC@sid}tjd�yt|�Wn[tk
r~}|jddkr^tdd|j��ntjdj|jd��nXd	}tjd
�yt|�Wn[tk
r�}|jddkr�tdd|j��ntjdj|jd��nX|stSd�}d
jtjdd��}|dj|��|dj|��|dj|��tS(u�
    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. 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
    uStop-DscConfigurationu#DSC: Stopping Running Configurationuretcodeiu Failed to Stop DSC ConfigurationRuDSC: {0}ustdoutuHRemove-DscConfigurationDocument -Stage Current, Pending, Previous -ForceuDSC: Removing Configurationu"Failed to remove DSC ConfigurationcS@sstjj|�rotjdj|��td|�sodj|�}tjdj|��t|��qondS(NuDSC: Removing {0}ufile.removeuFailed to remove {0}uDSC: {0}(	R,R#R5R	RRRR4R(R#R4((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt_remove_fs_objsu{0}\System32\Configurationu
SystemRootu
C:\Windowsu{0}\DSCStatusHistory.mofu{0}\DSCEngineCache.mofu{0}\ConfigurationStatus(R	RR"RRRR,tgetenv(tresetRRDRHtdsc_config_dir((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt
remove_config�s6$
	!
	!	cC@sYd}yt|dt�Wn8tk
rT}d|jdkrNtd��n�nXtS(u�
    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
    uRestore-DscConfigurationRu'A previous configuration does not existustderru Previous Configuration Not Found(R"RRR(RRD((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pytrestore_configscC@sYd}yt|dt�Wn8tk
rT}d|jdkrNtd��n�nXdS(u�
    Tests the current applied DSC Configuration

    Returns:
        bool: True if successfully applied, otherwise False

    CLI Example:

    .. code-block:: bash

        salt '*' dsc.test_config
    uTest-DscConfigurationRu$Current configuration does not existustderruNot ConfiguredN(R"RRR(RRD((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyttest_config7s
cC@sYd}yt|dt�SWn8tk
rT}d|jdkrNtd��n�nXdS(u

    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
    u�Get-DscConfigurationStatus | Select-Object -Property HostName, Status, MetaData, @{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, Type, Mode, RebootRequested, NumberofResourcesRuNo status information availableustderruNot ConfiguredN(R"RRR(RRD((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pytget_config_statusMscC@sd}t|�S(u	
    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
    uGet-DscLocalConfigurationManager | Select-Object -Property ConfigurationModeFrequencyMins, LCMState, RebootNodeIfNeeded, ConfigurationMode, ActionAfterReboot, RefreshMode, CertificateID, ConfigurationID, RefreshFrequencyMins, AllowModuleOverwrite, DebugMode, StatusRetentionTimeInDays (R"(R((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pytget_lcm_configgscC@s�tjddjtjd���}d}|d7}|d7}|r�|d6krnd
j|�}
t|
��n|dj|�7}n|r�t|t�s�dj|�}
t|
��n|d
j|�7}n|r|d7kr�td��n|dj|�7}n|r>t|t�s(td��n|dj|�7}n|d5k	r�t|t�shtd��n|rwd}nd}|dj|�7}n|r�|d8kr�td��n|dj|�7}n|d5k	r|dkr�d5}n|dj|�7}n|d5k	r8|dkr"d5}n|dj|�7}n|d5k	r�t|t�sbtd ��n|rqd}nd}|d!j|�7}n|	tk	r�|	d5kr�d"}	n|	d9kr�td%��n|d&j|	�7}n|
rt|
t�std'��n|d(j|
�7}n|d)7}|d*j|�7}t	|�d+j|�}t
d,|d-d.d/t�}t
d0d1j|��|d2s�tj
d3�tStjd4|�tSd5S(:uG
    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
    uTEMPu{0}\tempuWINDIRuConfiguration SaltConfig {u    Node localhost {u#        LocalConfigurationManager {u	ApplyOnlyuApplyAndMonitoruApplyAndAutoCorrectuYconfig_mode must be one of ApplyOnly, ApplyAndMonitor, or ApplyAndAutoCorrect. Passed {0}u&            ConfigurationMode = "{0}";u/config_mode_freq must be an integer. Passed {0}u1            ConfigurationModeFrequencyMins = {0};uDisableduPushuPullu3refresh_mode must be one of Disabled, Push, or Pullu             RefreshMode = "{0}";urefresh_freq must be an integeru'            RefreshFrequencyMins = {0};u(reboot_if_needed must be a boolean valueu$trueu$falseu%            RebootNodeIfNeeded = {0};uContinueConfigurationuStopConfigurationuMaction_after_reboot must be one of ContinueConfiguration or StopConfigurationu%            ActionAfterReboot = "{0}"uu"            CertificateID = "{0}";u$            ConfigurationID = "{0}";u.allow_module_overwrite must be a boolean valueu'            AllowModuleOverwrite = {0};uNoneuForceModuleImportuAlluQdebug_mode must be one of None, ForceModuleImport, ResourceScriptBreakAll, or Allu            DebugMode = "{0}";u(status_retention_days must be an integeru,            StatusRetentionTimeInDays = {0};u        }}};u'SaltConfig -OutputPath "{0}\SaltConfig"u7Set-DscLocalConfigurationManager -Path "{0}\SaltConfig"ucmd.run_allRu
powershellRufile.removeu{0}\SaltConfiguretcodeu$DSC: LCM config applied successfullyu)DSC: Failed to apply LCM config. Error %sN(u	ApplyOnlyuApplyAndMonitoruApplyAndAutoCorrect(uDisableduPushuPull(uContinueConfigurationuStopConfiguration(uNoneuForceModuleImportuAll(R,RIRRt
isinstancetintR6tboolRR"RRR	RR4(tconfig_modetconfig_mode_freqtrefresh_freqtreboot_if_neededtaction_after_reboottrefresh_modetcertificate_idtconfiguration_idtallow_module_overwritet
debug_modetstatus_retention_daysttemp_dirRR4R!((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pytset_lcm_config}s�K$

									

	

( t__doc__t
__future__RRRtloggingR,tsalt.utils.jsonRtsalt.utils.platformtsalt.utils.versionstsalt.exceptionsRRt	getLoggert__name__R	RRR6RR"R0R*R.RGRLRMRNRORPR`(((s8/usr/lib/python2.7/site-packages/salt/modules/win_dsc.pyt<module>sR	$S�O	(T	 			

Zerion Mini Shell 1.0