Tuesday, October 1, 2013

Chef and Windows - Group Membership Provider

So I need to add a domain user to the local machines administrators group.  Luckily, or so I thought, I could simply use Chef's group provider to do this.

I wrote the step in my cookbook as follows:

1
2
3
4
5
group "administrators" do
   action :modify
   append true
   members "#{user_domain}\\#{user}"
end
This works great the first time, but will fail after that with the following error:
ArgumentError: The specified account name is already a member of the group.

A quick search, and you'll find that this is a known issue, open since end of March.

So until Windows support becomes a priority, we are stuck with a workaround.  We have some options, WMI, .Net, Ruby, or Net.exe calls.

I am sure there is a better way, but I went with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
::Chef::Resource::Group.send(:include, Chef::Mixin::PowershellOut)
 
check_for_membership = <<-EOH
  $dsam = 'System.DirectoryServices.AccountManagement'
  $rtn = [reflection.assembly]::LoadWithPartialName($dsam)
  $context = New-Object 'System.DirectoryServices.AccountManagement.PrincipalContext'('machine', 'localhost')
  $gp = 'System.DirectoryServices.AccountManagement.GroupPrincipal' -as [type]
  $find = $gp::FindByIdentity($context, 'Administrators')
  return ($find.Members | where SamAccountName -eq '#{user}').Length -gt 0
EOH
 
# add user to local admins
group "administrators" do
  action :modify
  append true
  members "#{user_domain}\\#{user}"
  only_if {
    result = powershell_out(check_for_membership)
    result.stdout.chop == "False"
  }
end

No comments:

Post a Comment