Git Product home page Git Product logo

webadministrationdsc's Introduction

WebAdministrationDsc

This module contains DSC resources for the management and configuration of Microsoft Internet Information Services (IIS).

Build Status Azure DevOps coverage (branch) Azure DevOps tests codecov PowerShell Gallery (with prereleases) PowerShell Gallery

Code of Conduct

This project has adopted this Code of Conduct.

Releases

For each merge to the branch main a preview release will be deployed to PowerShell Gallery. Periodically a release version tag will be pushed which will deploy a full release to PowerShell Gallery.

Contributing

Please check out common DSC Community contributing guidelines.

Change log

A full list of changes in each version can be found in the change log.

Documentation

The documentation can be found in the WebAdministration Wiki. The DSC resources schema files is used to automatically update the documentation on each PR merge.

Examples

You can review the Examples directory in the WebAdministration module for some general use scenarios for all of the resources that are in the module.

The resource examples are also available in the WebAdministration Wiki.

Installation

From GitHub source code

To manually install the module, download the source code from GitHub and unzip the contents to the '$env:ProgramFiles\WindowsPowerShell\Modules' folder.

From PowerShell Gallery

To install from the PowerShell gallery using PowerShellGet (in PowerShell 5.0) run the following command:

Find-Module -Name WebAdministrationDsc | Install-Module

To confirm installation, run the below command and ensure you see the DSC resources available:

Get-DscResource -Module WebAdministrationDsc

Requirements

The minimum Windows Management Framework (PowerShell) version required is 4.0 or higher.

Note: In the CI pipeline the resource are only tested on PowerShell 5.1, so PowerShell 4.0 support is best effort as this time.

Examples

You can review the Examples directory in the WebAdministrationDsc module for some general use scenarios for all of the resources that are in the module.

Resources

WebApplicationHandler

  • [String] Ensure (Write): Indicates if the application handler exists. Set this property to Absent to ensure that the application handler does not exist. Default value is 'Present'. { Present | Absent }
  • [String] Name (Key): Specifies the name of the new request handler.
  • [String] Location (Write): Specifies The location of the configuration setting. Location tags are frequently used for configuration settings that must be set more precisely than per application or per virtual directory.
  • [String] PhysicalHandlerPath (Write): Specifies the physical path to the handler. This parameter applies to native modules only.
  • [String] Verb (Write): Specifies the HTTP verbs that are handled by the new handler.
  • [String] Modules (Write): Specifies the modules used for the handler.
  • [String[]] Path (Required): Specifies an IIS configuration path.
  • [String] PreCondition (Write): Specifies preconditions for the new handler.
  • [String] RequiredAccess (Write): Specifies the user rights that are required for the new handler. { None | Read | Write | Script | Execute }
  • [String] ScriptProcessor (Write): Specifies the script processor that runs for the module.
  • [String] Type (Write): Specifies the managed type of the new module. This parameter applies to managed modules only.
  • [String] ResourceType (Write): Specifies the resource type this handler runs. See ResourceType.
  • [Boolean] AllowPathInfo (Write): Specifies whether the handler processes full path information in a URI, such as contoso/marketing/imageGallery.aspx. If the value is true, the handler processes the full path, contoso/marketing/imageGallery. If the value is false, the handler processes only the last section of the path, /imageGallery.
  • [UInt64] ResponseBufferLimit (Write): Specifies the maximum size, in bytes, of the response buffer for a request handler runs.

IisFeatureDelegation

This resource manages the IIS configuration section locking (overrideMode) to control what configuration can be set in web.config.

  • Filter: Specifies the IIS configuration section to lock or unlock in this format: /system.webserver/security/authentication/anonymousAuthentication
  • OverrideMode: Mode of that section { Allow | Deny }
  • Path: Specifies the configuration path. This can be either an IIS configuration path in the format computer machine/webroot/apphost, or the IIS module path in this format IIS:\sites\Default Web Site. WARNING: both path types can be used to manage the same feature delegation, however, there is no way to control if two resources in the configuration set the same feature delegation.

IISLogging

Note This will set the logfile settings for all websites; for individual websites use the Log options under WebSite

  • LogPath: The directory to be used for logfiles.
  • LogFlags: The W3C logging fields: The values that are allowed for this property are: Date,Time,ClientIP,UserName,SiteName,ComputerName,ServerIP,Method,UriStem,UriQuery,HttpStatus,Win32Status,BytesSent,BytesRecv,TimeTaken,ServerPort,UserAgent,Cookie,Referer,ProtocolVersion,Host,HttpSubStatus
  • LogPeriod: How often the log file should rollover. The values that are allowed for this property are: Hourly,Daily,Weekly,Monthly,MaxSize
  • LogTruncateSize: How large the file should be before it is truncated. If this is set then LogPeriod will be ignored if passed in and set to MaxSize. The value must be a valid integer between 1048576 (1MB) and 4294967295 (4GB).
  • LoglocalTimeRollover: Use the localtime for file naming and rollover. The acceptable values for this property are: $true, $false
  • LogFormat: Format of the Logfiles. NoteOnly W3C supports LogFlags. The acceptable values for this property are: IIS,W3C,NCSA
  • LogTargetW3C: Log Target of the W3C Logfiles. The acceptable values for this property are: File,ETW,File,ETW
  • LogCustomFields: Custom logging field information the form of an array of embedded instances of the DSC_LogCustomField CIM class that implements the following properties:
    • LogFieldName: Field name to identify the custom field within the log file. Please note that the field name cannot contain spaces.
    • SourceType: You can select RequestHeader, ResponseHeader, or ServerVariable (note that enhanced logging cannot log a server variable with a name that contains lower-case characters - to include a server variable in the event log just make sure that its name consists of all upper-case characters).
    • SourceName: Name of the HTTP header or server variable (depending on the Source Type you selected) that contains a value that you want to log.

IisMimeTypeMapping

  • Extension: The file extension to map such as .html or .xml
  • MimeType: The MIME type to map that extension to such as text/html
  • Ensure: Ensures that the MIME type mapping is Present or Absent.

IisModule

  • Path: The path to the module to be registered.
  • Name: The logical name to register the module as in IIS.
  • RequestPath: The allowed request paths, such as *.php
  • Verb: An array of allowed verbs, such as get and post.
  • SiteName: The name of the Site to register the module for. If empty, the resource will register the module with all of IIS.
  • ModuleType: The type of the module. Currently, only FastCgiModule is supported.
  • Ensure: Ensures that the module is Present or Absent.

SslSettings

  • Name: The Name of website in which to modify the SSL Settings
  • Bindings: The SSL bindings to implement.
  • Ensure: Ensures if the bindings are Present or Absent.

WebApplication

  • Website: Name of website with which the web application is associated.
  • Name: The desired name of the web application.
  • WebAppPool: Web application’s application pool.
  • PhysicalPath: The path to the files that compose the web application.
  • Ensure: Ensures that the web application is Present or Absent.
  • PreloadEnabled: When set to $true this will allow WebSite to automatically start without a request
  • ServiceAutoStartEnabled: When set to $true this will enable Autostart on a Website
  • ServiceAutoStartProvider: Adds a AutostartProvider
  • ApplicationType: Adds a AutostartProvider ApplicationType
  • AuthenticationInfo: Web Application's authentication information in the form of an array of embedded instances of the DSC_WebApplicationAuthenticationInformation CIM class. DSC_WebApplicationAuthenticationInformation take the following properties:
    • Anonymous: The acceptable values for this property are: $true, $false
    • Basic: The acceptable values for this property are: $true, $false
    • Digest: The acceptable values for this property are: $true, $false
    • Windows: The acceptable values for this property are: $true, $false
  • SslFlags: SslFlags for the application: The acceptable values for this property are: '', Ssl, SslNegotiateCert, SslRequireCert, Ssl128
  • EnabledProtocols: EnabledProtocols for the application. The acceptable values for this property are: http, https, net.tcp, net.msmq, net.pipe

WebAppPool

  • Name : Indicates the application pool name. The value must contain between 1 and 64 characters.
  • Ensure : Indicates if the application pool exists. Set this property to Absent to ensure that the application pool does not exist. Setting it to Present (the default value) ensures that the application pool exists.
  • State : Indicates the state of the application pool. The values that are allowed for this property are: Started, Stopped.
  • autoStart : When set to $true, indicates to the World Wide Web Publishing Service (W3SVC) that the application pool should be automatically started when it is created or when IIS is started.
  • CLRConfigFile : Indicates the .NET configuration file for the application pool.
  • enable32BitAppOnWin64 : When set to $true, enables a 32-bit application to run on a computer that runs a 64-bit version of Windows.
  • enableConfigurationOverride : When set to $true, indicates that delegated settings in Web.config files will be processed for applications within this application pool. When set to $false, all settings in Web.config files will be ignored for this application pool.
  • managedPipelineMode : Indicates the request-processing mode that is used to process requests for managed content. The values that are allowed for this property are: Integrated, Classic.
  • managedRuntimeLoader : Indicates the managed loader to use for pre-loading the application pool.
  • managedRuntimeVersion : Indicates the CLR version to be used by the application pool. The values that are allowed for this property are: v4.0, v2.0, and "".
  • passAnonymousToken : When set to $true, the Windows Process Activation Service (WAS) creates and passes a token for the built-in IUSR anonymous user account to the Anonymous authentication module. The Anonymous authentication module uses the token to impersonate the built-in account. When this property is set to $false, the token will not be passed.
  • startMode : Indicates the startup type for the application pool. The values that are allowed for this property are: OnDemand, AlwaysRunning.
  • queueLength : Indicates the maximum number of requests that HTTP.sys will queue for the application pool. The value must be a valid integer between 10 and 65535.
  • cpuAction : Configures the action that IIS takes when a worker process exceeds its configured CPU limit. The values that are allowed for this property are: NoAction, KillW3wp, Throttle, and ThrottleUnderLoad.
  • cpuLimit : Configures the maximum percentage of CPU time (in 1/1000ths of one percent) that the worker processes in the application pool are allowed to consume over a period of time as indicated by the cpuResetInterval property. The value must be a valid integer between 0 and 100000.
  • cpuResetInterval : Indicates the reset period (in minutes) for CPU monitoring and throttling limits on the application pool. The value must be a string representation of a TimeSpan value. The valid range (in minutes) is 0 to 1440. Setting the value of this property to 00:00:00 disables CPU monitoring.
  • cpuSmpAffinitized : Indicates whether a particular worker process assigned to the application pool should also be assigned to a given CPU.
  • cpuSmpProcessorAffinityMask : Indicates the hexadecimal processor mask for multi-processor computers, which indicates to which CPU the worker processes in the application pool should be bound. Before this property takes effect, the cpuSmpAffinitized property must be set to $true for the application pool. The value must be a valid integer between 0 and 4294967295.
  • cpuSmpProcessorAffinityMask2 : Indicates the high-order DWORD hexadecimal processor mask for 64-bit multi-processor computers, which indicates to which CPU the worker processes in the application pool should be bound. Before this property takes effect, the cpuSmpAffinitized property must be set to $true for the application pool. The value must be a valid integer between 0 and 4294967295.
  • identityType : Indicates the account identity under which the application pool runs. The values that are allowed for this property are: ApplicationPoolIdentity, LocalService, LocalSystem, NetworkService, and SpecificUser.
  • Credential : Indicates the custom account crededentials. This property is only valid when the identityType property is set to SpecificUser.
  • idleTimeout : Indicates the amount of time (in minutes) a worker process will remain idle before it shuts down. The value must be a string representation of a TimeSpan value and must be less than the restartTimeLimit property value. The valid range (in minutes) is 0 to 43200.
  • idleTimeoutAction : Indicates the action to perform when the idle timeout duration has been reached. The values that are allowed for this property are: Terminate, Suspend.
  • loadUserProfile : Indicates whether IIS loads the user profile for the application pool identity.
  • logEventOnProcessModel : Indicates that IIS should generate an event log entry for each occurrence of the specified process model events.
  • logonType : Indicates the logon type for the process identity. The values that are allowed for this property are: LogonBatch, LogonService.
  • manualGroupMembership : Indicates whether the IIS_IUSRS group Security Identifier (SID) is added to the worker process token.
  • maxProcesses : Indicates the maximum number of worker processes that would be used for the application pool. The value must be a valid integer between 0 and 2147483647.
  • pingingEnabled : Indicates whether pinging (health monitoring) is enabled for the worker process(es) serving this application pool.
  • pingInterval : Indicates the period of time (in seconds) between health monitoring pings sent to the worker process(es) serving this application pool. The value must be a string representation of a TimeSpan value. The valid range (in seconds) is 1 to 4294967.
  • pingResponseTime : Indicates the maximum time (in seconds) that a worker process is given to respond to a health monitoring ping. The value must be a string representation of a TimeSpan value. The valid range (in seconds) is 1 to 4294967.
  • setProfileEnvironment : Indicates the environment to be set based on the user profile for the new process.
  • shutdownTimeLimit : Indicates the period of time (in seconds) a worker process is given to finish processing requests and shut down. The value must be a string representation of a TimeSpan value. The valid range (in seconds) is 1 to 4294967.
  • startupTimeLimit : Indicates the period of time (in seconds) a worker process is given to start up and initialize. The value must be a string representation of a TimeSpan value. The valid range (in seconds) is 1 to 4294967.
  • orphanActionExe : Indicates an executable to run when a worker process is orphaned.
  • orphanActionParams : Indicates parameters for the executable that is specified in the orphanActionExe property.
  • orphanWorkerProcess : Indicates whether to assign a worker process to an orphan state instead of terminating it when the application pool fails. If $true, an unresponsive worker process will be orphaned instead of terminated.
  • loadBalancerCapabilities : Indicates the response behavior of a service when it is unavailable. The values that are allowed for this property are: HttpLevel, TcpLevel. If set to HttpLevel and the application pool is stopped, HTTP.sys will return HTTP 503 error. If set to TcpLevel, HTTP.sys will reset the connection.
  • rapidFailProtection : Indicates whether rapid-fail protection is enabled. If $true, the application pool is shut down if there are a specified number of worker process crashes within a specified time period.
  • rapidFailProtectionInterval : Indicates the time interval (in minutes) during which the specified number of worker process crashes must occur before the application pool is shut down by rapid-fail protection. The value must be a string representation of a TimeSpan value. The valid range (in minutes) is 1 to 144000.
  • rapidFailProtectionMaxCrashes : Indicates the maximum number of worker process crashes permitted before the application pool is shut down by rapid-fail protection. The value must be a valid integer between 0 and 2147483647.
  • autoShutdownExe : Indicates an executable to run when the application pool is shut down by rapid-fail protection.
  • autoShutdownParams : Indicates parameters for the executable that is specified in the autoShutdownExe property.
  • disallowOverlappingRotation : Indicates whether the W3SVC service should start another worker process to replace the existing worker process while that process is shutting down. If $true, the application pool recycle will happen such that the existing worker process exits before another worker process is created.
  • disallowRotationOnConfigChange : Indicates whether the W3SVC service should rotate worker processes in the application pool when the configuration has changed. If $true, the application pool will not recycle when its configuration is changed.
  • logEventOnRecycle : Indicates that IIS should generate an event log entry for each occurrence of the specified recycling events.
  • restartMemoryLimit : Indicates the maximum amount of virtual memory (in KB) a worker process can consume before causing the application pool to recycle. The value must be a valid integer between 0 and 4294967295. A value of 0 means there is no limit.
  • restartPrivateMemoryLimit : Indicates the maximum amount of private memory (in KB) a worker process can consume before causing the application pool to recycle. The value must be a valid integer between 0 and 4294967295. A value of 0 means there is no limit.
  • restartRequestsLimit : Indicates the maximum number of requests the application pool can process before it is recycled. The value must be a valid integer between 0 and 4294967295. A value of 0 means the application pool can process an unlimited number of requests.
  • restartTimeLimit : Indicates the period of time (in minutes) after which the application pool will recycle. The value must be a string representation of a TimeSpan value. The valid range (in minutes) is 0 to 432000. A value of 00:00:00 means the application pool does not recycle on a regular interval.
  • restartSchedule : Indicates a set of specific local times, in 24 hour format, when the application pool is recycled. The value must be an array of string representations of TimeSpan values. TimeSpan values must be between 00:00:00 and 23:59:59 seconds inclusive, with a granularity of 60 seconds. Setting the value of this property to "" disables the schedule.

WebAppPoolDefaults

  • IsSingleInstance: Specifies the resource is a single instance, the value must be Yes
  • ManagedRuntimeVersion: CLR Version {v2.0|v4.0|} empty string for unmanaged.
  • ApplicationPoolIdentity: {ApplicationPoolIdentity | LocalService | LocalSystem | NetworkService}

WebConfigProperty

Ensures the value of an identified property in the web.config file.

  • WebsitePath: Path to website location (IIS or WebAdministration format).
  • Filter: Filter used to locate property to update.
  • PropertyName: Name of the property to update.
  • Value: Value of the property to update.
  • Ensure: Indicates if the property and value should be present or absent. Defaults to 'Present'. { Present | Absent }

WebConfigPropertyCollection

Ensures the value of an identified property collection item's property in the web.config file. Supports all web.config elements that contain collections of child items.

  • WebsitePath: Path to website location (IIS or WebAdministration format).
  • Filter: Filter used to locate property collection to update.
  • CollectionName: Name of the property collection to update.
  • ItemName: Name of the property collection item to update.
  • ItemKeyName: Name of the key of the property collection item to update.
  • ItemKeyValue: Value of the key of the property collection item to update.
  • ItemPropertyName: Name of the property of the property collection item to update.
  • ItemPropertyValue: Value of the property of the property collection item to update.
  • Ensure: Indicates if the property and value should be present or absent. Defaults to 'Present'. { Present | Absent }

WebSite

  • Name : The desired name of the website.
  • SiteId : Optional. The desired IIS site Id for the website.
  • PhysicalPath: The path to the files that compose the website.
  • State: The state of the website: { Started | Stopped }
  • BindingInfo: Website's binding information in the form of an array of embedded instances of the DSC_WebBindingInformation CIM class that implements the following properties:
    • Protocol: The protocol of the binding. This property is required. The acceptable values for this property are: http, https, msmq.formatname, net.msmq, net.pipe, net.tcp.
    • BindingInformation: The binding information in the form a colon-delimited string that includes the IP address, port, and host name of the binding. This property is ignored for http and https bindings if at least one of the following properties is specified: IPAddress, Port, HostName.
    • IPAddress: The IP address of the binding. This property is only applicable for http and https bindings. The default value is *.
    • Port: The port of the binding. The value must be a positive integer between 1 and 65535. This property is only applicable for http (the default value is 80) and https (the default value is 443) bindings.
    • HostName: The host name of the binding. This property is only applicable for http and https bindings.
    • CertificateThumbprint: The thumbprint of the certificate. This property is only applicable for https bindings.
    • CertificateSubject: The subject of the certificate if the thumbprint isn't known. This property is only applicable for https bindings.
    • CertificateStoreName: The name of the certificate store where the certificate is located. This property is only applicable for https bindings. The acceptable values for this property are: My, WebHosting. The default value is My.
    • SslFlags: The type of binding used for Secure Sockets Layer (SSL) certificates. This property is supported in IIS 8.0 or later, and is only applicable for https bindings. The acceptable values for this property are:
      • 0: The default value. The secure connection be made using an IP/Port combination. Only one certificate can be bound to a combination of IP address and the port.
      • 1: The secure connection be made using the port number and the host name obtained by using Server Name Indication (SNI). It allows multiple secure websites with different certificates to use the same IP address.
      • 2: The secure connection be made using the Centralized Certificate Store without requiring a Server Name Indication.
      • 3: The secure connection be made using the Centralized Certificate Store while requiring Server Name Indication.
  • ApplicationPool: The name of the website’s application pool.
  • DefaultPage: One or more names of files that will be set as Default Documents for this website.
  • EnabledProtocols: The protocols that are enabled for the website.
  • ServerAutoStart: When set to $true this will enable Autostart on a Website
  • Ensure: Ensures that the website is Present or Absent. Defaults to Present.
  • PreloadEnabled: When set to $true this will allow WebSite to automatically start without a request
  • ServiceAutoStartEnabled: When set to $true this will enable application Autostart (application initalization without an initial request) on a Website
  • ServiceAutoStartProvider: Adds a AutostartProvider
  • ApplicationType: Adds a AutostartProvider ApplicationType
  • AuthenticationInfo: Website's authentication information in the form of an embedded instance of the DSC_WebAuthenticationInformation CIM class. DSC_WebAuthenticationInformation takes the following properties:
    • Anonymous: The acceptable values for this property are: $true, $false
    • Basic: The acceptable values for this property are: $true, $false
    • Digest: The acceptable values for this property are: $true, $false
    • Windows: The acceptable values for this property are: $true, $false
  • LogPath: The directory to be used for logfiles.
  • LogFlags: The W3C logging fields: The values that are allowed for this property are: Date,Time,ClientIP,UserName,SiteName,ComputerName,ServerIP,Method,UriStem,UriQuery,HttpStatus,Win32Status,BytesSent,BytesRecv,TimeTaken,ServerPort,UserAgent,Cookie,Referer,ProtocolVersion,Host,HttpSubStatus
  • LogPeriod: How often the log file should rollover. The values that are allowed for this property are: Hourly,Daily,Weekly,Monthly,MaxSize
  • LogTargetW3C: Log Target of the W3C Logfiles. The acceptable values for this property are: File,ETW,File,ETW
  • LogTruncateSize: How large the file should be before it is truncated. If this is set then LogPeriod will be ignored if passed in and set to MaxSize. The value must be a valid integer between 1048576 (1MB) and 4294967295 (4GB).
  • LoglocalTimeRollover: Use the localtime for file naming and rollover. The acceptable values for this property are: $true, $false
  • LogFormat: Format of the Logfiles. NoteOnly W3C supports LogFlags. The acceptable values for this property are: IIS,W3C,NCSA
  • LogCustomFields: Custom logging field information the form of an array of embedded instances of the DSC_LogCustomFieldInformation CIM class that implements the following properties:
    • LogFieldName: Field name to identify the custom field within the log file. Please note that the field name cannot contain spaces.
    • SourceType: The acceptable values for this property are: RequestHeader, ResponseHeader, or ServerVariable (note that enhanced logging cannot log a server variable with a name that contains lower-case characters - to include a server variable in the event log just make sure that its name consists of all upper-case characters).
    • SourceName: Name of the HTTP header or server variable (depending on the Source Type you selected) that contains a value that you want to log.

WebSiteDefaults

  • Key: Required Key value, always Machine
  • LogFormat: Format of the Logfiles. NoteOnly W3C supports LogFlags. The acceptable values for this property are: IIS,W3C,NCSA,Custom.
  • LogDirectory: Directory for IIS logs.
  • TraceLogDirectory: Directory for FREB (Failed Request Tracing) logs.
  • DefaultApplicationPool: Name of the default application pool used by websites.
  • AllowSubDirConfig: Should IIS look for config files in subdirectories, either true or false

WebVirtualDirectory

  • Website: Name of website with which virtual directory is associated
  • WebApplication: The name of the containing web application or an empty string for the containing website
  • PhysicalPath: The path to the files that compose the virtual directory
  • Name: The name of the virtual directory
  • Ensure: Ensures if the virtual directory is Present or Absent.

WebConfigProperty

Ensures the value of an identified property in the web.config file.

  • WebsitePath: Path to website location (IIS or WebAdministration format).
  • Filter: Filter used to locate property to update.
  • PropertyName: Name of the property to update.
  • Value: Value of the property to update.
  • Ensure: Indicates if the property and value should be present or absent. Defaults to 'Present'. { Present | Absent }

WebConfigPropertyCollection

Ensures the value of an identified property collection item's property in the web.config file. Builds upon the WebConfigKeyValue resource to support all web.config elements that contain collections of child items.

  • WebsitePath: Path to website location (IIS or WebAdministration format).
  • Filter: Filter used to locate property collection to update.
  • CollectionName: Name of the property collection to update.
  • ItemName: Name of the property collection item to update.
  • ItemKeyName: Name of the key of the property collection item to update.
  • ItemKeyValue: Value of the key of the property collection item to update.
  • ItemPropertyName: Name of the property of the property collection item to update.
  • ItemPropertyValue: Value of the property of the property collection item to update.
  • Ensure: Indicates if the property and value should be present or absent. Defaults to 'Present'. { Present | Absent }

SslSettings

  • Name: The Name of website in which to modify the SSL Settings
  • Bindings: The SSL bindings to implement.
  • Ensure: Ensures if the bindings are Present or Absent.

IisFeatureDelegation

This resource manages the IIS configuration section locking (overrideMode) to control what configuration can be set in web.config.

  • Filter: Specifies the IIS configuration section to lock or unlock in this format: /system.webserver/security/authentication/anonymousAuthentication
  • OverrideMode: Mode of that section { Allow | Deny }
  • Path: Specifies the configuration path. This can be either an IIS configuration path in the format computer machine/webroot/apphost, or the IIS module path in this format IIS:\sites\Default Web Site. WARNING: both path types can be used to manage the same feature delegation, however, there is no way to control if two resources in the configuration set the same feature delegation.

IisMimeTypeMapping

  • Extension: The file extension to map such as .html or .xml
  • MimeType: The MIME type to map that extension to such as text/html
  • Ensure: Ensures that the MIME type mapping is Present or Absent.

WebAppPoolDefaults

  • IsSingleInstance: Specifies the resource is a single instance, the value must be Yes
  • ManagedRuntimeVersion: CLR Version {v2.0|v4.0|} empty string for unmanaged.
  • ApplicationPoolIdentity: {ApplicationPoolIdentity | LocalService | LocalSystem | NetworkService}

WebSiteDefaults

  • Key: Required Key value, always Machine
  • LogFormat: Format of the Logfiles. NoteOnly W3C supports LogFlags. The acceptable values for this property are: IIS,W3C,NCSA,Custom.
  • LogDirectory: Directory for IIS logs.
  • TraceLogDirectory: Directory for FREB (Failed Request Tracing) logs.
  • DefaultApplicationPool: Name of the default application pool used by websites.
  • AllowSubDirConfig: Should IIS look for config files in subdirectories, either true or false

Examples

Registering PHP

When configuring an IIS Application that uses PHP, you first need to register the PHP CGI module with IIS. The following xPhp configuration downloads and installs the prerequisites for PHP, downloads PHP, registers the PHP CGI module with IIS and sets the system environment variable that PHP needs to run.

Note: This example is intended to be used as a composite resource, so it does not use Configuration Data. Please see the Composite Configuration Blog on how to use this configuration in another configuration.

# Composite configuration to install the IIS pre-requisites for PHP
Configuration IisPreReqs_php
{
    param
    (
        [Parameter(Mandatory = $true)]
        [Validateset("Present","Absent")]
        [String]
        $Ensure
    )
    foreach ($Feature in @("Web-Server","Web-Mgmt-Tools","web-Default-Doc", `
            "Web-Dir-Browsing","Web-Http-Errors","Web-Static-Content",`
            "Web-Http-Logging","web-Stat-Compression","web-Filtering",`
            "web-CGI","web-ISAPI-Ext","web-ISAPI-Filter"))
    {
        WindowsFeature "$Feature$Number"
        {
            Ensure = $Ensure
            Name = $Feature
        }
    }
}

# Composite configuration to install PHP on IIS
configuration xPhp
{
    param
    (
        [Parameter(Mandatory = $true)]
        [switch] $installMySqlExt,
        [Parameter(Mandatory = $true)]
        [string] $PackageFolder,
        [Parameter(Mandatory = $true)]
        [string] $DownloadUri,
        [Parameter(Mandatory = $true)]
        [string] $Vc2012RedistDownloadUri,
        [Parameter(Mandatory = $true)]
        [String] $DestinationPath,
        [Parameter(Mandatory = $true)]
        [string] $ConfigurationPath
    )
        # Make sure the IIS Prerequisites for PHP are present
        IisPreReqs_php Iis
        {
            Ensure = "Present"
            # Removed because this dependency does not work in
            # Windows Server 2012 R2 and below
            # This should work in WMF v5 and above
            # DependsOn = "[File]PackagesFolder"
        }

        # Download and install Visual C Redist2012 from chocolatey.org
        Package vcRedist
        {
            Path = $Vc2012RedistDownloadUri
            ProductId = "{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}"
            Name = "Microsoft Visual C++ 2012 x64 Minimum Runtime - 11.0.61030"
            Arguments = "/install /passive /norestart"
        }

        $phpZip = Join-Path $PackageFolder "php.zip"

        # Make sure the PHP archine is in the package folder
        xRemoteFile phpArchive
        {
            uri = $DownloadURI
            DestinationPath = $phpZip
        }

        # Make sure the content of the PHP archine are in the PHP path
        Archive php
        {
            Path = $phpZip
            Destination  = $DestinationPath
        }

        if ($installMySqlExt )
        {
            # Make sure the MySql extention for PHP is in the main PHP path
            File phpMySqlExt
            {
                SourcePath = "$($DestinationPath)\ext\php_mysql.dll"
                DestinationPath = "$($DestinationPath)\php_mysql.dll"
                Ensure = "Present"
                DependsOn = @("[Archive]PHP")
                MatchSource = $true
            }
        }

        # Make sure the php.ini is in the Php folder
        File PhpIni
        {
            SourcePath = $ConfigurationPath
            DestinationPath = "$($DestinationPath)\php.ini"
            DependsOn = @("[Archive]PHP")
            MatchSource = $true
        }

        # Make sure the php cgi module is registered with IIS
        IisModule phpHandler
        {
            Name = "phpFastCgi"
            Path = "$($DestinationPath)\php-cgi.exe"
            RequestPath = "*.php"
            Verb = "*"
            Ensure = "Present"
            DependsOn = @("[Package]vcRedist","[File]PhpIni")
            # Removed because this dependency does not work in
            # Windows Server 2012 R2 and below
            # This should work in WMF v5 and above
            # "[IisPreReqs_php]Iis"
        }

        # Make sure the php binary folder is in the path
        Environment PathPhp
        {
            Name = "Path"
            Value = ";$($DestinationPath)"
            Ensure = "Present"
            Path = $true
            DependsOn = "[Archive]PHP"
        }
}

xPhp -PackageFolder "C:\packages" `
    -DownloadUri  -DownloadUri "http://windows.php.net/downloads/releases/php-5.5.13-Win32-VC11-x64.zip" `
    -Vc2012RedistDownloadUri "http://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe" `
    -DestinationPath "C:\php" `
    -ConfigurationPath "C:\MyPhp.ini" `
    -installMySqlExt $false

webadministrationdsc's People

Contributors

bhlokana-msft avatar brianfarnhill avatar ctrlc-root avatar dan1el42 avatar dscbot avatar gigi81 avatar hansmelin avatar joeyaiello avatar johlju avatar jwainwright avatar karolkaczmarek avatar kwirkykat avatar mbreakey3 avatar mcbobke avatar mgreenegit avatar midacts avatar omiossec avatar outek avatar pwiens avatar randomnoun7 avatar regedit32 avatar remcoeissing avatar rosberglinhares avatar snikalaichyk avatar tomlarse avatar tommysor avatar travisez13 avatar vors avatar wh33ly avatar x-guardian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webadministrationdsc's Issues

Create a function to generate the BindingInfo

I'm trying to create a function that returns the bindinginfo for a website. This is intended to reduce the complexity of my dsc resource file that will have 20/30 websites with similar bindinginfo based on the node name. Below is what I have at the moment but I'm getting an error and I don't know exactly how to sort it out. Any help on this would be really appreciated.

This is what I have at the moment:

`
configuration DscTest
{
Import-DscResource -ModuleName xWebAdministration;

Node localhost
{
    xWebsite TestWebSite
    {
        Ensure = "Present"
        Name = "TestWebSite"
        PhysicalPath = "C:\inetpub\test"
        BindingInfo = (Get-TestBindingInformation $Node)
    }
}

}

function Get-TestBindingInformation
{
[OutputType([Microsoft.Management.Infrastructure.CimInstance[]])]
param(
[System.Collections.Hashtable] $node
)

return @(
    New-CimInstance -ClassName MSFT_xWebBindingInformation -Namespace root/microsoft/Windows/DesiredStateConfiguration -Property @{
        Port                  = 80
        Protocol              = "HTTP"
        HostName              = "test1"
    } -ClientOnly

    New-CimInstance -ClassName MSFT_xWebBindingInformation -Namespace root/microsoft/Windows/DesiredStateConfiguration -Property @{
        Port                  = 80
        Protocol              = "HTTP"
        HostName              = "test2"
    } -ClientOnly
)

}

DscTest
`

And this is the error I get:

Write-NodeMOFFile : Invalid MOF definition for node 'localhost': Exception calling "ValidateInstanceText" with "1" argument(s):
"Convert property 'BindingInfo' value from type 'STRING[]' to type 'INSTANCE[]' failed
At line:22, char:2
Buffer:
onName = "DscTest";
};^
insta
"
At C:\windows\system32\windowspowershell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psm1:2193 char:21

  • ... Write-NodeMOFFile $Name $mofNode $Script:NodeInstanceAlia ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    
    • CategoryInfo : InvalidOperation: (:) [Write-Error], InvalidOperationException
    • FullyQualifiedErrorId : InvalidMOFDefinition,Write-NodeMOFFile

xWebsite will set bindings every time

So in xWebsite if you specify the bindings as follows:

BindingInfo     = MSFT_xWebBindingInformation
{
    IP                   = '*'
    Protocol             = 'HTTP'
    Port                 = 80
    Thumbprint           = ''
    CertificateStoreName = 'My'
}

DSC will continously try to "fix" your web server as it'll never be able to match the CertificateStoreName. I have a lead on where the bug is and will be submitting a PR as soon as I've had time to write the tests.

Binding are always updated (xWebsite) on every DSC execution

Found an interesting issue, given this example:

     xWebsite Website
        {
            Name = 'Website'
            PhysicalPath = 'D:\Webroot\website'
            ApplicationPool  = 'AppPool'
            BindingInfo = @(
            MSFT_xWebBindingInformation
            {
                Protocol              = 'HTTP' 
                Port                  = '80'
                IPAddress             = '*'
                HostName              = 'sometest.test.com.au'

            };
            MSFT_xWebBindingInformation
            {
                Protocol              = 'HTTP' 
                Port                  = '80'
                IPAddress             = '*'
                HostName              = 'sometest.test.co.nz'

            };
            MSFT_xWebBindingInformation
            {
                Protocol              = 'HTTPS' 
                Port                  = '443' 
                CertificateThumbprint = '5438DC0CB31B1C91B8945C7D91B3338F9C08BEFA'
                CertificateStoreName  = 'My'
                IPAddress             = '*'
            })
           }

You would expect that it test-target resource would correctly find the above bindings and not reset anything however it appears not to be the case that is it always run and set:

VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer D2251-DSCTARGET with user sid S-1-5-21-1700922704-892494943-355810188-39006.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Set      ]
...<SNIP>....
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Resource ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Test     ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] Importing the module MSFT_xWebsite in force mode.
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] The Ensure state for website Website does not match the desired state.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Test     ]  [[xWebsite]Website]  in 0.2030 seconds.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Set      ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] Importing the module MSFT_xWebsite in force mode.
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] Performing the operation "Set Item" on target "Item: ConfirmPreference Value: High".
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]  [[xWebsite]Website]  in 1.5700 seconds.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Resource ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]    in  3.6370 seconds.
VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 3.692 seconds


Mode                LastWriteTime         Length Name                                                                                                                                                                                                                          
----                -------------         ------ ----                                                                                                                                                                                                                          
-a----       23/11/2015   3:40 PM           6462 Localhost.mof                                                                                                                                                                                                                 
VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer D2251-DSCTARGET with user sid S-1-5-21-1700922704-892494943-355810188-39006.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Set      ]
...<SNIP>....
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Resource ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Test     ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] Importing the module MSFT_xWebsite in force mode.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Test     ]  [[xWebsite]Website]  in 0.2970 seconds.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ Start  Set      ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]:                            [[xWebsite]Website] Importing the module MSFT_xWebsite in force mode.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]  [[xWebsite]Website]  in 0.3280 seconds.
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Resource ]  [[xWebsite]Website]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]
VERBOSE: [D2251-DSCTARGET]: LCM:  [ End    Set      ]    in  7.9840 seconds.

this also enters this in the event viewer:

SSL Certificate Settings deleted for endpoint : 0.0.0.0:443 .
followed by
SSL Certificate Settings created by an admin process for endpoint : 0.0.0.0:443 .

Now this is not good as if I have a node running in PULL mode that means every-time the LCM does a consistency check it is causing IIS to recompile .NET and as a result a slow site

I have been attempting to figure this out for a couple of hours with no luck

Out of interest this happens on both xWebadministration(dev branch), the Powershell.Org version and a custom cBindings resource I have.

Is anyone able to confirm this is an issue? if so it appears to be fairly critical

thanks

edit: BTW this is running on Window 2012R2 with WMF5 Production Preview installed; I will/want to test WMF4 as well tomorrow

MSFT_xWebBindingInformation certificate store values are incorrect

MSFT_xWebsite.schema.mof contains "Person" and "WebHosting" certificate store names.

Personal is not actually the certificate store name and needs to be changed to "My". Here is my machine cert store list:

gci Cert:\LocalMachine\ | select Name

Name
----
TrustedPublisher
ClientAuthIssuer
Remote Desktop
Root
TrustedDevices
WebHosting <-- This shows up as "Web Hosting" in MMC
CA
Windows Live ID Token Issuer
REQUEST
AuthRoot
FlightRoot
TrustedPeople
My <-- This shows up as "Personal" in MMC
SmartCardRoot
Trust
Disallowed
SMS

xWebsite incorrectly validates that port is unique across site bindings

This is a regression introduced in 1441fde.

The function Test-BindingInfo asserts for "standard" bindings (i.e. http and https) that the port number is unique across bindings; this is incorrect. It is perfectly valid (and what we are trying to do at the moment) to have multiple bindings on the same port that differ by host header.

What it should actually do is assert that the combination of port and hostname is unique.

Proposing additional DscResources for the server level

For a few years now I'm setting up my web server using PowerShell. When looking at the existing resources, a few things are missing (in addition to the new stuff in cWebAdministration) I propose the following new resources:

  • IisFeatureDelegation
  • IisMimeTypeMapping
  • WebSiteDefaults
  • AppPoolDefaults

these are all working against the server level rather than a site or AppPool.

I have already done some work on these and would just like to check whether anybody else is working in this area?

Multiple SSL Bindings

Multiple SSL bindings applied to the same site with different certificates; only the certificate specified on the LAST applied SSL binding is actually applied - to all of the bindings.

Inconsistent spacing in xWebsite

In xWebsite the spacing, bracing, and returns are super inconsistant. Would anyone mind terribly if I went and corrected it so my style OCD can calm down? 😆

xWebsite: Resource should check if there's conflicting website running

Per @KarolKaczmarek,

STEPS:

  • run following config (it creates IIS which means there will be Default Web Site started)
configuration webconfig
{

Import-DscResource -Module xWebAdministration

Node localhost {

# Install the IIS role
WindowsFeature IIS
{
Ensure = "Present"
Name = "Web-Server"
}

# Copy the website content
File WebContent
{
Ensure = "Present"
SourcePath = "C:\test\testwebsite"
DestinationPath = "C:\inetpub\FourthCoffee"
Recurse = $true
Type = "Directory"
} 

xWebsite FrontEndSite
{
Ensure = "Present"
Name = "FourthCoffee"
PhysicalPath = "c:\inetpub\FourthCoffee"
State = "Started"
#BindingInfo = MSFT_xWebBindingInformation {Port="80"}
DependsOn = "[File]WebContent"
}

}

}
webconfig
  • Call: Start-DscOperation -path .\webconfig -wait -verbose
    (it will fail to start the new website because default web site is already running and there's conflict)

EXPECTED RESULT:
we should get error that we cannot start a new website because of bindings conflict where there is already a site running on the same IP address and port.
Error could also suggest to stop those conflicting websites using Stop-Website cmdlet.

ACTUAL RESULT:
"InvalidOperation" error which doesn't help much:

PowerShell DSC resource MSFT_xWebsite failed to execute Set-TargetResource functionality with error message:
+ CategoryInfo : InvalidOperation: (:) [], CimException
+ FullyQualifiedErrorId : ProviderOperationExecutionFailure
+ PSComputerName : localhost

The SendConfigurationApply function did not succeed.
+ CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 1
+ PSComputerName : localhost

Per @jianyunt,

The issue was partially fixed:

  1. if a user privides BindingInfo (BindingInfo = MSFT_xWebBindingInformation {Port="80"}) in the configuration, and then try to create a new website Let's say FourthCoffee4, a proper error messages shows - Fixed
  2. if a user does not provide Bindinginfo in the configuration, the issue repro's, meaning no proper error message shows. Only the following. - Not fixed.

PowerShell provider MSFT_xWebsite failed to execute Set-TargetResource functionality with error message:

+ CategoryInfo : InvalidOperation: (:) [], CimException
+ FullyQualifiedErrorId : ProviderOperationExecutionFailure
+ PSComputerName : localhost
VERBOSE: [TestMachineName]: LCM: [ End Set ]
The SendConfigurationApply function did not succeed.
+ CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 1
+ PSComputerName : localhost

xWebApplication test failing and attempting to redeploy

I've got a webapplication that's deployed under a virtual directory

VirtualDir
----WebApplication

It's deploying fine with:
xWebApplication "$app Application"
{
Ensure = "Present"
Name = "WebApi"
PhysicalPath = $node.instances.$instance.confphysicalPath + "$app" +"\WebApi"
Website = "$Instance/$app"
WebAppPool = "$instance" + "_" + "$app"
}

But every run of the config it'll try and redeploy the application giving:

VERBOSE: [Server]: LCM: [ Start Resource ] [[xWebVirtualDirectory] VirtualDir]
VERBOSE: [Server]: LCM: [ Start Test ] [[xWebVirtualDirectory] VirtualDir]
VERBOSE: [Server]: [[xWebVirtualDirectory] VirtualDir] Checking whether WebAdministration is there in the machine or not.
VERBOSE: [Server]: [[xWebVirtualDirectory] VirtualDir] Checking the virtual directories for the website.
VERBOSE: [Server]: LCM: [ End Test ] [[xWebVirtualDirectory] VirtualDir] in 0.0630 seconds.
VERBOSE: [Server]: LCM: [ Skip Set ] [[xWebVirtualDirectory] VirtualDir]
VERBOSE: [Server]: LCM: [ End Resource ] [[xWebVirtualDirectory] VirtualDir]
VERBOSE: [Server]: LCM: [ Start Resource ] [[xWebApplication] Application]
VERBOSE: [Server]: LCM: [ Start Test ] [[xWebApplication] Application]
VERBOSE: [Server]: [[xWebApplication] Application] Checking whether WebAdministration is there in the machine or not.
VERBOSE: [Server]: LCM: [ End Test ] [[xWebApplication] Application] in 0.0470 seconds.
VERBOSE: [Server]: LCM: [ Start Set ] [[xWebApplication] Application]
VERBOSE: [Server]: [[xWebApplication] Application] Checking whether WebAdministration is there in the machine or not.
Destination element already exists, please use "force" parameter to override.
+ CategoryInfo : InvalidArgument: (:) [], CimException
+ FullyQualifiedErrorId : Destination element already exists, please use "force" parameter to override.,Microsoft.IIs.PowerShell.Provider.NewWebApplicationCommand
+ PSComputerName : Server

Running the test manually on the target server, passing $instance/$app it returns the one application, as expected.
Applications that are under the root of the website are passing the test fine and skipping the set as they should.

Question about testing and mocking

I just started writing tests for my new resources which make server level changes. The first test has the following steps:

  • Backup IIS Config
  • Using the dsc resource to change a value
  • Check that the value has actually been changed using IIS cmdlets.
  • Restore the saved IIS config

Questions:
This actually makes changes to the ApplicationHost.config file, should I use some mocking instead, in which case I don't really test whether my resource works. Many tests I've seen, just check for existence of some resource or successful execution but don't actually perform the change and verify it.

This is my first time using Pester, a variable I set in the test is empty after I ran Start-DscConfiguration... so I can't use it for any assertions. Is that normal?

The test is at:
https://github.com/hahndorf/xWebAdministration/blob/ServerLevelResources/Tests/MSFT_xIISServerLevel.Tests.ps1

As a workaround I store my data in an environment variable.

xWebAdministration tests fail on local machine cause module isn't deployed

xWebAdministration tests fail cause they expect the module to be deployed on a machine.
Tests are passing on appveyor builds because in appveyor.yml we modify PSModulePath so that development version is discovered:

$tempModulePath = (Resolve-Path (join-path $PWD '..')).ProviderPath 
$env:PSModulePath = "$env:PSModulePath;$tempModulePath 

We should be deploying the module during the test execution instead (similarily to: https://github.com/PowerShell/xTimeZone/pull/12/files ) so that we can run tests successfully on local machine as well.

xWebAppPool's Tests Need to be Updated

They don't currently test set-targetresource, should also look into how much coverage we get with the integration tests.

I'm currently working on this and am just filing an issue to reference when I submit the PR.

xWebVirtualDirectory setting PhysicalPath to UNC

Setting a PhysicalPath to UNC for a VirtualDirectory fails.

Perhaps we need to change

New-WebVirtualDirectory -Site $Website -Application $WebApplication -Name $Name -PhysicalPath $PhysicalPath

for

$virtualDirectory = Get-WebVirtualDirectoryInternal -Site $Website -Name $Name -Application $WebApplication

$virtualDirectoryPath = "IIS:\Sites$Website$Name"

New-Item $virtualDirectoryPath -Type VirtualDirectory -PhysicalPath $PhysicalPath

Require Server Name Indication

Is there anyway to specify that I want to require Server Name Inidication on my SSL bindings?

Basically the setup is:
IP Address: All Unassigned
Port 443
Type: HTTPS
Hostname: somehostname
SNI: Checked
SSL Certificate: somehostname ssl thumbprint

Is there way to do this through DSC?

PSSA Errors

Script Analyzer error in version 1.9.0.0

Parse error in file C:\Users\psgadmin\Documents\WindowsPowerShell\Modules\xWebAdministration\1.9.0.0\Examples\Sample_xWebsite_WithSSLFlags.ps1: Missing '=' operator after key in property assignment at line 83 column 14.Parse error in file C:\Users\psgadmin\Documents\WindowsPowerShell\Modules\xWebAdministration\1.9.0.0\Examples\Sample_xWebsite_WithSSLFlags.ps1: Missing closing '}' in statement block or type definition at line 2 column 1.Parse error in file C:\Users\psgadmin\Documents\WindowsPowerShell\Modules\xWebAdministration\1.9.0.0\Examples\Sample_xWebsite_WithSSLFlags.ps1: An attribute name for resource 'xWebsite' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{ Protocol = 'https' Port = '443' CertificateStoreName = 'MY' CertificateThumbprint = 'BB84DE3EC423DDDE90C08AB3C5A828692089493C' HostName = $Website IPAddress = '*' SSLFlags = '1' }' with a simple string at line 75 column 13. 

Add a resource that verifies a website is running

Scenario

You want to verify a Web Site you deployed is basically functional

Concept

Add a resource that only implements test, set always throws. It pings a web page, if the web page passes, it skips set, if the web page fails, it cause set to be called. Therefore your configuration will fail if your page isn't working.

xWebsite SSL Binding set certificate fails with "Value does not fall within the expected range."

Using xWebsite to configure an SSL binding and set the certificate on a domain-joined web server running Windows 2012 R2 Standard.

When resource gets to the portion where it has to set the certificate it errors out with "Value does not fall within the expected range."

If I manually change the $Properties.certificateHash in the set-target to the certificate thumbprint or store it manually in a variable, it works ($certHash = "hash" works, but $certHash = $Properties.certificateHash doesn't even with $certHash type forcibly set to string via [string]$certHash.)

Works :
$certHash = "hash"
$Binding.AddSslCertificate($certHash, $Properties.certificateStoreName)

Works:
$Binding.AddSslCertificate("hash", $Properties.certificateStoreName)

Doesn't Work :
[string]$certHash = $Properties.certificateHash
$Binding.AddSslCertificate($certHash, $Properties.certificateStoreName)

Doesn't Work (Original):
$Binding.AddSslCertificate($Properties.certificateHash, $Properties.certificateStoreName)

It looks like $Properties.certificateHash itself is set properly, value wise.(verified by doing a write-verbose $Properties.certificateHash just before the call).

xWebAppPool should be able to specify Managed Pipeline Mode

I'd like to see a ManagedPipelineMode property on the xWebAppPool resource with values 'Classic' and 'Integrated'.

This could be done by checking the value of the 'managedPipelineMode' property of IIS:\AppPools$Name and setting it accordingly.

MSFT_xWebAppPool Does not allow Managed Service Accounts

I don't seem to be able to use MSFT_xWebAppPool to set an AppPool to Run as a gMSA.

I had hoped it would work using a credential with a blank password like so:
Note that You have to set PSDscAllowPlainTextPassword = $true in the configuration data for this to work.

$pw = (new-object System.Security.SecureString)
$un = "domain\account$"
$cred = New-Object System.Management.Automation.PSCredential ( $un, $pw)

xWebAppPool testpool
{
    Name = "testPool"
    Ensure = "Present"
    enable32BitAppOnWin64 = $true
    autoStart = $true
    managedRuntimeVersion = "v4.0"
    managedPipelineMode = "Integrated"
    startMode = "AlwaysRunning"
    LoadUserProfile = $false
    IdentityType = "SpecificUser"
    Credential = $cred
    restartSchedule = @()
}

Note that You have to set PSDscAllowPlainTextPassword = $true in the configuration data for this to work (well, not work, but you get the Idea... )

This creates the Schema files correctly (I think!)

However I receive the following error when I send the configuration:

The password supplied to the Desired State Configuration resource MSFT_xWebAppPool is not valid. The password cannot be null or empty.
    + CategoryInfo          : InvalidResult: (:) [], CimException
    + FullyQualifiedErrorId : InvalidPassword
    + PSComputerName        : localhost

The SendConfigurationApply function did not succeed.
    + CategoryInfo          : ObjectNotFound: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MI RESULT 6
    + PSComputerName        : localhost

Is there any hope for this? Not allowing gMSA's is a deal breaker for my situation, so I would be thankful for any workaround...

I'm pasting a complete test config below to make checking this easier.

Configuration testIIS
{
    # Import the module that defines custom resources
    Import-DscResource -Module xWebAdministration, PSDesiredStateConfiguration

    # Dynamically find the applicable nodes from configuration data
    Node $AllNodes.where{$_.Roles -contains 'Web'}.NodeName
    {
        # Install the IIS role
        WindowsFeature IIS
        {
            Ensure          = 'Present'
            Name            = 'Web-Server'
        }

        # Install the ASP .NET 4.5 role
        WindowsFeature AspNet45
        {
            Ensure          = 'Present'
            Name            = 'Web-Asp-Net45'
        }

        $pw = (new-object System.Security.SecureString)
        $un = "domain\account$"
        $cred = New-Object System.Management.Automation.PSCredential ( $un, $pw)

        xWebAppPool testpool
        {
            Name = "testPool"
            Ensure = "Present"
            enable32BitAppOnWin64 = $true
            autoStart = $true
            managedRuntimeVersion = "v4.0"
            managedPipelineMode = "Integrated"
            startMode = "AlwaysRunning"
            LoadUserProfile = $false
            IdentityType = "SpecificUser"
            Credential = $cred
            restartSchedule = @()
        }

        # Create a new website
        xWebsite testSite 
        {
            Ensure          = 'Present'
            Name            = "TestSite"
            State           = 'Started'
            PhysicalPath    = 'D:\Acumen\InetPub\Test-Site'
            DependsOn       = '[xWebAppPool]testpool'
        }

    }


}

$configData = @{
    AllNodes = @(
                    @{
                        NodeName = "*";
                        PSDscAllowPlainTextPassword = $true
                    }
                    @{
                        NodeName = "localhost";
                        Roles=@("web")

                    }


        )
    }

testIIS -ConfigurationData $configData 

xWebAppPool Get-TargetResource fails

Below are my settings, and whenever I run Get-DscConfiguration I get the following error.

        xWebAppPool InstallWebAppPool {
            Ensure = 'Present'
            Name = 'MyAppPool"
            State = 'Started'
            autoStart = 'true'
            managedRuntimeVersion = 'v4.0'
            managedPipelineMode = 'Integrated'
        }

Get-DscConfiguration : GetConfiguration did not succeed.
At line:1 char:1

  • Get-DscConfiguration
  • - CategoryInfo          : NotSpecified: (MSFT_DSCLocalConfigurationManager:root/Microsoft/...gurationManager) [Get-DscConfiguration], CimException
    - FullyQualifiedErrorId : MI RESULT 1,Get-DscConfiguration
    

xWebConfigKeyValue does not handle existing appsettings correctly

Hi,
I am trying to use xWebConfigKeyValue to modify an existing set of appsettings.
The service is installed through a package and already has some existing appsettings in place.
But trying to alter these values results in the same value in all value attributes.

Looks like the Modify-Item function filters on value only. Resulting in changes on every setting with an empty value.
$filter= "$defaultFilter/add[@$propertyName='$oldValue']"

But missing the $key value in that function to fix it. And I'm not sure if adding it would break something.

Appsettings that need to be changed

 <add key="WEB_SERVICE_SDK_AUTHENTICATION_USERNAME" value=""/>
 <add key="WEB_SERVICE_SDK_AUTHENTICATION_PASSWORD" value=""/>

Used DSC

        xWebConfigKeyValue setMobileSdkUserName
        {
            Ensure = "Present"
            ConfigSection = "AppSettings"
            Key = "WEB_SERVICE_SDK_AUTHENTICATION_USERNAME"
            Value = $mfaCreds.UserName
            IsAttribute = $false
            WebsitePath = "IIS:\sites\" + $siteName + "\" + $mfaMobileApp
            DependsOn = @("[xPackage]installMobileAppService")
        }

xWebConfigKeyValue use of Key values in schema

I think that it would make sense to remove 'key' attribute for 'ConfigSection' and 'WebsitePath' properties to allow for multiple invocation of xWebConfigKeyValue resource against the same site or configuration section.

Leaving just the 'Key' property as the only one with 'key' attribute set would cater for situation where a user needs to add multiple Key/Value entries within the same configuration section and/or for the same site. An example of this is adding multiple custom script handler mappings for the same site/root instance.

If a particular property is mandatory then setting a sensible/safe default value may be a better approach, which would remove the multiple 'key' attribute requirement.

Error for Stopping and Starting the Application Pool

I'm trying to create the DSC script for deployment web applications.
The process is Stop the application pool, copy new files and Start the application pool
But, when I create the .mof file, return the following error

Add-NodeKeys : The key properties combination 'AppPoolLeandroPradoDSC' is duplicated for keys 'Name' of resource 'xWebAppPool' in node 'VSALM'. Please make sure key properties are unique for each resource in a node.

In attach the dsc script.

dscerror

What is the best way for stop and start the application pool?

Issue creating site

Hi,

I'm new with DSC so apologizes if there is something I'm doing wrong here. I have written a simple configuration, it is something like this:

configuration IISConfigurationDSC
{ 
    param 
    ( 
        # Target nodes to apply the configuration 
        [string[]]$NodeName = 'localhost',
        [string[]]$secureFolder = 'E:\Web_secureNO2\' 
    ) 
    # Import the module that defines custom resources 
    Import-DscResource -Module xWebAdministration 
    Import-DscResource -ModuleName 'PSDesiredStateConfiguration'

    Node localhost
    {
        xWebAppPool secureAppPool
        {
            Name   = "secure2"
            Ensure = "Present"
            State  = "Started"
        }

        File wwwroot_secure
        {
            Type = "Directory"
            Ensure = "Present"
            DestinationPath = "$($secureFolder)wwwroot_secure"
        }

        xWebsite secureSite
        { 
            Ensure          = "Present" 
            Name            = "secure2" 
            ApplicationPool = "secure"
            State           = "Started" 
            PhysicalPath    = "$($secureFolder)wwwroot_secure"
            BindingInfo     = MSFT_xWebBindingInformation
                 {
                   Protocol              = "HTTP"
                   Port                  = 81
                 }
            DependsOn       = @("[xWebAppPool]secureAppPool","[File]wwwroot_secure")
        }
    }
}

I get this error saying "Cannot find path 'IIS:\Sites\secure2' because it does not exist.", obvious...

I took a quick look at the MSFT_xWebSite.psm1 module and I find line 404

$Website = Get-Website -Name $Name

This command returns all sites, for some reason the -Name parameter does not work. It should have a where statement to be able to filter the appropiate WebSite

$Website = Get-Website | where name -eq $Name

Is there anybody experiencing the same issue?

xWebsite should be able to specifiy Log Path

Being able to change the default path for the website would be a nice to have.

Could be done by checking the properties "IIS:\Sites$Name" -name logFile.directory and modifying accordingly.

Remove all websites except the ones I really want

So assume the desired state of my server is to have two web-sites, Site-A and Site-B, I only want these but no others. Another administrator has setup Site-C and MyPrivateWebSite

I don't know the names of these sites, but I want them gone.

I'm just starting with DSC, so I'm not sure how this can be handled if you have to specify a name for a resource.

I guess this problem applies to many other resources as well. Is there a recommended way to handle this?

PhysicalPath parameter not consistent in xWebsite

The PhysicalPath property is marked as "Mandatory" on Set-TargetResource, but "write" in the MOF. This is misleading when you look at the help generated in the ISE and results in the somewhat difficult to troubleshoot error message:

PowerShell DSC resource MSFT_xWebsite failed to execute Test-TargetResource functionality with error message: PowerShell Desired State Configuration does not support execution of
commands in an interactive mode. Please ensure that the underlying command is not prompting for user input, such as missing mandatory parameter, confirmation prompt etc.

xWebAppPool InvalidCastToXmlDocument

The Get-TargetResource and the Test-TargetResource functions in the xWebAppPool resource may fail on trying to cast appcmd.exe XML string output to an XmlDocument. For example if application pool user has "<" in its password.
I think this bug may be interrelated with #92 (UPDATE: it was not related).

Error:

Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "'<', hexadecimal value 0x3C, is an
invalid attribute character. Line 2, position 90."
At line:1 char:1
+ [xml] $PoolConfig = Invoke-AppCmd -Arguments list,apppool,$Name,/conf ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

Event Log Entry:

This event indicates that a non-terminating error was thrown when DSCEngine was executing Test-TargetResource on MSFT_xWebAppPool DSC resource. FullyQualifiedErrorId is InvalidCastToXmlDocument. Error Message is Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "'<', hexadecimal value 0x3C, is an invalid attribute character. Line 2, position 90.".

Create SMTP Server Resource

Having just stood up an SMTP Relay server in IIS it would have been super handy to have. If anyone wants to cobble something together I'd be greatful.

Ideally it would allow you to configure every property available to configure.

A full list would be found by running:

$mySite = [ADSI]"IIS://localhost/smtpsvc/1"
$mysite.Properties | gm

Some psudocode to get someone started would be:

Set Code:

$mySite = [ADSI]"IIS://Localhost/smtpsvc/1"
$mySite.Put("LogType", 1)
$mySite.Put("LogFileDirectory", "C:\inetpub\logs")
$mySite.Put("LogFileTruncateSize" , "19922944")
$mySite.Put("LogFilePeriod", "1")
$mySite.Put("LogExtFileFlags", "4194303")
$mySite.SetInfo()

Get Code

$mySite = [ADSI]"IIS://Localhost/smtpsvc/1"
$mySite.Properties['LogFileDirectory']

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.