Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created March 16, 2023 04:15
Show Gist options
  • Save mahemoff/7e436211bfb7bdafe6b41488606b967a to your computer and use it in GitHub Desktop.
Save mahemoff/7e436211bfb7bdafe6b41488606b967a to your computer and use it in GitHub Desktop.
ChqatGPT v4 server monitoring

write ruby code using digitalocean api to reboot a droplet

To reboot a droplet using the DigitalOcean API, you'll first need to install the droplet_kit gem, which is the official DigitalOcean API client for Ruby. You can install the gem by adding the following line to your Gemfile and running bundle install:

ruby Copy code gem 'droplet_kit' After installing the gem, you can create a Ruby script to reboot a droplet using the DigitalOcean API. Replace YOUR_DIGITALOCEAN_API_TOKEN with your actual API token and DROPLET_ID with the ID of the droplet you want to reboot.

ruby Copy code require 'droplet_kit'

Replace with your DigitalOcean API token

api_token = 'YOUR_DIGITALOCEAN_API_TOKEN'

Initialize the DigitalOcean API client

client = DropletKit::Client.new(access_token: api_token)

Replace with the ID of the droplet you want to reboot

droplet_id = 'DROPLET_ID'

Reboot the droplet

client.droplet_actions.reboot(droplet_id: droplet_id)

puts "Rebooting droplet with ID: #{droplet_id}" Save this code in a file named reboot_droplet.rb and run it using ruby reboot_droplet.rb. This will reboot the specified droplet using the DigitalOcean API.

how could you run this on AWS Lambda every 10 minutes

To run this Ruby script on AWS Lambda every 10 minutes, you need to follow these steps:

Create a Lambda function Set up an Amazon EventBridge (formerly CloudWatch Events) rule to trigger the Lambda function every 10 minutes Package and deploy the Ruby script and dependencies to Lambda Here's a step-by-step guide:

Step 1: Create a Lambda function

Sign in to the AWS Management Console and navigate to the Lambda service. Click on "Create function". Select "Author from scratch". Name your function (e.g., "RebootDroplet"), and choose the Ruby runtime (e.g., Ruby 2.7). Under "Function code", choose "Upload a .zip file" as the "Code entry type". We will package and upload the code later. For the execution role, create a new role with basic Lambda permissions. Click on "Create function". Step 2: Set up an Amazon EventBridge rule

Navigate to the Amazon EventBridge service in the AWS Management Console. Click on "Create rule". Name your rule (e.g., "RebootDropletRule"), and optionally provide a description. Under "Define pattern", select "Schedule". Choose "Fixed rate of" and set the rate to "10" minutes. Under "Select targets", choose the "Lambda function" option and select your "RebootDroplet" function from the dropdown. Click on "Create". Step 3: Package and deploy the Ruby script and dependencies to Lambda

On your local machine, create a folder (e.g., reboot_droplet_lambda). Inside the folder, create a file named Gemfile with the following content: ruby Copy code source 'https://rubygems.org'

gem 'aws-sdk-lambda' gem 'droplet_kit' Run bundle install --path vendor/bundle to install the gems locally in the vendor/bundle folder. Create a file named lambda_function.rb with the following content: ruby Copy code require 'droplet_kit' require 'json'

def lambda_handler(event:, context:)

Replace with your DigitalOcean API token

api_token = 'YOUR_DIGITALOCEAN_API_TOKEN'

Initialize the DigitalOcean API client

client = DropletKit::Client.new(access_token: api_token)

Replace with the ID of the droplet you want to reboot

droplet_id = 'DROPLET_ID'

Reboot the droplet

client.droplet_actions.reboot(droplet_id: droplet_id)

{ statusCode: 200, body: JSON.generate('Rebooting droplet with ID: #{droplet_id}') } end Zip the contents of the reboot_droplet_lambda folder. Make sure to include the vendor folder, Gemfile, Gemfile.lock, and lambda_function.rb at the root level of the zip archive. Upload the zip file to your Lambda function in the AWS Management Console. You can do this by selecting the "RebootDroplet" Lambda function, clicking on "Function code", and uploading the zip file under "Code entry type". Update the "Handler" setting in the "Runtime settings" section to lambda_function.lambda_handler. Click on "Save" to save the changes. Now, your Lambda function will automatically run every 10 minutes, rebooting the specified DigitalOcean droplet.


I want to make it so the server reboots only if the server did not respond twice ie at two consecutive 10-minute runs To reboot the server only if it did not respond twice in two consecutive 10-minute runs, you can modify your Lambda function to check for server availability and maintain a counter using Amazon DynamoDB.

First, create a DynamoDB table to store the counter:

Sign in to the AWS Management Console and navigate to the DynamoDB service. Click on "Create table". Name your table (e.g., "DropletStatus") and set the primary key to "droplet_id" with a type of "String". Click on "Create". Now, update your Lambda function code and grant it permissions to access the DynamoDB table:

Add the aws-sdk-dynamodb gem to your Gemfile: ruby Copy code source 'https://rubygems.org'

gem 'aws-sdk-lambda' gem 'aws-sdk-dynamodb' gem 'droplet_kit' Run bundle install --path vendor/bundle to install the new gem. Update your lambda_function.rb with the following code: ruby Copy code require 'droplet_kit' require 'aws-sdk-dynamodb' require 'json' require 'net/http'

def check_server_availability(server_url) uri = URI(server_url) http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = 5 http.open_timeout = 5

request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request)

response.code == '200' rescue false end

def update_droplet_status(dynamodb, droplet_id, available) table_name = 'DropletStatus'

if available dynamodb.delete_item(table_name: table_name, key: { droplet_id: droplet_id }) else item = dynamodb.get_item(table_name: table_name, key: { droplet_id: droplet_id }).item counter = item ? item['counter'].to_i : 0 counter += 1

if counter >= 2
  dynamodb.delete_item(table_name: table_name, key: { droplet_id: droplet_id })
  return true
else
  dynamodb.put_item(table_name: table_name, item: { droplet_id: droplet_id, counter: counter })
end

end

false end

def lambda_handler(event:, context:)

Replace with your DigitalOcean API token

api_token = 'YOUR_DIGITALOCEAN_API_TOKEN'

Replace with the ID of the droplet you want to reboot

droplet_id = 'DROPLET_ID'

Replace with the URL of your server for health checking

server_url = 'http://example.com'

Initialize the DigitalOcean API client

client = DropletKit::Client.new(access_token: api_token)

Initialize the AWS DynamoDB client

dynamodb = Aws::DynamoDB::Client.new

Check server availability

available = check_server_availability(server_url)

Update the droplet status in DynamoDB

reboot_required = update_droplet_status(dynamodb, droplet_id, available)

Reboot the droplet if it didn't respond in the last two runs

if reboot_required client.droplet_actions.reboot(droplet_id: droplet_id) { statusCode: 200, body: JSON.generate("Rebooting droplet with ID: #{droplet_id}") } else { statusCode: 200, body: JSON.generate("Droplet with ID: #{droplet_id} is running fine") }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment