Skip to content

Instantly share code, notes, and snippets.

@tcotav
Created November 15, 2013 19:08
Show Gist options
  • Save tcotav/7489860 to your computer and use it in GitHub Desktop.
Save tcotav/7489860 to your computer and use it in GitHub Desktop.
Recipe snippet to join a host to AD via Powershell using Chef (Chef::Mixin::PowershellOut)
#
# set this up for reboot should we join domain successfully
#
windows_reboot 5 do
reason 'Reboot after joining AD'
action :nothing
end
#
# import mixin powershellout here
# also, make sure that Powershell cookbook is on active runlist for node
#
::Chef::Recipe.send(:include, Chef::Mixin::PowershellOut)
########################################################################################
# put the powershell script in here between the ruby heredoc string thingies
# ref: http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#here_doc
#
script =<<-'EOF'
$exitVal=0;
function addComputer { param([string]$username, [string]$password, [string]$domain)
try {
if ((gwmi win32_computersystem).partofdomain -eq $true) {
# arguably here, I would check if it is the RIGHT domain... next rev...
# $domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
# $domainName = $domain.name
# < compare with passed in value >
$message = \"The system is joined to the domain\";
$exitVal=2;
}
else {
add-computer -domain $domain -credential (New-Object System.Management.Automation.PSCredential ($username, (ConvertTo-SecureString $password -AsPlainText -Force))) -passthru -verbose
$message = \"computer joined to domain\";
$exitVal=3;
}
}
catch
{
$message = \"Join Error - \";
$message += $_;
$exitVal=1;
}
write-host $message;
exit $exitVal;
}
# this next line uses ruby
addComputer #{node['ad']['user']} #{node['ad']['pwd']} #{node['ad']['domain']}
EOF
########################################################################################
#
#
result = powershell_out(script)
Chef::Log.debug("powershell exit #{result.exitstatus}")
Chef::Log.debug("powershell error #{result.stderr}")
Chef::Log.debug("powershell stdout #{result.stdout}")
# same as shell_out
if result.exitstatus == 2
Chef::Log.debug("Already part of domain: #{result.stdout}")
elsif result.exitstatus == 3
Chef::Log.debug("Joined domain: #{result.stdout}")
# reboot if joining domain
notifies :request, 'windows_reboot[5]', :delayed
else
Chef::Log.error("Domain join fail: #{result.stdout}")
# any other actions here? maybe flag the node?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment