Update sudo and users cookbooks

This commit is contained in:
Greg Karékinian 2017-05-02 11:39:43 +02:00
parent d7bdd5cdf3
commit 11b812fbb8
22 changed files with 282 additions and 278 deletions

4
Batali
View File

@ -19,8 +19,8 @@ Batali.define do
cookbook 'application_javascript'
cookbook 'application_ruby'
cookbook 'application_git', '~> 1.1.0' # 1.2.0 doesn't work with knife-solo
cookbook 'users'
cookbook 'sudo'
cookbook 'users', '~> 5.0.0'
cookbook 'sudo', '~> 3.4.0'
cookbook 'hostname'
cookbook 'redis',
git: 'https://github.com/phlipper/chef-redis.git',

View File

@ -900,11 +900,11 @@
"dependencies": [
],
"version": "4.0.3",
"version": "5.0.0",
"source": {
"type": "Batali::Source::Site",
"url": "https://supermarket.chef.io:443/api/v1/cookbooks/users/versions/4.0.3/download",
"version": "4.0.3"
"url": "https://supermarket.chef.io:443/api/v1/cookbooks/users/versions/5.0.0/download",
"version": "5.0.0"
}
},
{
@ -912,11 +912,11 @@
"dependencies": [
],
"version": "3.3.1",
"version": "3.4.0",
"source": {
"type": "Batali::Source::Site",
"url": "https://supermarket.chef.io:443/api/v1/cookbooks/sudo/versions/3.3.1/download",
"version": "3.3.1"
"url": "https://supermarket.chef.io:443/api/v1/cookbooks/sudo/versions/3.4.0/download",
"version": "3.4.0"
}
},
{

View File

@ -2,6 +2,15 @@
This file is used to list changes made in each version of the sudo cookbook.
## 3.4.0 (2017-04-26)
- Add lwrp support for only env_keep add/subtract
- Readme improvements
- Move the files out of the default directory since Chef >= 12 doesn't require this
- Test with Local Delivery instead of Rake
- Cookstyle fixes
- Update apache2 license string
## 3.3.1 (2017-01-17)
- fixed command_aliases in README

View File

@ -2,9 +2,7 @@
[![Build Status](https://travis-ci.org/chef-cookbooks/sudo.svg?branch=master)](http://travis-ci.org/chef-cookbooks/sudo) [![Cookbook Version](https://img.shields.io/cookbook/v/sudo.svg)](https://supermarket.chef.io/cookbooks/sudo)
The Chef `sudo` cookbook installs the `sudo` package and configures the `/etc/sudoers` file.
It also exposes an LWRP for adding and managing sudoers.
The default recipe installs the `sudo` package and configures the `/etc/sudoers` file. The cookbook also includes a sudo resource to adding and removing individual sudo entries.
## Requirements
@ -25,6 +23,7 @@ It also exposes an LWRP for adding and managing sudoers.
- None
## Attributes
- `node['authorization']['sudo']['groups']` - groups to enable sudo access (default: `[ "sysadmin" ]`)
- `node['authorization']['sudo']['users']` - users to enable sudo access (default: `[]`)
- `node['authorization']['sudo']['passwordless']` - use passwordless sudo (default: `false`)
@ -34,7 +33,9 @@ It also exposes an LWRP for adding and managing sudoers.
- `node['authorization']['sudo']['setenv']` - Whether to permit preserving of environment with `sudo -E` (default: `false`)
## Usage
### Attributes
To use attributes for defining sudoers, set the attributes above on the node (or role) itself:
```json
@ -105,6 +106,7 @@ default_attributes(
**Note that the template for the sudoers file has the group "sysadmin" with ALL:ALL permission, though the group by default does not exist.**
### Sudoers Defaults
Configure a node attribute, `node['authorization']['sudo']['sudoers_defaults']` as an array of `Defaults` entries to configure in `/etc/sudoers`. A list of examples for common platforms is listed below:
_Debian_
@ -113,12 +115,6 @@ _Debian_
node.default['authorization']['sudo']['sudoers_defaults'] = ['env_reset']
```
_Ubuntu 10.04_
```ruby
node.default['authorization']['sudo']['sudoers_defaults'] = ['env_reset']
```
_Ubuntu 12.04_
```ruby
@ -188,7 +184,8 @@ node.default['authorization']['sudo']['sudoers_defaults'] = [
]
```
### LWRP
### Sudo Resource
**Note** Sudo version 1.7.2 or newer is required to use the sudo LWRP as it relies on the "#includedir" directive introduced in version 1.7.2. The recipe does not enforce installing the version. To use this LWRP, set `node['authorization']['sudo']['include_sudoers_d']` to `true`.
There are two ways for rendering a sudoer-fragment using this LWRP:
@ -225,7 +222,8 @@ In either case, the following file would be generated in `/etc/sudoers.d/tomcat`
%tomcat ALL=(app_user) /etc/init.d/tomcat restart
```
#### LWRP Attributes
#### Resource Properties
<table>
<thead>
<tr>
@ -321,42 +319,8 @@ case it is not already</td>
**If you use the template attribute, all other attributes will be ignored except for the variables attribute.**
## Development
This section details "quick development" steps. For a detailed explanation, see [[Contributing.md]].
- Clone this repository from GitHub:
```
$ git clone git@github.com:chef-cookbooks/sudo.git
```
- Create a git branch
```
$ git checkout -b my_bug_fix
```
- Install dependencies:
```
$ bundle install
```
- Make your changes/patches/fixes, committing appropiately
- **Write tests**
- Run the tests:
- `bundle exec foodcritic -f any .`
- `bundle exec rspec`
- `bundle exec rubocop`
- `bundle exec kitchen test`
In detail:
- Foodcritic will catch any Chef-specific style errors
- RSpec will run the unit tests
- Rubocop will check for Ruby-specific style errors
- Test Kitchen will run and converge the recipes
## License & Authors
**Author:** Bryan W. Berry [bryan.berry@gmail.com](mailto:bryan.berry@gmail.com)
**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))

File diff suppressed because one or more lines are too long

View File

@ -47,7 +47,7 @@ def validate_fragment!(resource)
file.rewind
cmd = Mixlib::ShellOut.new("visudo -cf #{file.path}").run_command
unless cmd.exitstatus.zero?
unless cmd.exitstatus == 0
Chef::Log.error("Fragment validation failed: \n\n")
Chef::Log.error(file.read)
Chef::Application.fatal!("Template #{file.path} failed fragment validation!")
@ -77,7 +77,7 @@ def render_sudoer
action :nothing
end
else
sudoer = new_resource.user || "%#{new_resource.group}".squeeze('%')
sudoer = new_resource.user || ("%#{new_resource.group}".squeeze('%') if new_resource.group)
resource = template "#{node['authorization']['sudo']['prefix']}/sudoers.d/#{sudo_filename}" do
source 'sudoer.erb'

View File

@ -31,7 +31,6 @@ if node['authorization']['sudo']['include_sudoers_d']
end
cookbook_file "#{prefix}/sudoers.d/README" do
source 'README'
mode '0440'
owner 'root'
group node['root_group']

View File

@ -14,7 +14,7 @@ Defaults env_keep -= "<%= env_keep %>"
<% end -%>
<% @commands.each do |command| -%>
<%= @sudoer %> <%= @host %>=(<%= @runas %>) <%= 'NOEXEC:' if @noexec %><%= 'NOPASSWD:' if @nopasswd %><%= 'SETENV:' if @setenv %><%= command %>
<% if @sudoer %><%= @sudoer %> <%= @host %>=(<%= @runas %>) <%= 'NOEXEC:' if @noexec %><%= 'NOPASSWD:' if @nopasswd %><%= 'SETENV:' if @setenv %><%= command %><% end -%>
<% end -%>
<% unless @defaults.empty? %>

View File

@ -1 +0,0 @@
~FC003

View File

@ -1,16 +1,37 @@
# users Cookbook CHANGELOG
This file is used to list changes made in each version of the users cookbook.
## 5.0.0 (2017-04-17)
### Breaking changes
- The users_manage LWRP has been converted to a custom resource, which requires Chef 12.5 or later
- The sysadmins recipe contains no resources now and will do nothing
### Other changes
- Added integration tests with Inspec
- Fixed all deprecation warnings
- Fixed group creation on macOS when the group already exists
- Added suse platforms as supported in the metadata
- Switched to a SPDX apache-2.0 license string
- Moved all templates out of the default directory as we don't support Chef 11 anymore
## 4.0.3 (2016-11-23)
- Update manage provider to return true/false in guard block which avoids warnings during run on Chef 12.14+
## 4.0.2 (2016-11-18)
- Deprecate the sysadmins recipe
## 4.0.1 (2016-09-15)
- Fix creation of user home directory
## 4.0.0 (2016-09-15)
- Add chef_version to the metadata
- Require Chef 12.1+
- Testing updates
@ -19,27 +40,32 @@ This file is used to list changes made in each version of the users cookbook.
- Add a warning if someone includes users::default since that does nothing
## v3.0.0
- @onlyhavecans - Fix FreeBSD support
- @stem - Fix user creation on Mac OS X on 10.7 and 10.8
- Remove old style chef solo code to clean up rubocop issues, move to using cookstyle
- Adding zlinux support
## v2.0.3
- @nkadel-skyhook - create .ssh directory only if keys are configured.
- @signe - allow force parameter to be specified for users configured to be removed.
- @FlorentFlament - adding the ability to manage groups for existing users.
## v2.0.2 (2016-1-25)
- @375gnu- validate uid/gid for strings versus numeric
- fix rubocop errors based on https://github.com/bbatsov/rubocop/issues/2608
- fix rubocop errors based on <https://github.com/bbatsov/rubocop/issues/2608>
- fix kitchen configurations for testing
## v2.0.1 (2016-1-8)
- Fixed provider to work on Mac OS X
- funzoneq - add correct default shell for FreeBSD if not provided
- Added kitchen.dokken to speed up platform testing
## v2.0.0 (2015-12-11)
- Removed Chef 10 compatibility code
- Removed the nodes fqdn from the authorized_keys file
- Removed a trailing comma in a readme example
@ -48,12 +74,15 @@ This file is used to list changes made in each version of the users cookbook.
- Resolved foodcritic warnings
## v1.8.2 (2015-03-18)
- No changes, just republishing 1.8.1
## v1.8.1 (2015-03-12)
- Add `source_url` and `issues_url` to the metadata.rb so Supermarket can display appropriate links
## v1.8.0 (2015-03-09)
- Expose LWRP state attributes
- [COOK-4401] - Add unit tests with ChefSpec
- [COOK-4404] - Determine file system and add manage_nfs_home_dirs attribute to disable managing NFS mounted home directories
@ -65,40 +94,52 @@ This file is used to list changes made in each version of the users cookbook.
- Updates for RSpec 3
## v1.7.0 (2014-02-14)
- [COOK-4139] - users_manage resource always notifies
- [COOK-4078] - users cookbook fails in why-run mode for .ssh directory
- [COOK-3959] - Add support for Mac OS X to users cookbook
## v1.6.0
### Bug
- **[COOK-3744](https://tickets.opscode.com/browse/COOK-3744)** - Allow passing an action option via the `data_bag` to the user resource
## v1.5.2
### Bug
- **[COOK-3215](https://tickets.opscode.com/browse/COOK-3215)** - Make `group_id` optional
## v1.5.0
- [COOK-2427] - Mistakenly released instead of sudo :-).
## v1.4.0
- [COOK-2479] - Permit users cookbook to work with chef-solo if edelight/chef-solo-search is installed
- [COOK-2486] - specify precedence when setting node attribute
## v1.3.0
- [COOK-1842] - allow specifying private SSH keys
- [COOK-2021] - Empty default recipe for including users LWRPs
## v1.2.0
- [COOK-1398] - Provider manage.rb ignores username attribute
- [COOK-1582] - ssh_keys should take an array in addition to a string separated by new lines
## v1.1.4
- [COOK-1396] - removed users get recreated
- [COOK-1433] - resolve foodcritic warnings
- [COOK-1583] - set passwords for users
## v1.1.2
- [COOK-1076] - authorized_keys template not found in another cookbook
## v1.1.0
- [COOK-623] - LWRP conversion

View File

@ -12,21 +12,22 @@ This cookbook is concerned with the management of OS users and groups from datab
A data bag populated with user objects must exist. The default data bag in this recipe is `users`. See USAGE.
### Chef
- Chef 12.1+
### Platform Support
### Platforms
The following platforms have been tested with Test Kitchen:
- Debian / Ubuntu and derivatives
- Debian / Ubuntu derivatives
- RHEL and derivatives
- Fedora
- openSUSE / SUSE Linux Enterprises
- FreeBSD / OpenBSD
- Mac OS X
### Cookbook Dependencies
### Chef
- Chef 12.5+
### Cookbooks
- none
@ -303,7 +304,7 @@ The Apache cookbook can set up authentication using OpenIDs, which is set up usi
**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))
**Copyright:** 2009-2016, Chef Software, Inc.
**Copyright:** 2009-2017, Chef Software, Inc.
```
Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -1,5 +1,3 @@
require 'mixlib/shellout'
module Users
# Helpers for Users
module Helpers
@ -28,8 +26,16 @@ module Users
def validate_id(id)
id.to_i.to_s == id ? id.to_i : id
end
# Returns the appropriate base user home directory per platform
#
# @return [ String]
def home_basedir
if platform_family?('mac_os_x')
'/Users'
else
'/home'
end
end
end
end
Chef::Resource.send(:include, ::Users::Helpers)
Chef::Provider.send(:include, ::Users::Helpers)

View File

@ -0,0 +1,29 @@
module Users
# Helpers for Users
module OsxHelper
def dscl(*args)
host = '.'
stdout_result = ''
stderr_result = ''
cmd = "dscl #{host} -#{args.join(' ')}"
status = shell_out(cmd)
status.stdout.each_line { |line| stdout_result << line }
status.stderr.each_line { |line| stderr_result << line }
[cmd, status, stdout_result, stderr_result]
end
def safe_dscl(*args)
result = dscl(*args)
return '' if (args.first =~ /^delete/) && (result[1].exitstatus != 0)
raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") unless result[1].exitstatus == 0
raise(Chef::Exceptions::Group, "dscl error: #{result.inspect}") if result[2] =~ /No such key: /
result[2]
end
def gid_used?(gid)
return false unless gid
groups_gids = safe_dscl('list /Groups gid')
!!(groups_gids =~ Regexp.new("#{Regexp.escape(gid.to_s)}\n"))
end
end
end

File diff suppressed because one or more lines are too long

View File

@ -1,172 +0,0 @@
#
# Cookbook:: users
# Provider:: manage
#
# Copyright:: 2011-2016, Eric G. Wolfe
# Copyright:: 2009-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
use_inline_resources
def whyrun_supported?
true
end
action :remove do
search(new_resource.data_bag, "groups:#{new_resource.search_group} AND action:remove") do |rm_user|
user rm_user['username'] ||= rm_user['id'] do
action :remove
force rm_user['force'] ||= false
end
end
end
action :create do
users_groups = {}
users_groups[new_resource.group_name] = []
search(new_resource.data_bag, "groups:#{new_resource.search_group} AND NOT action:remove") do |u|
u['username'] ||= u['id']
u['groups'].each do |g|
users_groups[g] = [] unless users_groups.key?(g)
users_groups[g] << u['username']
end
if node['apache'] && node['apache']['allowed_openids']
Array(u['openid']).compact.each do |oid|
node.default['apache']['allowed_openids'] << oid unless node['apache']['allowed_openids'].include?(oid)
end
end
# Platform specific checks
# Set home_basedir
# Set shell on FreeBSD
home_basedir = '/home'
case node['platform_family']
when 'mac_os_x'
home_basedir = '/Users'
when 'freebsd'
# Check if we need to prepend shell with /usr/local/?
u['shell'] = (!::File.exist?(u['shell']) && ::File.exist?("/usr/local#{u['shell']}") ? "/usr/local#{u['shell']}" : '/bin/sh')
end
# Set home to location in data bag,
# or a reasonable default ($home_basedir/$user).
home_dir = (u['home'] ? u['home'] : "#{home_basedir}/#{u['username']}")
# check whether home dir is null
manage_home = (home_dir == '/dev/null' ? false : true)
# The user block will fail if the group does not yet exist.
# See the -g option limitations in man 8 useradd for an explanation.
# This should correct that without breaking functionality.
group u['username'] do # ~FC022
gid validate_id(u['gid'])
only_if { u['gid'] && u['gid'].is_a?(Numeric) }
end
# Create user object.
# Do NOT try to manage null home directories.
user u['username'] do
uid validate_id(u['uid'])
gid validate_id(u['gid']) if u['gid']
shell u['shell']
comment u['comment']
password u['password'] if u['password']
salt u['salt'] if u['salt']
iterations u['iterations'] if u['iterations']
manage_home manage_home
home home_dir
action u['action'] if u['action']
end
if manage_home_files?(home_dir, u['username'])
Chef::Log.debug("Managing home files for #{u['username']}")
directory "#{home_dir}/.ssh" do
recursive true
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0700'
only_if { !!(u['ssh_keys'] || u['ssh_private_key'] || u['ssh_public_key']) }
end
template "#{home_dir}/.ssh/authorized_keys" do
source 'authorized_keys.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0600'
variables ssh_keys: u['ssh_keys']
only_if { !!(u['ssh_keys']) }
end
if u['ssh_private_key']
key_type = u['ssh_private_key'].include?('BEGIN RSA PRIVATE KEY') ? 'rsa' : 'dsa'
template "#{home_dir}/.ssh/id_#{key_type}" do
source 'private_key.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0400'
variables private_key: u['ssh_private_key']
end
end
if u['ssh_public_key']
key_type = u['ssh_public_key'].include?('ssh-rsa') ? 'rsa' : 'dsa'
template "#{home_dir}/.ssh/id_#{key_type}.pub" do
source 'public_key.pub.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0400'
variables public_key: u['ssh_public_key']
end
end
else
Chef::Log.debug("Not managing home files for #{u['username']}")
end
end
# Populating users to appropriates groups
users_groups.each do |g, u|
group g do
members u
append true
action :manage # Do nothing if group doesn't exist
end unless g == new_resource.group_name # Dealing with managed group later
end
group new_resource.group_name do
gid new_resource.group_id if new_resource.group_id
members users_groups[new_resource.group_name]
end
end
private
def manage_home_files?(home_dir, _user)
# Don't manage home dir if it's NFS mount
# and manage_nfs_home_dirs is disabled
if home_dir == '/dev/null'
false
elsif fs_remote?(home_dir)
new_resource.manage_nfs_home_dirs ? true : false
else
true
end
end

View File

@ -2,7 +2,7 @@
# Cookbook:: users
# Recipe:: default
#
# Copyright:: 2009-2016, Chef Software, Inc.
# Copyright:: 2009-2017, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.

View File

@ -2,8 +2,8 @@
# Cookbook:: users
# Recipe:: sysadmins
#
# Copyright:: 2011-2016, Eric G. Wolfe
# Copyright:: 2009-2016, Chef Software, Inc.
# Copyright:: 2011-2017, Eric G. Wolfe
# Copyright:: 2009-2017, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -18,11 +18,4 @@
# limitations under the License.
#
Chef::Log.warn('The sysadmins recipe has been deprecated. We suggest using the users_manage resource in your own cookbook if you need similar functionality. The resource in this recipe will be removed with a major release of the cookbook in April 2017')
# Searches data bag "users" for groups attribute "sysadmin".
# Places returned users in Unix group "sysadmin" with GID 2300.
users_manage 'sysadmin' do
group_id 2300
action [:remove, :create]
end
Chef::Log.warn('The sysadmins recipe has been deprecated. We suggest using the users_manage resource in your own cookbook if you need similar functionality.')

View File

@ -2,7 +2,7 @@
# Cookbook:: users
# Resources:: manage
#
# Copyright:: 2011-2016, Eric G. Wolfe
# Copyright:: 2011-2017, Eric G. Wolfe
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -17,24 +17,159 @@
# limitations under the License.
#
# Data bag user object needs an "action": "remove" tag to actually be removed by the action.
actions :create, :remove
default_action :create
state_attrs :cookbook,
:data_bag,
:group_id,
:group_name,
:search_group
# :data_bag is the object to search
# :search_group is the groups name to search for, defaults to resource name
# :group_name is the string name of the group to create, defaults to resource name
# :group_id is the numeric id of the group to create, default is to allow the OS to pick next
# :cookbook is the name of the cookbook that the authorized_keys template should be found in
attribute :data_bag, kind_of: String, default: 'users'
attribute :search_group, kind_of: String, name_attribute: true
attribute :group_name, kind_of: String, name_attribute: true
attribute :group_id, kind_of: Integer
attribute :cookbook, kind_of: String, default: 'users'
attribute :manage_nfs_home_dirs, kind_of: [TrueClass, FalseClass], default: true
property :data_bag, String, default: 'users'
property :search_group, String, name_property: true
property :group_name, String, name_property: true
property :group_id, Integer
property :cookbook, String, default: 'users'
property :manage_nfs_home_dirs, [true, false], default: true
action :create do
users_groups = {}
users_groups[new_resource.group_name] = []
search(new_resource.data_bag, "groups:#{new_resource.search_group} AND NOT action:remove") do |u|
u['username'] ||= u['id']
u['groups'].each do |g|
users_groups[g] = [] unless users_groups.key?(g)
users_groups[g] << u['username']
end
# Check if we need to prepend shell with /usr/local/?
if platform_family? 'freebsd'
u['shell'] = (!::File.exist?(u['shell']) && ::File.exist?("/usr/local#{u['shell']}") ? "/usr/local#{u['shell']}" : '/bin/sh')
end
# Set home to location in data bag,
# or a reasonable default ($home_basedir/$user).
home_dir = (u['home'] ? u['home'] : "#{home_basedir}/#{u['username']}")
# check whether home dir is null
manage_home = (home_dir == '/dev/null' ? false : true)
# The user block will fail if the group does not yet exist.
# See the -g option limitations in man 8 useradd for an explanation.
# This should correct that without breaking functionality.
group u['username'] do # ~FC022
case node['platform_family']
when 'mac_os_x'
gid validate_id(u['gid']) unless gid_used?(validate_id(u['gid'])) || new_resource.group_name == u['username']
else
gid validate_id(u['gid'])
end
only_if { u['gid'] && u['gid'].is_a?(Numeric) }
end
# Create user object.
# Do NOT try to manage null home directories.
user u['username'] do
uid validate_id(u['uid'])
gid validate_id(u['gid']) if u['gid']
shell u['shell']
comment u['comment']
password u['password'] if u['password']
salt u['salt'] if u['salt']
iterations u['iterations'] if u['iterations']
manage_home manage_home
home home_dir
action u['action'] if u['action']
end
if manage_home_files?(home_dir, u['username'])
Chef::Log.debug("Managing home files for #{u['username']}")
directory "#{home_dir}/.ssh" do
recursive true
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0700'
only_if { !!(u['ssh_keys'] || u['ssh_private_key'] || u['ssh_public_key']) }
end
template "#{home_dir}/.ssh/authorized_keys" do
source 'authorized_keys.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0600'
variables ssh_keys: u['ssh_keys']
only_if { !!(u['ssh_keys']) }
end
if u['ssh_private_key']
key_type = u['ssh_private_key'].include?('BEGIN RSA PRIVATE KEY') ? 'rsa' : 'dsa'
template "#{home_dir}/.ssh/id_#{key_type}" do
source 'private_key.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0400'
variables private_key: u['ssh_private_key']
end
end
if u['ssh_public_key']
key_type = u['ssh_public_key'].include?('ssh-rsa') ? 'rsa' : 'dsa'
template "#{home_dir}/.ssh/id_#{key_type}.pub" do
source 'public_key.pub.erb'
cookbook new_resource.cookbook
owner u['uid'] ? validate_id(u['uid']) : u['username']
group validate_id(u['gid']) if u['gid']
mode '0400'
variables public_key: u['ssh_public_key']
end
end
else
Chef::Log.debug("Not managing home files for #{u['username']}")
end
end
# Populating users to appropriates groups
users_groups.each do |g, u|
group g do
members u
append true
action :manage # Do nothing if group doesn't exist
end unless g == new_resource.group_name # Dealing with managed group later
end
group new_resource.group_name do
case node['platform_family']
when 'mac_os_x'
gid new_resource.group_id unless gid_used?(new_resource.group_id)
else
gid new_resource.group_id
end
members users_groups[new_resource.group_name]
end
end
action :remove do
search(new_resource.data_bag, "groups:#{new_resource.search_group} AND action:remove") do |rm_user|
user rm_user['username'] ||= rm_user['id'] do
action :remove
force rm_user['force'] ||= false
end
end
end
action_class.class_eval do
include ::Users::Helpers
include ::Users::OsxHelper
def manage_home_files?(home_dir, _user)
# Don't manage home dir if it's NFS mount
# and manage_nfs_home_dirs is disabled
if home_dir == '/dev/null'
false
elsif fs_remote?(home_dir)
new_resource.manage_nfs_home_dirs ? true : false
else
true
end
end
end