Skip to content

Instantly share code, notes, and snippets.

@harmy
Last active January 28, 2019 05:26
Show Gist options
  • Save harmy/664ea0a1b06677586cc2fec44130648c to your computer and use it in GitHub Desktop.
Save harmy/664ea0a1b06677586cc2fec44130648c to your computer and use it in GitHub Desktop.
update haproxy configuration and reload it dymamiclly
*/3 * * * * sudo ruby /usr/bin/haproxy-autoscaling-update.rb
# /usr/bin/haproxy-autoscaling-update.rb
require 'aws-sdk'
# We use instance profile credentials to authenticate
# using the role attached to the instance
region = "us-east-1"
auto_scaling_group = "AutoScaleGrp-xfrps-prod-001-20190116090909593800000005"
credentials = Aws::InstanceProfileCredentials.new
Aws.config.update(credentials: credentials)
Aws.config.update(region: region)
autoscaling = Aws::AutoScaling::Client.new(region: region)
ec2 = Aws::EC2::Client.new(region: region)
# Retrieve current autoscaling group instances
response = autoscaling.describe_auto_scaling_groups(auto_scaling_group_names: [auto_scaling_group])
instances = response.auto_scaling_groups.first.instances
hosts = []
instances.each do |instance|
if instance.lifecycle_state == "InService"
# We cannot access the private IP address of the
# instance using Autoscaling API, so we have to
# retrieve the instance object from the EC2 API.
ec2_instance = ec2.describe_instances(instance_ids: [instance.instance_id]).reservations.first.instances.first
if ec2_instance.state.name == "running"
hosts << {ip: ec2_instance.private_ip_address, public_name: ec2_instance.public_dns_name}
end
end
end
# Copy template config to the config file
# and append hosts to backend configuration
FileUtils.cp("/etc/haproxy/haproxy.cfg.template", "/etc/haproxy/haproxy.cfg")
open("/etc/haproxy/haproxy.cfg", "a") do |f|
f << "frontend xfrps\n\tbind *:7000\n\tmode tcp\n\toption tcplog\n\tdefault_backend xfrps\n\tmaxconn 10000000\n"
f << "backend xfrps\n\tbalance source\n\tmode tcp\n"
hosts.each do |host|
f << "\tserver #{host[:public_name]} #{host[:ip]}:7000 check send-proxy\n"
end
f << "frontend xfrps_api\n\tbind *:80\n\tdefault_backend xfrps_api\n"
f << "backend xfrps_api\n\tbalance roundrobin\n"
hosts.each do |host|
f << "\tserver #{host[:public_name]} #{host[:ip]}:7001 check\n"
end
end
if !File.exist?("/etc/haproxy/haproxy.cfg.old") || !FileUtils.identical?("/etc/haproxy/haproxy.cfg.old", "/etc/haproxy/haproxy.cfg")
FileUtils.cp("/etc/haproxy/haproxy.cfg", "/etc/haproxy/haproxy.cfg.old")
# Reload HAProxy with system command
stdout = `service haproxy reload`
puts " -> reloaded HAProxy: #{stdout}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment