hashicorp / terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
https://www.terraform.io/
Other
42.72k stars 9.55k forks source link

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

Closed Alexandre-Delaunay closed 4 years ago

Alexandre-Delaunay commented 4 years ago

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

danieldreier commented 4 years ago

@Alexandre-Delaunay thanks for reporting this. We use GitHub issues for tracking bugs and enhancements to Terraform Core itself, rather than for questions and troubleshooting.

I can see clearly that your configuration isn't working as expected, but it's less clear to me that there is a specific bug in Terraform Core itself. We don't have any specific experience using DSC or Azure on this team - we just maintain Terraform Core itself.

I think that this is an issue to be addressed in the AzureRM Terraform provider, rather than in core. I'm going to label it as such, and the HashiBot will shortly migrate it over to the provider GitHub repository. Please feel free to re-open this if they determine that it is indeed an issue that needs to be addressed in Terraform core.

They may also determine that this is a configuration issue rather than a bug. While we can sometimes help with certain simple problems here, it's better to use the community forum for questions.

ghost commented 4 years ago

This issue has been automatically migrated to terraform-providers/terraform-provider-azurerm#7381 because it looks like an issue with that provider. If you believe this is not an issue with the provider, please reply to terraform-providers/terraform-provider-azurerm#7381.

ghost commented 4 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.