hashicorp / terraform-provider-azurerm

Terraform provider for Azure Resource Manager
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs
Mozilla Public License 2.0
4.6k stars 4.64k forks source link

DSC extension with arm tmeplate - PSCredential name or password incorrect #7381

Closed ghost closed 3 years ago

ghost commented 4 years ago

This issue was originally opened by @Alexandre-Delaunay as hashicorp/terraform#25267. It was migrated here as a result of the provider split. The original body of the issue is below.


Terraform Version & Windows Server

v0.12.26 Windows Server 2016

Terraform Configuration Files

The following code is my DSC extension

resource "azurerm_virtual_machine_extension" "DeployRDS" {
  count                = var.brokers_number
  name                 = "deployRDS"
  location             = var.location
  resource_group_name  = var.vm_windows_rg_name
  virtual_machine_name = "${var.prefix}-${var.env}-${var.brokers_prefix}${count.index + 1}"
  publisher            = "Microsoft.Powershell"
  type                 = "DSC"
  type_handler_version = "2.77"

  settings           = <<SETTINGS
            {
                "WmfVersion": "latest",
                "configuration": {
                    "url": "${var.url_archive}",                    
                    "script": "Configuration.ps1",
                    "function": "RDSDeployment"
                },
                "configurationArguments": {
                    "DomainName": "${var.active_directory_domain}",
                    "connectionBroker": "${var.prefix}-${var.env}-${var.brokers_prefix}1.${var.active_directory_domain}",
                    "externalfqdn": "gateway-access.mydomainname",    
                    "numberOfRdshInstances" : "${var.tses_number}",
                    "sessionHostNamingPrefix": "${var.prefix}-${var.env}-${var.tses_prefix}",
                    "webAccessServer": "${var.prefix}-${var.env}-${var.gateways_prefix}1.${var.active_directory_domain}"
                }
            }
            SETTINGS
  protected_settings = <<PROTECTED_SETTINGS
        { 
            "configurationArguments": {
                "adminCreds": {
                    "UserName": "${var.active_directory_username}",
                    "Password": "${var.active_directory_password}"
                }
            },
            "configurationUrlSasToken": "${var.url_archive_token}"
        }
    PROTECTED_SETTINGS
  depends_on = [var.archive_uploaded_depends_on, azurerm_virtual_machine_extension.join_domain, var.tses_module_depends_on, var.gateways_module_depends_on]

}

The next is my function RDSDeployment using ARM template from here

configuration RDSDeployment
{
   param 
    ( 
        [Parameter(Mandatory)]
        [String]$domainName,

        [Parameter(Mandatory)]
        [PSCredential]$adminCreds,

        # Connection Broker Node name
        [String]$connectionBroker,

        # Web Access Node name
        [String]$webAccessServer,

        # Gateway external FQDN
        [String]$externalFqdn,

        # RD Session Host count and naming prefix
        [Int]$numberOfRdshInstances = 1,
        [String]$sessionHostNamingPrefix = "SessionHost-",

        # Collection Name
        [String]$collectionName,

        # Connection Description
        [String]$collectionDescription

    ) 

    Import-DscResource -ModuleName PSDesiredStateConfiguration -ModuleVersion 1.1
    Import-DscResource -ModuleName xActiveDirectory, xComputerManagement, xRemoteDesktopSessionHost

    $localhost = [System.Net.Dns]::GetHostByName((hostname)).HostName

    [SecureString]$password = ConvertTo-SecureString -String $adminCreds.Password -AsPlainText -Force
    $username = $adminCreds.UserName -split '\\' | Select-Object -last 1
    $domainCreds = New-Object System.Management.Automation.PSCredential ($username, $password)

    #Log OK
    Set-Content -Path C:\log_AdminCreds_Username.txt -Value ($adminCreds.UserName)

    #Log KO
    $adminCredsPasswordTemp = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($adminCreds.Password)
    $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($adminCredsPasswordTemp)    
    Set-Content -Path C:\log_AdminCreds_Password.txt -Value ($UnsecurePassword)

    if (-not $connectionBroker)   { $connectionBroker = $localhost }
    if (-not $webAccessServer)    { $webAccessServer  = $localhost }

    if ($sessionHostNamingPrefix)
    { 
        $sessionHosts = @( 1..($numberOfRdshInstances) | ForEach-Object { "$sessionHostNamingPrefix$_.$domainname"} )
    }
    else
    {
        $sessionHosts = @( $localhost )
    }

    if (-not $collectionName)         { $collectionName = "Desktop Collection" }
    if (-not $collectionDescription)  { $collectionDescription = "A sample RD Session collection up in cloud." }

    Node localhost
    {
        LocalConfigurationManager
        {
            RebootNodeIfNeeded = $true
            ConfigurationMode = "ApplyOnly"
            ConfigurationModeFrequencyMins = 1200
        }

        WindowsFeature 'NetFramework45' # added to support 2019 SD nov 2019
        {
            Name   = 'NET-Framework-45-Features'
            Ensure = 'Present'
            IncludeAllSubFeature = $true
        }

        WindowsFeature InstallWebServer  # added to support 2019 SD nov 2019
        { 
            Ensure = "Present"
            Name = "Web-Server" 
            IncludeAllSubFeature = $true
        } 

        WindowsFeature RSAT-RDS-Tools
        {
            Ensure = "Present"
            Name = "RSAT-RDS-Tools"
            IncludeAllSubFeature = $true
        }

        WindowsFeature RDS-Licensing
        {
            Ensure = "Present"
            Name = "RDS-Licensing"
        }

        xRDSessionDeployment Deployment
        {
            ConnectionBroker = $connectionBroker
            WebAccessServer  = $webAccessServer

            SessionHosts     = $sessionHosts

            PsDscRunAsCredential = $domainCreds
        }

        xRDServer AddLicenseServer
        {
            DependsOn = "[xRDSessionDeployment]Deployment"

            Role    = 'RDS-Licensing'
            Server  = $connectionBroker

            PsDscRunAsCredential = $domainCreds
        }

        xRDLicenseConfiguration LicenseConfiguration
        {
            DependsOn = "[xRDServer]AddLicenseServer"

            ConnectionBroker = $connectionBroker
            LicenseServers   = @( $connectionBroker )

            LicenseMode = 'PerUser'

            PsDscRunAsCredential = $domainCreds
        }

        xRDServer AddGatewayServer
        {
            DependsOn = "[xRDLicenseConfiguration]LicenseConfiguration"

            Role    = 'RDS-Gateway'
            Server  = $webAccessServer

            GatewayExternalFqdn = $externalFqdn

            PsDscRunAsCredential = $domainCreds
        }

        xRDGatewayConfiguration GatewayConfiguration
        {
            DependsOn = "[xRDServer]AddGatewayServer"

            ConnectionBroker = $connectionBroker
            GatewayServer    = $webAccessServer

            ExternalFqdn = $externalFqdn

            GatewayMode = 'Custom'
            LogonMethod = 'Password'

            UseCachedCredentials = $true
            BypassLocal = $false

            PsDscRunAsCredential = $domainCreds
        } 

        xRDSessionCollection Collection
        {
            DependsOn = "[xRDGatewayConfiguration]GatewayConfiguration"

            ConnectionBroker = $connectionBroker

            CollectionName = $collectionName
            CollectionDescription = $collectionDescription

            SessionHosts = $sessionHosts

            PsDscRunAsCredential = $domainCreds
        }

    }

Expected Behavior

A successful connection.

Actual Behavior

In my azure pipeline when i run Terraform apply i got the error,

Error: Code="VMExtensionProvisioningError" Message="VM has reported a failure when processing extension 'deployRDS'. Error message: \"DSC Configuration 'RDSDeployment' completed with error(s). Following are the first few: The user name or password is incorrect The SendConfigurationApply function did not succeed.\"\r\n\r\nMore information on troubleshooting is available at https://aka.ms/VMExtensionDSCWindowsTroubleshoot "

Additional Context

This script is called from a windows server used like broker to deploy to multiples machines named tses.

Logs from the DSC logs on the windows server (broker),

[[WindowsFeature]RDS-Licensing] Installation succeeded. VERBOSE: [2020-06-05 14:23:06Z] [VERBOSE] [tf-stage-brk1]: [[WindowsFeature]RDS-Licensing] Successfully installed the feature RDS-Licensing. VERBOSE: [2020-06-05 14:23:06Z] [VERBOSE] [tf-stage-brk1]: LCM: [ End Set ] [[WindowsFeature]RDS-Licensing] in 16.9570 seconds. VERBOSE: [2020-06-05 14:23:06Z] [VERBOSE] [tf-stage-brk1]: LCM: [ End Resource ] [[WindowsFeature]RDS-Licensing] VERBOSE: [2020-06-05 14:23:06Z] [VERBOSE] [tf-stage-brk1]: LCM: [ Start Resource ] [[xRDSessionDeployment]Deployment] VERBOSE: [2020-06-05 14:23:06Z] [VERBOSE] [tf-stage-brk1]: LCM: [ Start Test ] [[xRDSessionDeployment]Deployment] VERBOSE: [2020-06-05 14:23:07Z] [VERBOSE] [tf-stage-brk1]: LCM: [ End Test ] [[xRDSessionDeployment]Deployment] in 0.3440 seconds. VERBOSE: [2020-06-05 14:23:07Z] [ERROR] The user name or password is incorrect VERBOSE: [2020-06-05 14:23:07Z] [VERBOSE] [tf-stage-brk1]: LCM: [ End Set ] VERBOSE: [2020-06-05 14:23:07Z] [ERROR] The SendConfigurationApply function did not succeed.

I tried to logs what i receive on the machine,

image

then try a connection with the same username and password i got from logs,

$adminCreds = @{ UserName = "adminusername@mydomain" ; Password = adminpassword" } [SecureString]$password = ConvertTo-SecureString -String $adminCreds.Password -AsPlainText -Force $username = $adminCreds.UserName -split '\' | Select-Object -last 1 domainCreds = New-Object System.Management.Automation.PSCredential (domainCreds=New−ObjectSystem.Management.Automation.PSCredential(username, $password) Invoke-Command -ComputerName tf-stage-tse1 -ScriptBlock { Get-ChildItem C:\ } -credential $domainCreds

and it succeeded.

image

Alexandre-Delaunay commented 4 years ago

When i try to execute the script with the parameters on the machine, i got this error:

image

It probably come from the way i use DSC configuration settings with the string in password?

favoretti commented 3 years ago

Thanks for opening this issue! Since this issue has been reported a long time ago and relates to an older version of provider - I'm going to close it. If this is still relevant and occurring on the latest version of terraform and provider please do open a new issue!

github-actions[bot] commented 3 years ago

I'm going to lock this issue because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues. If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.