I am running a jenkinsfile using multiline powershell to add VMs to domain and dns.
pipeline {
agent { label 'slave-windows' }
stages {
stage('Parameters') {
steps {
script {
properties([
parameters([
string(name: 'VM_NAME', defaultValue: '', description: 'Enter the VM you would like to add to Domain.'),
string(name: 'IP_ADDR', defaultValue: '', description: 'Enter the IP of your VM.')
])
])
}
}
}
stage('domain') {
steps {
powershell '''
\$VM_NAME=\$VM_NAME
\$DOMAIN="domain"
\$IP_ADDR=\$IP_ADDR
\$DNS="adserver"
\$username="domain\\administrator"
\$password="password" | ConvertTo-SecureString -asPlainText -Force
\$credential=New-Object System.Management.Automation.PSCredential(\$username,\$password)
Add-Computer -ComputerName \$VM_NAME -Domain \$DOMAIN -Credential \$credential -Restart
Enter-PSSession -ComputerName \$DNS
Add-DnsServerResourceRecordA –ComputerName \$DNS -Name \$VM_NAME -ZoneName \$DOMAIN -AllowUpdateAny -IPv4Address \$IP_ADDR
'''
}
}
}
The vm_name and ip_addr is passed by the user on build run. When I run the build, I get an error that the vm_name variables is null:
powershell.exe : Add-Computer : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\jenkins\workspace\DNS Registration\Add To Domain@tmp\durable-809aaad3\powershellScript.ps1:10 char:48
Add-Computer -ComputerName $VM_NAME -Domain $DOMA ...
CategoryInfo : InvalidData: (:) [Add-Computer], ParentContainsErrorRecordException
FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.AddComputerCommand
I am passing the vm_name on build run but for some reason it doesn't seem to pick up the value. Any ideas?
CodePudding user response:
You are treating all variables in the powershell
step method as PS variables, but it seems like you really want VM_NAME
and IP_ADDR
to be Groovy variables from the Jenkines Pipeline params
object specified in the parameters
directive. Modifying the code to interpolate Groovy variables, and to use the params
object values arrives at:
powershell """
\$DOMAIN="domain"
\$DNS="adserver"
\$username="domain\\administrator"
\$password="password" | ConvertTo-SecureString -asPlainText -Force
\$credential=New-Object System.Management.Automation.PSCredential(\$username,\$password)
Add-Computer -ComputerName ${params.VM_NAME} -Domain \$DOMAIN -Credential \$credential -Restart
Enter-PSSession -ComputerName \$DNS
Add-DnsServerResourceRecordA –ComputerName \$DNS -Name ${params.VM_NAME} -ZoneName \$DOMAIN -AllowUpdateAny -IPv4Address ${params.IP_ADDR}
"""
which will fix the issue in your question.