Last active
August 29, 2015 14:06
-
-
Save nathwill/e931f03c9360ba445946 to your computer and use it in GitHub Desktop.
chef user monkey patch for github ssh keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'chef/resource/directory' | |
require 'chef/resource/file' | |
require 'chef/resource/remote_file' | |
require 'chef/resource/user' | |
require 'chef/provider/user' | |
class Chef | |
class Resource::TreehouseUser < Chef::Resource::User | |
def github_users(arg = nil) | |
set_or_return( | |
:github_users, arg, | |
:kind_of => [String, Array], | |
) | |
end | |
end | |
end | |
class Chef | |
class Provider::User | |
alias_method :orig_action_create, :action_create | |
def action_create | |
orig_action_create | |
if new_resource.respond_to?(:github_users) && new_resource.github_users | |
create_ssh_dir | |
write_authorized_keys(ssh_keys) | |
end | |
end | |
private | |
def create_ssh_dir | |
dir = Chef::Resource::Directory.new(ssh_dir, run_context) | |
dir.owner new_resource.username | |
dir.group new_resource.username | |
dir.mode 0700 | |
dir.run_action(:create) | |
new_resource.updated_by_last_action(true) if dir.updated_by_last_action? | |
end | |
def ssh_keys | |
Array(new_resource.github_users).map do |gh_user| | |
path = ::File.join(Chef::Config[:file_cache_path], "#{gh_user}.keys") | |
cached = Chef::Resource::RemoteFile.new("#{gh_user}_keys", run_context) | |
cached.source("https://github.com/#{gh_user}.keys") | |
cached.path(path) | |
cached.run_action(:create) | |
::File.read(path).split("\n").map { |k| "#{k} #{gh_user}"} | |
end | |
end | |
def write_authorized_keys(auth_keys = []) | |
f = Chef::Resource::File.new(::File.join(ssh_dir, 'authorized_keys'), run_context) | |
f.content auth_keys.join("\n") | |
f.owner new_resource.username | |
f.group new_resource.username | |
f.mode 0600 | |
f.run_action(:create) | |
new_resource.updated_by_last_action(true) if f.updated_by_last_action? | |
end | |
def ssh_dir | |
::File.join(Dir.home(new_resource.username), '.ssh') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment