Last active
March 12, 2023 06:08
-
-
Save sizovs/a96cc58f714b4103939182b02ece6040 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
require 'droplet_kit' | |
DO_API_TOKEN = 'YOUR_DO_API_TOKEN_HERE' | |
client = DropletKit::Client.new(access_token: DO_API_TOKEN) | |
# Auto scaling configuration | |
auto_scaling_config = { | |
droplet_size: 's-1vcpu-1gb', | |
max_instances: 5, | |
min_instances: 1, | |
cpu_threshold: 80, | |
lb_name: 'my-load-balancer' | |
} | |
# Get the number of instances in the auto scaling group | |
def get_instance_count | |
client.droplets.all(tag_name: 'autoscaling').count | |
end | |
# Create a new droplet | |
def create_droplet | |
droplet = DropletKit::Droplet.new( | |
name: "autoscale-#{Time.now.to_i}", | |
region: 'nyc3', | |
size: auto_scaling_config[:droplet_size], | |
image: 'ubuntu-20-04-x64', | |
tags: ['autoscaling'] | |
) | |
client.droplets.create(droplet) | |
end | |
# Destroy a droplet by ID | |
def destroy_droplet(droplet_id) | |
client.droplets.delete(id: droplet_id) | |
end | |
# Add a droplet to the load balancer | |
def add_to_load_balancer(droplet_id) | |
lb = client.load_balancers.all.find { |l| l.name == auto_scaling_config[:lb_name] } | |
if lb | |
lb_droplets = lb.droplets + [DropletKit::LoadBalancer::Droplet.new(id: droplet_id)] | |
lb = lb.to_h.merge(droplets: lb_droplets) | |
client.load_balancers.update(lb) | |
end | |
end | |
# Remove a droplet from the load balancer | |
def remove_from_load_balancer(droplet_id) | |
lb = client.load_balancers.all.find { |l| l.name == auto_scaling_config[:lb_name] } | |
if lb | |
lb_droplets = lb.droplets.reject { |d| d.id == droplet_id } | |
lb = lb.to_h.merge(droplets: lb_droplets) | |
client.load_balancers.update(lb) | |
end | |
end | |
# Get the CPU usage of the server | |
# /v2/monitoring/metrics/droplet/cpu. | |
def get_cpu_usage | |
end | |
# Main loop | |
while true do | |
cpu_usage = get_cpu_usage | |
instance_count = get_instance_count | |
if cpu_usage > auto_scaling_config[:cpu_threshold] && instance_count < auto_scaling_config[:max_instances] | |
# Create a new droplet | |
droplet = create_droplet | |
add_to_load_balancer(droplet.id) | |
elsif cpu_usage < auto_scaling_config[:cpu_threshold] / 2 && instance_count > auto_scaling_config[:min_instances] | |
# Destroy the oldest droplet | |
oldest_droplet = client.droplets.all(tag_name: 'autoscaling').sort_by { |d| d.created_at }.first | |
destroy_droplet(oldest_droplet.id) if oldest_droplet | |
remove_from_load_balancer(oldest_droplet.id) | |
end | |
# Sleep for 1 minute | |
sleep(60) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment