Created
April 27, 2016 17:54
-
-
Save leoh0/3d2504b3a122e2e85e7029fc29a4b440 to your computer and use it in GitHub Desktop.
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
| #!/usr/env/bin/knife exec | |
| # | |
| # Based on: | |
| # - https://gist.github.com/mpasternacki/1952431 | |
| # | |
| abort("usage: knife exec #{ARGV[1]} from_id to_id") unless ARGV[3] | |
| require 'net/ssh' | |
| require 'net/scp' | |
| require 'chef/config' | |
| require 'chef/rest' | |
| from_id = ARGV[2] | |
| to_id = ARGV[3] | |
| puts "Loading node #{from_id}..." | |
| orig_node = Chef::Node.load(from_id) | |
| puts "Changing name attribute to #{to_id}..." | |
| orig_node.name(to_id) | |
| puts "Saving node #{to_id}..." | |
| orig_node.save | |
| puts "Create client #{to_id}..." | |
| client = Chef::ApiClient.new | |
| client.name(to_id) | |
| response = client.create | |
| File.open(to_id + ".pem", 'w') { |file| file.write(response['private_key']) } | |
| rest = Chef::ServerAPI.new(Chef::Config[:chef_server_url]) | |
| acl = rest.get_rest("nodes/#{to_id}/_acl") | |
| perms = 'create,delete,grant,read,update' | |
| perms.split(',').each do |perm| | |
| ace = acl[perm] | |
| next if ace['actors'].include?(to_id) | |
| ace['actors'] << to_id | |
| rest.put_rest("nodes/#{to_id}/_acl/#{perm}", perm => ace) | |
| puts "Put acl #{perm} => #{to_id}" | |
| end | |
| puts "Logging into node to #{to_id}..." | |
| Net::SSH.start(to_id, Chef::Config[:knife][:ssh_user]) do |ssh| | |
| puts "Uploading validation.pem..." | |
| ssh.scp.upload!(to_id + ".pem", "/etc/chef/client.pem") | |
| puts "Running update script..." | |
| ssh.exec! <<EOF do |ch, stream, data| | |
| set -e -x | |
| chef-client -N #{to_id} | |
| EOF | |
| if stream == :stderr | |
| STDERR.write data | |
| STDERR.flush | |
| else | |
| STDOUT.write data | |
| STDOUT.flush | |
| end | |
| end | |
| end | |
| unless ENV['KEEP_IT_SAFE'] | |
| puts "Deleting node #{from_id}..." | |
| orig_node2 = Chef::Node.load(from_id) | |
| orig_node2.destroy | |
| puts "Deleting client #{from_id}..." | |
| Chef::ApiClient.load(from_id).destroy | |
| end | |
| puts 'Done!' | |
| exit 0 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tested it chef-server 12.4.1.