client_management/lib/tasks/change_site_server_name.rake

36 lines
1.4 KiB
Ruby
Raw Normal View History

2021-02-17 16:59:11 +00:00
require 'net/ssh'
require 'pathname'
namespace :create_site do
desc "Change Site Server Name"
task :change_site_server_name,[:id,:server_name] => :environment do |task,args|
begin
site_construct = SiteConstruct.find(args.id)
site_server = site_construct.site_server
if !site_server.nil?
@password = site_server.password
Net::SSH.start(site_server.ip , site_server.account , password: site_server.password) do |ssh|
2021-02-18 01:46:55 +00:00
nginx_file_content = exec_command_by_user(ssh,"cat #{site_construct.nginx_file}")
2021-02-19 09:21:08 +00:00
nginx_file_content = nginx_file_content.gsub(/^[ \t]*server_name[ \t]+.*;/," server_name #{args.server_name};")
2021-02-17 16:59:11 +00:00
puts nginx_file_content
2021-02-19 09:20:13 +00:00
cmd = "x='#{nginx_file_content}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{site_construct.nginx_file}\""
exec_command_by_user(ssh,cmd)
2021-02-17 16:59:11 +00:00
exec_ssh_command_by_sudo(ssh,"service nginx restart")
end
2021-03-03 04:18:42 +00:00
site_construct.update(:domain_name=>args.server_name)
2021-02-17 16:59:11 +00:00
end
rescue => e
puts [e,e.backtrace]
end
end
2021-02-18 01:46:55 +00:00
def exec_command_by_user(session,command)
output = session.exec!(command)
2021-03-06 10:48:14 +00:00
return output[0...-1].gsub(/^\n[\n]+/,'')
2021-02-18 01:46:55 +00:00
end
2021-02-17 16:59:11 +00:00
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