diff --git a/Batali b/Batali index 2e8ac02..2268d4f 100644 --- a/Batali +++ b/Batali @@ -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', diff --git a/batali.manifest b/batali.manifest index b6dcb72..44e7752 100644 --- a/batali.manifest +++ b/batali.manifest @@ -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" } }, { diff --git a/cookbooks/sudo/CHANGELOG.md b/cookbooks/sudo/CHANGELOG.md index 7283d9f..7ae8ead 100644 --- a/cookbooks/sudo/CHANGELOG.md +++ b/cookbooks/sudo/CHANGELOG.md @@ -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 diff --git a/cookbooks/sudo/README.md b/cookbooks/sudo/README.md index a78f833..e93af1e 100644 --- a/cookbooks/sudo/README.md +++ b/cookbooks/sudo/README.md @@ -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 + @@ -321,42 +319,8 @@ case it is not already **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)) diff --git a/cookbooks/sudo/files/default/README b/cookbooks/sudo/files/README similarity index 100% rename from cookbooks/sudo/files/default/README rename to cookbooks/sudo/files/README diff --git a/cookbooks/sudo/metadata.json b/cookbooks/sudo/metadata.json index f1afd08..f96d2e8 100644 --- a/cookbooks/sudo/metadata.json +++ b/cookbooks/sudo/metadata.json @@ -1 +1 @@ -{"name":"sudo","version":"3.3.1","description":"Installs sudo and configures /etc/sudoers","long_description":"# sudo cookbook\n\n[![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)\n\nThe Chef `sudo` cookbook installs the `sudo` package and configures the `/etc/sudoers` file.\n\nIt also exposes an LWRP for adding and managing sudoers.\n\n## Requirements\n\n### Platforms\n\n- Debian/Ubuntu\n- RHEL/CentOS/Scientific/Amazon/Oracle\n- FreeBSD\n- Mac OS X\n- openSUSE / Suse\n\n### Chef\n\n- Chef 12.1+\n\n### Cookbooks\n\n- None\n\n## Attributes\n- `node['authorization']['sudo']['groups']` - groups to enable sudo access (default: `[ \"sysadmin\" ]`)\n- `node['authorization']['sudo']['users']` - users to enable sudo access (default: `[]`)\n- `node['authorization']['sudo']['passwordless']` - use passwordless sudo (default: `false`)\n- `node['authorization']['sudo']['include_sudoers_d']` - include and manage `/etc/sudoers.d` (default: `false`)\n- `node['authorization']['sudo']['agent_forwarding']` - preserve `SSH_AUTH_SOCK` when sudoing (default: `false`)\n- `node['authorization']['sudo']['sudoers_defaults']` - Array of `Defaults` entries to configure in `/etc/sudoers`\n- `node['authorization']['sudo']['setenv']` - Whether to permit preserving of environment with `sudo -E` (default: `false`)\n\n## Usage\n### Attributes\nTo use attributes for defining sudoers, set the attributes above on the node (or role) itself:\n\n```json\n{\n \"default_attributes\": {\n \"authorization\": {\n \"sudo\": {\n \"groups\": [\"admin\", \"wheel\", \"sysadmin\"],\n \"users\": [\"jerry\", \"greg\"],\n \"passwordless\": \"true\"\n }\n }\n }\n}\n```\n\n```json\n{\n \"default_attributes\": {\n \"authorization\": {\n \"sudo\": {\n \"command_aliases\": [{\n \"name\": \"TEST\",\n \"command_list\": [\n \"/usr/bin/ls\",\n \"/usr/bin/cat\"\n ]\n }],\n \"custom_commands\": {\n \"users\": [\n {\n \"user\": \"test_user\",\n \"passwordless\": true,\n \"command_list\": [\n \"TEST\"\n ]\n }\n ],\n \"groups\": [\n {\n \"group\": \"test_group\",\n \"passwordless\": false,\n \"command_list\": [\n \"TEST\"\n ]\n }\n ]\n }\n }\n }\n }\n}\n```\n\n```ruby\n# roles/example.rb\ndefault_attributes(\n \"authorization\" => {\n \"sudo\" => {\n \"groups\" => [\"admin\", \"wheel\", \"sysadmin\"],\n \"users\" => [\"jerry\", \"greg\"],\n \"passwordless\" => true\n }\n }\n)\n```\n\n**Note that the template for the sudoers file has the group \"sysadmin\" with ALL:ALL permission, though the group by default does not exist.**\n\n### Sudoers Defaults\nConfigure 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:\n\n_Debian_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = ['env_reset']\n```\n\n_Ubuntu 10.04_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = ['env_reset']\n```\n\n_Ubuntu 12.04_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"'\n]\n```\n\n_FreeBSD_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"'\n]\n```\n\n_RHEL family 5.x_ The version of sudo in RHEL 5 may not support `+=`, as used in `env_keep`, so its a single string.\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n '!visiblepw',\n 'env_reset',\n 'env_keep = \"COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR \\\n LS_COLORS MAIL PS1 PS2 QTDIR USERNAME \\\n LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION \\\n LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC \\\n LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS \\\n _XKB_CHARSET XAUTHORITY\"'\n]\n```\n\n_RHEL family 6.x_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n '!visiblepw',\n 'env_reset',\n 'env_keep = \"COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS\"',\n 'env_keep += \"MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE\"',\n 'env_keep += \"LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES\"',\n 'env_keep += \"LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE\"',\n 'env_keep += \"LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY\"',\n 'env_keep += \"HOME\"',\n 'always_set_home',\n 'secure_path = /sbin:/bin:/usr/sbin:/usr/bin'\n]\n```\n\n_Mac OS X_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'env_keep += \"BLOCKSIZE\"',\n 'env_keep += \"COLORFGBG COLORTERM\"',\n 'env_keep += \"__CF_USER_TEXT_ENCODING\"',\n 'env_keep += \"CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE\"',\n 'env_keep += \"LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME\"',\n 'env_keep += \"LINES COLUMNS\"',\n 'env_keep += \"LSCOLORS\"',\n 'env_keep += \"TZ\"',\n 'env_keep += \"DISPLAY XAUTHORIZATION XAUTHORITY\"',\n 'env_keep += \"EDITOR VISUAL\"',\n 'env_keep += \"HOME MAIL\"'\n]\n```\n\n### LWRP\n**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`.\n\nThere are two ways for rendering a sudoer-fragment using this LWRP:\n1. Using the built-in template\n2. Using a custom, cookbook-level template\n\nBoth methods will create the `/etc/sudoers.d/#{resourcename}` file with the correct permissions.\n\nThe LWRP also performs **fragment validation**. If a sudoer-fragment is not valid, the Chef run will throw an exception and fail. This ensures that your sudoers file is always valid and cannot become corrupt (from this cookbook).\n\nExample using the built-in template:\n\n```ruby\nsudo 'tomcat' do\n user \"%tomcat\" # or a username\n runas 'app_user' # or 'app_user:tomcat'\n commands ['/etc/init.d/tomcat restart']\nend\n```\n\n```ruby\nsudo 'tomcat' do\n template 'my_tomcat.erb' # local cookbook template\n variables :cmds => ['/etc/init.d/tomcat restart']\nend\n```\n\nIn either case, the following file would be generated in `/etc/sudoers.d/tomcat`\n\n```bash\n# This file is managed by Chef for node.example.com\n# Do NOT modify this file directly.\n\n%tomcat ALL=(app_user) /etc/init.d/tomcat restart\n```\n\n#### LWRP Attributes\n
\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AttributeDescriptionExampleDefault
namename of the `/etc/sudoers.d` filerestart-tomcatcurrent resource name
commandsarray of commands this sudoer can execute['/etc/init.d/tomcat restart']['ALL']
groupgroup to provide sudo privileges to, except `%` is prepended to the name in\ncase it is not already%admin
nopasswdsupply a password to invoke sudotruefalse
noexecprevents commands from shelling outtruefalse
runasUser the command(s) can be run asrootALL
templatethe erb template to render instead of the defaultrestart-tomcat.erb
useruser to provide sudo privileges totomcat
defaultsarray of defaults this user has['!requiretty','env_reset']
setenvwhether to permit the preserving of environment with `sudo -E`true
env_keep_addarray of strings to add to env_keep['HOME', 'MY_ENV_VAR MY_OTHER_ENV_VAR']
env_keep_subtractarray of strings to remove from env_keep['DISPLAY', 'MY_SECURE_ENV_VAR']
variablesthe variables to pass to the custom template:commands => ['/etc/init.d/tomcat restart']
\n\n**If you use the template attribute, all other attributes will be ignored except for the variables attribute.**\n\n## Development\nThis section details \"quick development\" steps. For a detailed explanation, see [[Contributing.md]].\n- Clone this repository from GitHub:\n\n ```\n $ git clone git@github.com:chef-cookbooks/sudo.git\n ```\n\n- Create a git branch\n\n ```\n $ git checkout -b my_bug_fix\n ```\n\n- Install dependencies:\n\n ```\n $ bundle install\n ```\n\n- Make your changes/patches/fixes, committing appropiately\n- **Write tests**\n- Run the tests:\n - `bundle exec foodcritic -f any .`\n - `bundle exec rspec`\n - `bundle exec rubocop`\n - `bundle exec kitchen test`\n\n In detail:\n\n - Foodcritic will catch any Chef-specific style errors\n - RSpec will run the unit tests\n - Rubocop will check for Ruby-specific style errors\n - Test Kitchen will run and converge the recipes\n\n## License & Authors\n**Author:** Bryan W. Berry [bryan.berry@gmail.com](mailto:bryan.berry@gmail.com)\n\n**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))\n\n**Copyright:** 2008-2016, Chef Software, Inc.\n\n```\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","maintainer":"Chef Software, Inc.","maintainer_email":"cookbooks@chef.io","license":"Apache 2.0","platforms":{"redhat":">= 0.0.0","centos":">= 0.0.0","fedora":">= 0.0.0","ubuntu":">= 0.0.0","debian":">= 0.0.0","freebsd":">= 0.0.0","mac_os_x":">= 0.0.0","oracle":">= 0.0.0","scientific":">= 0.0.0","zlinux":">= 0.0.0","suse":">= 0.0.0","opensuse":">= 0.0.0","opensuseleap":">= 0.0.0"},"dependencies":{},"recommendations":{},"suggestions":{},"conflicting":{},"providing":{},"replacing":{},"attributes":{},"groupings":{},"recipes":{"sudo":"Installs sudo and configures /etc/sudoers"}} \ No newline at end of file +{"name":"sudo","version":"3.4.0","description":"Installs sudo and configures /etc/sudoers","long_description":"# sudo cookbook\n\n[![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)\n\nThe 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.\n\n## Requirements\n\n### Platforms\n\n- Debian/Ubuntu\n- RHEL/CentOS/Scientific/Amazon/Oracle\n- FreeBSD\n- Mac OS X\n- openSUSE / Suse\n\n### Chef\n\n- Chef 12.1+\n\n### Cookbooks\n\n- None\n\n## Attributes\n\n- `node['authorization']['sudo']['groups']` - groups to enable sudo access (default: `[ \"sysadmin\" ]`)\n- `node['authorization']['sudo']['users']` - users to enable sudo access (default: `[]`)\n- `node['authorization']['sudo']['passwordless']` - use passwordless sudo (default: `false`)\n- `node['authorization']['sudo']['include_sudoers_d']` - include and manage `/etc/sudoers.d` (default: `false`)\n- `node['authorization']['sudo']['agent_forwarding']` - preserve `SSH_AUTH_SOCK` when sudoing (default: `false`)\n- `node['authorization']['sudo']['sudoers_defaults']` - Array of `Defaults` entries to configure in `/etc/sudoers`\n- `node['authorization']['sudo']['setenv']` - Whether to permit preserving of environment with `sudo -E` (default: `false`)\n\n## Usage\n\n### Attributes\n\nTo use attributes for defining sudoers, set the attributes above on the node (or role) itself:\n\n```json\n{\n \"default_attributes\": {\n \"authorization\": {\n \"sudo\": {\n \"groups\": [\"admin\", \"wheel\", \"sysadmin\"],\n \"users\": [\"jerry\", \"greg\"],\n \"passwordless\": \"true\"\n }\n }\n }\n}\n```\n\n```json\n{\n \"default_attributes\": {\n \"authorization\": {\n \"sudo\": {\n \"command_aliases\": [{\n \"name\": \"TEST\",\n \"command_list\": [\n \"/usr/bin/ls\",\n \"/usr/bin/cat\"\n ]\n }],\n \"custom_commands\": {\n \"users\": [\n {\n \"user\": \"test_user\",\n \"passwordless\": true,\n \"command_list\": [\n \"TEST\"\n ]\n }\n ],\n \"groups\": [\n {\n \"group\": \"test_group\",\n \"passwordless\": false,\n \"command_list\": [\n \"TEST\"\n ]\n }\n ]\n }\n }\n }\n }\n}\n```\n\n```ruby\n# roles/example.rb\ndefault_attributes(\n \"authorization\" => {\n \"sudo\" => {\n \"groups\" => [\"admin\", \"wheel\", \"sysadmin\"],\n \"users\" => [\"jerry\", \"greg\"],\n \"passwordless\" => true\n }\n }\n)\n```\n\n**Note that the template for the sudoers file has the group \"sysadmin\" with ALL:ALL permission, though the group by default does not exist.**\n\n### Sudoers Defaults\n\nConfigure 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:\n\n_Debian_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = ['env_reset']\n```\n\n_Ubuntu 12.04_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"'\n]\n```\n\n_FreeBSD_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"'\n]\n```\n\n_RHEL family 5.x_ The version of sudo in RHEL 5 may not support `+=`, as used in `env_keep`, so its a single string.\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n '!visiblepw',\n 'env_reset',\n 'env_keep = \"COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR \\\n LS_COLORS MAIL PS1 PS2 QTDIR USERNAME \\\n LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION \\\n LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC \\\n LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS \\\n _XKB_CHARSET XAUTHORITY\"'\n]\n```\n\n_RHEL family 6.x_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n '!visiblepw',\n 'env_reset',\n 'env_keep = \"COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS\"',\n 'env_keep += \"MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE\"',\n 'env_keep += \"LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES\"',\n 'env_keep += \"LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE\"',\n 'env_keep += \"LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY\"',\n 'env_keep += \"HOME\"',\n 'always_set_home',\n 'secure_path = /sbin:/bin:/usr/sbin:/usr/bin'\n]\n```\n\n_Mac OS X_\n\n```ruby\nnode.default['authorization']['sudo']['sudoers_defaults'] = [\n 'env_reset',\n 'env_keep += \"BLOCKSIZE\"',\n 'env_keep += \"COLORFGBG COLORTERM\"',\n 'env_keep += \"__CF_USER_TEXT_ENCODING\"',\n 'env_keep += \"CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE\"',\n 'env_keep += \"LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME\"',\n 'env_keep += \"LINES COLUMNS\"',\n 'env_keep += \"LSCOLORS\"',\n 'env_keep += \"TZ\"',\n 'env_keep += \"DISPLAY XAUTHORIZATION XAUTHORITY\"',\n 'env_keep += \"EDITOR VISUAL\"',\n 'env_keep += \"HOME MAIL\"'\n]\n```\n\n### Sudo Resource\n\n**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`.\n\nThere are two ways for rendering a sudoer-fragment using this LWRP:\n1. Using the built-in template\n2. Using a custom, cookbook-level template\n\nBoth methods will create the `/etc/sudoers.d/#{resourcename}` file with the correct permissions.\n\nThe LWRP also performs **fragment validation**. If a sudoer-fragment is not valid, the Chef run will throw an exception and fail. This ensures that your sudoers file is always valid and cannot become corrupt (from this cookbook).\n\nExample using the built-in template:\n\n```ruby\nsudo 'tomcat' do\n user \"%tomcat\" # or a username\n runas 'app_user' # or 'app_user:tomcat'\n commands ['/etc/init.d/tomcat restart']\nend\n```\n\n```ruby\nsudo 'tomcat' do\n template 'my_tomcat.erb' # local cookbook template\n variables :cmds => ['/etc/init.d/tomcat restart']\nend\n```\n\nIn either case, the following file would be generated in `/etc/sudoers.d/tomcat`\n\n```bash\n# This file is managed by Chef for node.example.com\n# Do NOT modify this file directly.\n\n%tomcat ALL=(app_user) /etc/init.d/tomcat restart\n```\n\n#### Resource Properties\n\n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AttributeDescriptionExampleDefault
namename of the `/etc/sudoers.d` filerestart-tomcatcurrent resource name
commandsarray of commands this sudoer can execute['/etc/init.d/tomcat restart']['ALL']
groupgroup to provide sudo privileges to, except `%` is prepended to the name in\ncase it is not already%admin
nopasswdsupply a password to invoke sudotruefalse
noexecprevents commands from shelling outtruefalse
runasUser the command(s) can be run asrootALL
templatethe erb template to render instead of the defaultrestart-tomcat.erb
useruser to provide sudo privileges totomcat
defaultsarray of defaults this user has['!requiretty','env_reset']
setenvwhether to permit the preserving of environment with `sudo -E`true
env_keep_addarray of strings to add to env_keep['HOME', 'MY_ENV_VAR MY_OTHER_ENV_VAR']
env_keep_subtractarray of strings to remove from env_keep['DISPLAY', 'MY_SECURE_ENV_VAR']
variablesthe variables to pass to the custom template:commands => ['/etc/init.d/tomcat restart']
\n\n**If you use the template attribute, all other attributes will be ignored except for the variables attribute.**\n\n## License & Authors\n\n**Author:** Bryan W. Berry [bryan.berry@gmail.com](mailto:bryan.berry@gmail.com)\n\n**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))\n\n**Copyright:** 2008-2016, Chef Software, Inc.\n\n```\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","maintainer":"Chef Software, Inc.","maintainer_email":"cookbooks@chef.io","license":"Apache-2.0","platforms":{"redhat":">= 0.0.0","centos":">= 0.0.0","fedora":">= 0.0.0","ubuntu":">= 0.0.0","debian":">= 0.0.0","freebsd":">= 0.0.0","mac_os_x":">= 0.0.0","oracle":">= 0.0.0","scientific":">= 0.0.0","zlinux":">= 0.0.0","suse":">= 0.0.0","opensuse":">= 0.0.0","opensuseleap":">= 0.0.0"},"dependencies":{},"recommendations":{},"suggestions":{},"conflicting":{},"providing":{},"replacing":{},"attributes":{},"groupings":{},"recipes":{"sudo":"Installs sudo and configures /etc/sudoers"},"source_url":"https://github.com/chef-cookbooks/sudo","issues_url":"https://github.com/chef-cookbooks/sudo/issues","chef_version":[[">= 12.1"]],"ohai_version":[]} \ No newline at end of file diff --git a/cookbooks/sudo/providers/default.rb b/cookbooks/sudo/providers/default.rb index e8f524a..4b6a16f 100644 --- a/cookbooks/sudo/providers/default.rb +++ b/cookbooks/sudo/providers/default.rb @@ -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' diff --git a/cookbooks/sudo/recipes/default.rb b/cookbooks/sudo/recipes/default.rb index 249afd1..ed109bc 100644 --- a/cookbooks/sudo/recipes/default.rb +++ b/cookbooks/sudo/recipes/default.rb @@ -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'] diff --git a/cookbooks/sudo/templates/default/sudoer.erb b/cookbooks/sudo/templates/default/sudoer.erb index 02c9898..6d2cdfb 100644 --- a/cookbooks/sudo/templates/default/sudoer.erb +++ b/cookbooks/sudo/templates/default/sudoer.erb @@ -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? %> diff --git a/cookbooks/users/.foodcritic b/cookbooks/users/.foodcritic deleted file mode 100644 index 698ef4c..0000000 --- a/cookbooks/users/.foodcritic +++ /dev/null @@ -1 +0,0 @@ -~FC003 diff --git a/cookbooks/users/CHANGELOG.md b/cookbooks/users/CHANGELOG.md index ecde6bd..8e6eae3 100644 --- a/cookbooks/users/CHANGELOG.md +++ b/cookbooks/users/CHANGELOG.md @@ -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. +- @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 - 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 +- 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 diff --git a/cookbooks/users/README.md b/cookbooks/users/README.md index 73979f1..e85cc66 100644 --- a/cookbooks/users/README.md +++ b/cookbooks/users/README.md @@ -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"); diff --git a/cookbooks/users/libraries/helpers.rb b/cookbooks/users/libraries/helpers.rb index e0a358b..bf7b37e 100644 --- a/cookbooks/users/libraries/helpers.rb +++ b/cookbooks/users/libraries/helpers.rb @@ -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) diff --git a/cookbooks/users/libraries/osx_helper.rb b/cookbooks/users/libraries/osx_helper.rb new file mode 100644 index 0000000..d195e76 --- /dev/null +++ b/cookbooks/users/libraries/osx_helper.rb @@ -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 diff --git a/cookbooks/users/metadata.json b/cookbooks/users/metadata.json index 260994b..789307a 100644 --- a/cookbooks/users/metadata.json +++ b/cookbooks/users/metadata.json @@ -1 +1 @@ -{"name":"users","version":"4.0.3","description":"Creates users from a databag search","long_description":"# users Cookbook\n\n[![Build Status](https://travis-ci.org/chef-cookbooks/users.svg?branch=master)](http://travis-ci.org/chef-cookbooks/users) [![Cookbook Version](https://img.shields.io/cookbook/v/users.svg)](https://supermarket.chef.io/cookbooks/users)\n\nManages OS users from databags.\n\n## Scope\n\nThis cookbook is concerned with the management of OS users and groups from databags. It also manages the distribution of ssh keys to a user's home directory.\n\n## Requirements\n\nA data bag populated with user objects must exist. The default data bag in this recipe is `users`. See USAGE.\n\n### Chef\n\n- Chef 12.1+\n\n### Platform Support\n\nThe following platforms have been tested with Test Kitchen:\n\n- Debian / Ubuntu and derivatives\n- RHEL and derivatives\n- Fedora\n- FreeBSD / OpenBSD\n- Mac OS X\n\n### Cookbook Dependencies\n\n- none\n\n## Usage\n\nTo use the resource `users_manage`, make sure to add the dependency on the users cookbook by the following line to your wrapper cookbook's [metadata.rb](https://docs.chef.io/config_rb_metadata.html):\n\n```\ndepends 'users'\n```\n\nor to pin to a specific version of the users cookbook, in this case any version of 2.X:\n\n```\ndepends 'users', '~> 2'\n```\n\nThen in a recipe:\n\n```ruby\nusers_manage 'GROUPNAME' do\n group_id GROUPID\n action [:create]\n data_bag 'DATABAG_NAME'\nend\n```\n\nExample:\n\n```ruby\nusers_manage 'testgroup' do\n group_id 3000\n action [:create]\n data_bag 'test_home_dir'\nend\n```\n\n**Note**: If you do not specify the data_bag, the default will be to look for a databag called users.\n\n## Databag Definition\n\nA sample user object in a users databag would look like:\n\n```json\n{\n \"id\": \"test_user\",\n \"password\": \"$1$5cE1rI/9$4p0fomh9U4kAI23qUlZVv/\",\n \"ssh_keys\": [\n \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\\nNrRFi9wrf+M7Q== chefuser@mylaptop.local\",\n \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\\nNQCPO0ZZEa1== chefuser@mylaptop.local\"\n ],\n \"groups\": [ \"testgroup\", \"nfsgroup\" ],\n \"uid\": 9001,\n \"shell\": \"\\/bin\\/bash\",\n \"comment\": \"Test User\"\n}\n```\n\n### Databag Key Definitions\n\n- `id`: _String_ specifies the username, as well as the data bag object id.\n- `password`: _String_ specifies the user's password.\n- `ssh_keys`: _Array_ an array of authorized keys that will be managed by Chef to the user's home directory in .ssh/authorized_keys\n- `groups`: _Array_ an array of groups that the user will be added to\n- `uid`: _Integer_ a unique identifier for the user\n- `shell`: _String_ the user's shell\n- `comment`:_String_ the [GECOS field](https://en.wikipedia.org/wiki/Gecos_field), generally the User's full name.\n\nOther potential fields:\n\n- `home`: _String_ User's home directory. If not assigned, will be set based on platform and username.\n- `action`: _String_ Supported actions are one's supported by the [user](https://docs.chef.io/resource_user.html#actions) resource. If not specified, the default action is `create`.\n- `ssh_private_key`: _String_ manages user's private key generally ~/.ssh/id_*\n- `ssh_public_key`: _String_ manages user's public key generally ~/.ssh/id_*.pub\n\n## Resources Overview\n\n### users_manage\n\nThe `users_manage` resource manages users and groups based off of a data bag search and specified action.\n\n#### Examples\n\nCreates the `sysadmin` group and users defined in the `users` databag.\n\n```ruby\nusers_manage 'sysadmin' do\n group_id 2300\n action [:create]\nend\n```\n\nCreates the `testgroup` group, and users defined in the `test_home_dir` databag.\n\n```ruby\nusers_manage 'testgroup' do\n group_id 3000\n action [:create]\n data_bag 'test_home_dir'\nend\n```\n\nCreates the `nfsgroup` group, and users defined in the `test_home_dir` databag and does not manage nfs home directories.\n\n```ruby\nusers_manage 'nfsgroup' do\n group_id 4000\n action [:create]\n data_bag 'test_home_dir'\n manage_nfs_home_dirs false\nend\n```\n\n#### Parameters\n\n- `data_bag` _String_ is the data bag to search\n- `search_group` _String_ groups name to search for, defaults to resource name\n- `group_name` _String_ name of the group to create, defaults to resource name\n- `group_id` _Integer_ numeric id of the group to create, default is to allow the OS to pick next\n- `cookbook` _String_ name of the cookbook that the authorized_keys template should be found in\n- `manage_nfs_home_dirs` _Boolean_ whether to manage nfs home directories.\n\nOtherwise, this cookbook is specific for setting up `sysadmin` group and users with the sysadmins recipe for now.\n\n## Recipe Overview\n\n### Deprecation Notice\n\nThis recipe has been deprecated and the resource will be removed from the recipe in a new major release of this cookbook in April 2017\\. The functionality can easily be recreated and changed to suit your organization by copying the single resource below into your own cookbook.\n\n`sysadmins.rb`: recipe that manages the group sysadmins with group id 2300, and adds users to this group.\n\nTo use:\n\n```ruby\ninclude_recipe \"users::sysadmins\"\n```\n\nThe recipe is defined as follows:\n\n```ruby\nusers_manage \"sysadmin\" do\n group_id 2300\n action [ :create ]\nend\n```\n\nThis `users_manage` resource searches the `users` data bag for the `sysadmin` group attribute, and adds those users to a Unix security group `sysadmin`. The only required attribute is group_id, which represents the numeric Unix gid and _must_ be unique. The default action for the resource is `:create`.\n\nThe recipe, by default, will also create the sysadmin group. The sysadmin group will be created with GID 2300.\n\n## Data bag Overview\n\n**Reminder** Data bags generally should not be stored in cookbooks, but in a policy repo within your organization. Data bags are useful across cookbooks, not just for a single cookbook.\n\nUse knife to create a data bag for users.\n\n```bash\n$ knife data bag create users\n```\n\nCreate a user in the data_bag/users/ directory.\n\nAn optional password hash can be specified that will be used as the user's password.\n\nThe hash can be generated with the following command.\n\n```bash\n$ openssl passwd -1 \"plaintextpassword\"\n```\n\nNote: The ssh_keys attribute below can be either a String or an Array. However, we are recommending the use of an Array.\n\n```json\n{\n \"id\": \"bofh\",\n \"ssh_keys\": \"ssh-rsa AAAAB3Nz...yhCw== bofh\"\n}\n```\n\n```json\n{\n \"id\": \"bofh\",\n \"password\": \"$1$d...HgH0\",\n \"ssh_keys\": [\n \"ssh-rsa AAA123...xyz== foo\",\n \"ssh-rsa AAA456...uvw== bar\"\n ],\n \"groups\": [ \"sysadmin\", \"dba\", \"devops\" ],\n \"uid\": 2001,\n \"shell\": \"\\/bin\\/bash\",\n \"comment\": \"BOFH\"\n}\n```\n\nYou can pass any action listed in the [user](http://docs.chef.io/chef/resources.html#user) resource for Chef via the \"action\" option. For Example:\n\nLock a user, johndoe1.\n\n```bash\n$ knife data bag edit users johndoe1\n```\n\nAnd then change the action to \"lock\":\n\n```javascript\n{\n \"id\": \"johndoe1\",\n \"groups\": [\"sysadmin\", \"dba\", \"devops\"],\n \"uid\": 2002,\n \"action\": \"lock\", // <--\n \"comment\": \"User violated access policy\"\n}\n```\n\nRemove a user, johndoe1.\n\n```bash\n$ knife data bag edit users johndoe1\n```\n\nAnd then change the action to \"remove\":\n\n```javascript\n{\n \"id\": \"johndoe1\",\n \"groups\": [ \"sysadmin\", \"dba\", \"devops\" ],\n \"uid\": 2002,\n \"action\": \"remove\", // <--\n \"comment\": \"User quit, retired, or fired.\"\n}\n```\n\n- Note only user bags with the \"action : remove\" and a search-able \"group\" attribute will be purged by the :remove action.\n- As of v2.0.3 you can use the force parameter within the user data bag object for users with action remove. As per [user docs](https://docs.chef.io/resource_user.html) this may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users.\n\nIf you have different requirements, for example:\n- You want to search a different data bag specific to a role such as\n- mail. You may change the data_bag searched.\n - data_bag `mail`\n\n- You want to search for a different group attribute named\n- `postmaster`. You may change the search_group attribute. This\n- attribute defaults to the LWRP resource name.\n - search_group `postmaster`\n\n- You want to add the users to a security group other than the\n- lightweight resource name. You may change the group_name attribute.\n- This attribute also defaults to the LWRP resource name.\n - group_name `wheel`\n\nPutting these requirements together our recipe might look like this:\n\n```ruby\nusers_manage \"postmaster\" do\n data_bag \"mail\"\n group_name \"wheel\"\n group_id 10\nend\n```\n\nKnife supports reading data bags from a file and automatically looks in a directory called +data_bags+ in the current directory. The \"bag\" should be a directory with JSON files of each item. For the above:\n\n```bash\n$ mkdir data_bags/users\n$EDITOR data_bags/users/bofh.json\n```\n\nPaste the user's public SSH key into the ssh_keys value. Also make sure the uid is unique, and if you're not using bash, that the shell is installed.\n\nThe Apache cookbook can set up authentication using OpenIDs, which is set up using the openid key here. See the Chef Software 'apache2' cookbook for more information about this.\n\n## License & Authors\n\n**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))\n\n**Copyright:** 2009-2016, Chef Software, Inc.\n\n```\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","maintainer":"Chef Software, Inc.","maintainer_email":"cookbooks@chef.io","license":"Apache 2.0","platforms":{"ubuntu":">= 0.0.0","debian":">= 0.0.0","redhat":">= 0.0.0","centos":">= 0.0.0","fedora":">= 0.0.0","freebsd":">= 0.0.0","mac_os_x":">= 0.0.0","scientific":">= 0.0.0","oracle":">= 0.0.0","amazon":">= 0.0.0","zlinux":">= 0.0.0"},"dependencies":{},"recommendations":{},"suggestions":{},"conflicting":{},"providing":{},"replacing":{},"attributes":{},"groupings":{},"recipes":{"users::default":"Empty recipe","users::sysadmins":"Deprecated recipe to create and manage sysadmin group."}} \ No newline at end of file +{"name":"users","version":"5.0.0","description":"Creates users from a databag search","long_description":"# users Cookbook\n\n[![Build Status](https://travis-ci.org/chef-cookbooks/users.svg?branch=master)](http://travis-ci.org/chef-cookbooks/users) [![Cookbook Version](https://img.shields.io/cookbook/v/users.svg)](https://supermarket.chef.io/cookbooks/users)\n\nManages OS users from databags.\n\n## Scope\n\nThis cookbook is concerned with the management of OS users and groups from databags. It also manages the distribution of ssh keys to a user's home directory.\n\n## Requirements\n\nA data bag populated with user objects must exist. The default data bag in this recipe is `users`. See USAGE.\n\n### Platforms\n\nThe following platforms have been tested with Test Kitchen:\n\n- Debian / Ubuntu derivatives\n- RHEL and derivatives\n- Fedora\n- openSUSE / SUSE Linux Enterprises\n- FreeBSD / OpenBSD\n- Mac OS X\n\n### Chef\n\n- Chef 12.5+\n\n### Cookbooks\n\n- none\n\n## Usage\n\nTo use the resource `users_manage`, make sure to add the dependency on the users cookbook by the following line to your wrapper cookbook's [metadata.rb](https://docs.chef.io/config_rb_metadata.html):\n\n```\ndepends 'users'\n```\n\nor to pin to a specific version of the users cookbook, in this case any version of 2.X:\n\n```\ndepends 'users', '~> 2'\n```\n\nThen in a recipe:\n\n```ruby\nusers_manage 'GROUPNAME' do\n group_id GROUPID\n action [:create]\n data_bag 'DATABAG_NAME'\nend\n```\n\nExample:\n\n```ruby\nusers_manage 'testgroup' do\n group_id 3000\n action [:create]\n data_bag 'test_home_dir'\nend\n```\n\n**Note**: If you do not specify the data_bag, the default will be to look for a databag called users.\n\n## Databag Definition\n\nA sample user object in a users databag would look like:\n\n```json\n{\n \"id\": \"test_user\",\n \"password\": \"$1$5cE1rI/9$4p0fomh9U4kAI23qUlZVv/\",\n \"ssh_keys\": [\n \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\\nNrRFi9wrf+M7Q== chefuser@mylaptop.local\",\n \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\\nNQCPO0ZZEa1== chefuser@mylaptop.local\"\n ],\n \"groups\": [ \"testgroup\", \"nfsgroup\" ],\n \"uid\": 9001,\n \"shell\": \"\\/bin\\/bash\",\n \"comment\": \"Test User\"\n}\n```\n\n### Databag Key Definitions\n\n- `id`: _String_ specifies the username, as well as the data bag object id.\n- `password`: _String_ specifies the user's password.\n- `ssh_keys`: _Array_ an array of authorized keys that will be managed by Chef to the user's home directory in .ssh/authorized_keys\n- `groups`: _Array_ an array of groups that the user will be added to\n- `uid`: _Integer_ a unique identifier for the user\n- `shell`: _String_ the user's shell\n- `comment`:_String_ the [GECOS field](https://en.wikipedia.org/wiki/Gecos_field), generally the User's full name.\n\nOther potential fields:\n\n- `home`: _String_ User's home directory. If not assigned, will be set based on platform and username.\n- `action`: _String_ Supported actions are one's supported by the [user](https://docs.chef.io/resource_user.html#actions) resource. If not specified, the default action is `create`.\n- `ssh_private_key`: _String_ manages user's private key generally ~/.ssh/id_*\n- `ssh_public_key`: _String_ manages user's public key generally ~/.ssh/id_*.pub\n\n## Resources Overview\n\n### users_manage\n\nThe `users_manage` resource manages users and groups based off of a data bag search and specified action.\n\n#### Examples\n\nCreates the `sysadmin` group and users defined in the `users` databag.\n\n```ruby\nusers_manage 'sysadmin' do\n group_id 2300\n action [:create]\nend\n```\n\nCreates the `testgroup` group, and users defined in the `test_home_dir` databag.\n\n```ruby\nusers_manage 'testgroup' do\n group_id 3000\n action [:create]\n data_bag 'test_home_dir'\nend\n```\n\nCreates the `nfsgroup` group, and users defined in the `test_home_dir` databag and does not manage nfs home directories.\n\n```ruby\nusers_manage 'nfsgroup' do\n group_id 4000\n action [:create]\n data_bag 'test_home_dir'\n manage_nfs_home_dirs false\nend\n```\n\n#### Parameters\n\n- `data_bag` _String_ is the data bag to search\n- `search_group` _String_ groups name to search for, defaults to resource name\n- `group_name` _String_ name of the group to create, defaults to resource name\n- `group_id` _Integer_ numeric id of the group to create, default is to allow the OS to pick next\n- `cookbook` _String_ name of the cookbook that the authorized_keys template should be found in\n- `manage_nfs_home_dirs` _Boolean_ whether to manage nfs home directories.\n\nOtherwise, this cookbook is specific for setting up `sysadmin` group and users with the sysadmins recipe for now.\n\n## Recipe Overview\n\n### Deprecation Notice\n\nThis recipe has been deprecated and the resource will be removed from the recipe in a new major release of this cookbook in April 2017\\. The functionality can easily be recreated and changed to suit your organization by copying the single resource below into your own cookbook.\n\n`sysadmins.rb`: recipe that manages the group sysadmins with group id 2300, and adds users to this group.\n\nTo use:\n\n```ruby\ninclude_recipe \"users::sysadmins\"\n```\n\nThe recipe is defined as follows:\n\n```ruby\nusers_manage \"sysadmin\" do\n group_id 2300\n action [ :create ]\nend\n```\n\nThis `users_manage` resource searches the `users` data bag for the `sysadmin` group attribute, and adds those users to a Unix security group `sysadmin`. The only required attribute is group_id, which represents the numeric Unix gid and _must_ be unique. The default action for the resource is `:create`.\n\nThe recipe, by default, will also create the sysadmin group. The sysadmin group will be created with GID 2300.\n\n## Data bag Overview\n\n**Reminder** Data bags generally should not be stored in cookbooks, but in a policy repo within your organization. Data bags are useful across cookbooks, not just for a single cookbook.\n\nUse knife to create a data bag for users.\n\n```bash\n$ knife data bag create users\n```\n\nCreate a user in the data_bag/users/ directory.\n\nAn optional password hash can be specified that will be used as the user's password.\n\nThe hash can be generated with the following command.\n\n```bash\n$ openssl passwd -1 \"plaintextpassword\"\n```\n\nNote: The ssh_keys attribute below can be either a String or an Array. However, we are recommending the use of an Array.\n\n```json\n{\n \"id\": \"bofh\",\n \"ssh_keys\": \"ssh-rsa AAAAB3Nz...yhCw== bofh\"\n}\n```\n\n```json\n{\n \"id\": \"bofh\",\n \"password\": \"$1$d...HgH0\",\n \"ssh_keys\": [\n \"ssh-rsa AAA123...xyz== foo\",\n \"ssh-rsa AAA456...uvw== bar\"\n ],\n \"groups\": [ \"sysadmin\", \"dba\", \"devops\" ],\n \"uid\": 2001,\n \"shell\": \"\\/bin\\/bash\",\n \"comment\": \"BOFH\"\n}\n```\n\nYou can pass any action listed in the [user](http://docs.chef.io/chef/resources.html#user) resource for Chef via the \"action\" option. For Example:\n\nLock a user, johndoe1.\n\n```bash\n$ knife data bag edit users johndoe1\n```\n\nAnd then change the action to \"lock\":\n\n```javascript\n{\n \"id\": \"johndoe1\",\n \"groups\": [\"sysadmin\", \"dba\", \"devops\"],\n \"uid\": 2002,\n \"action\": \"lock\", // <--\n \"comment\": \"User violated access policy\"\n}\n```\n\nRemove a user, johndoe1.\n\n```bash\n$ knife data bag edit users johndoe1\n```\n\nAnd then change the action to \"remove\":\n\n```javascript\n{\n \"id\": \"johndoe1\",\n \"groups\": [ \"sysadmin\", \"dba\", \"devops\" ],\n \"uid\": 2002,\n \"action\": \"remove\", // <--\n \"comment\": \"User quit, retired, or fired.\"\n}\n```\n\n- Note only user bags with the \"action : remove\" and a search-able \"group\" attribute will be purged by the :remove action.\n- As of v2.0.3 you can use the force parameter within the user data bag object for users with action remove. As per [user docs](https://docs.chef.io/resource_user.html) this may leave the system in an inconsistent state. For example, a user account will be removed even if the user is logged in. A user’s home directory will be removed, even if that directory is shared by multiple users.\n\nIf you have different requirements, for example:\n- You want to search a different data bag specific to a role such as\n- mail. You may change the data_bag searched.\n - data_bag `mail`\n\n- You want to search for a different group attribute named\n- `postmaster`. You may change the search_group attribute. This\n- attribute defaults to the LWRP resource name.\n - search_group `postmaster`\n\n- You want to add the users to a security group other than the\n- lightweight resource name. You may change the group_name attribute.\n- This attribute also defaults to the LWRP resource name.\n - group_name `wheel`\n\nPutting these requirements together our recipe might look like this:\n\n```ruby\nusers_manage \"postmaster\" do\n data_bag \"mail\"\n group_name \"wheel\"\n group_id 10\nend\n```\n\nKnife supports reading data bags from a file and automatically looks in a directory called +data_bags+ in the current directory. The \"bag\" should be a directory with JSON files of each item. For the above:\n\n```bash\n$ mkdir data_bags/users\n$EDITOR data_bags/users/bofh.json\n```\n\nPaste the user's public SSH key into the ssh_keys value. Also make sure the uid is unique, and if you're not using bash, that the shell is installed.\n\nThe Apache cookbook can set up authentication using OpenIDs, which is set up using the openid key here. See the Chef Software 'apache2' cookbook for more information about this.\n\n## License & Authors\n\n**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))\n\n**Copyright:** 2009-2017, Chef Software, Inc.\n\n```\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n","maintainer":"Chef Software, Inc.","maintainer_email":"cookbooks@chef.io","license":"Apache-2.0","platforms":{"ubuntu":">= 0.0.0","debian":">= 0.0.0","redhat":">= 0.0.0","centos":">= 0.0.0","fedora":">= 0.0.0","freebsd":">= 0.0.0","mac_os_x":">= 0.0.0","scientific":">= 0.0.0","oracle":">= 0.0.0","amazon":">= 0.0.0","zlinux":">= 0.0.0","suse":">= 0.0.0","opensuse":">= 0.0.0","opensuseleap":">= 0.0.0"},"dependencies":{},"recommendations":{},"suggestions":{},"conflicting":{},"providing":{},"replacing":{},"attributes":{},"groupings":{},"recipes":{},"source_url":"https://github.com/chef-cookbooks/users","issues_url":"https://github.com/chef-cookbooks/users/issues","chef_version":[[">= 12.5"]],"ohai_version":[]} \ No newline at end of file diff --git a/cookbooks/users/providers/manage.rb b/cookbooks/users/providers/manage.rb deleted file mode 100644 index 83a018c..0000000 --- a/cookbooks/users/providers/manage.rb +++ /dev/null @@ -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 diff --git a/cookbooks/users/recipes/default.rb b/cookbooks/users/recipes/default.rb index 59e688c..317ccf7 100644 --- a/cookbooks/users/recipes/default.rb +++ b/cookbooks/users/recipes/default.rb @@ -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. diff --git a/cookbooks/users/recipes/sysadmins.rb b/cookbooks/users/recipes/sysadmins.rb index 03f248a..85ba4e7 100644 --- a/cookbooks/users/recipes/sysadmins.rb +++ b/cookbooks/users/recipes/sysadmins.rb @@ -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.') diff --git a/cookbooks/users/resources/manage.rb b/cookbooks/users/resources/manage.rb index 69e1378..5361920 100644 --- a/cookbooks/users/resources/manage.rb +++ b/cookbooks/users/resources/manage.rb @@ -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 diff --git a/cookbooks/users/templates/default/authorized_keys.erb b/cookbooks/users/templates/authorized_keys.erb similarity index 100% rename from cookbooks/users/templates/default/authorized_keys.erb rename to cookbooks/users/templates/authorized_keys.erb diff --git a/cookbooks/users/templates/default/private_key.erb b/cookbooks/users/templates/private_key.erb similarity index 100% rename from cookbooks/users/templates/default/private_key.erb rename to cookbooks/users/templates/private_key.erb diff --git a/cookbooks/users/templates/default/public_key.pub.erb b/cookbooks/users/templates/public_key.pub.erb similarity index 100% rename from cookbooks/users/templates/default/public_key.pub.erb rename to cookbooks/users/templates/public_key.pub.erb