58 lines
2.8 KiB
Ruby
58 lines
2.8 KiB
Ruby
require 'net/ssh'
|
|
require 'pathname'
|
|
require 'json'
|
|
namespace :create_site do
|
|
desc "Change Site Cert"
|
|
task :change_site_cert,[:id] => :environment do |task,args|
|
|
begin
|
|
@site_construct = SiteConstruct.find(args.id)
|
|
@site_cert = @site_construct.site_cert
|
|
site_server = @site_construct.site_server
|
|
@site_construct.update(:infos=>[],:status=>"changing")
|
|
if !site_server.nil? && !@site_cert.nil?
|
|
@password = site_server.password
|
|
Net::SSH.start(site_server.ip , site_server.account , password: site_server.password) do |ssh|
|
|
update_infos("Copying Cert to #{@site_construct.server_type}...")
|
|
cert_file_content = [(@site_cert.cert_file.file.read.strip rescue ""),(@site_cert.ca_bundle.file.read.strip rescue "")].join("\n").strip
|
|
private_key_content = @site_cert.private_key.file.read
|
|
cert_file_store_path = @site_construct.cert_file_remote_store_path
|
|
exec_ssh_command_by_sudo(ssh,"mkdir -p #{File.dirname(cert_file_store_path)}")
|
|
exec_command_by_user(ssh,"x='#{cert_file_content}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{cert_file_store_path}\"")
|
|
private_key_store_path = @site_construct.private_key_remote_store_path
|
|
exec_ssh_command_by_sudo(ssh,"mkdir -p #{File.dirname(private_key_store_path)}")
|
|
exec_command_by_user(ssh,"x='#{private_key_content}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{private_key_store_path}\"")
|
|
update_infos("Finish copy.")
|
|
update_infos("Setting Cert...")
|
|
nginx_file_content = exec_command_by_user(ssh,"cat #{@site_construct.nginx_file}")
|
|
all_ports = (@site_construct.port + ["443"]).uniq
|
|
@site_construct.update(:port=> all_ports )
|
|
nginx_file_content = @site_construct.generate_nginx_text(nginx_file_content)
|
|
cmd = "x='#{nginx_file_content}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{@site_construct.nginx_file}\""
|
|
exec_command_by_user(ssh,cmd)
|
|
puts nginx_file_content
|
|
exec_ssh_command_by_sudo(ssh,"service nginx restart")
|
|
update_infos("Finish!")
|
|
@site_construct.update(:status=>"finish")
|
|
end
|
|
else
|
|
update_infos("Cert not found!")
|
|
@site_construct.update(:status=>"error")
|
|
end
|
|
rescue => e
|
|
puts [e,e.backtrace]
|
|
update_infos(e.to_s)
|
|
@site_construct.update(:status=>"error")
|
|
end
|
|
end
|
|
def exec_command_by_user(session,command)
|
|
output = session.exec!(command)
|
|
return output[0...-1].gsub(/^\n[\n]+/,'')
|
|
end
|
|
def exec_ssh_command_by_sudo(session,command)
|
|
output = session.exec!("echo '#{@password}' | sudo -S #{command}")
|
|
if output.include?("sudo:") && output.include?("command not found")
|
|
output = session.exec!(command)
|
|
end
|
|
return output
|
|
end
|
|
end |