#Ruby Basics for DevOps

Ruby is known for its elegant syntax and is the foundation of popular DevOps tools like Chef, Vagrant, and Puppet.

#📋 Table of Contents


#Why Ruby for DevOps?

#Tools Built with Ruby

ToolPurpose
ChefConfiguration management
PuppetInfrastructure automation
VagrantDevelopment environments
CapistranoDeployment automation
HomebrewmacOS package manager
MetasploitSecurity testing

#Setting Up Ruby

bash
1# Install rbenv (Ruby version manager)
2curl -fsSL https://github.com/rbenv/rbenv-installer/raw/main/bin/rbenv-installer | bash
3
4# Add to shell config
5echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
6echo 'eval "$(rbenv init -)"' >> ~/.bashrc
7source ~/.bashrc
8
9# Install Ruby
10rbenv install 3.2.0
11rbenv global 3.2.0
12
13# Verify
14ruby --version
15gem --version

#Ruby Basics

#Variables and Data Types

ruby
1# Strings
2server_name = "web-server-01"
3region = 'us-east-1'
4
5# Numbers
6port = 8080
7cpu_threshold = 80.5
8
9# Arrays
10servers = ["web-01", "web-02", "web-03"]
11
12# Hashes (dictionaries)
13server_config = {
14  name: "web-server-01",
15  ip: "10.0.1.100",
16  port: 8080,
17  enabled: true
18}
19
20# String interpolation
21puts "Server #{server_name} on port #{port}"
22
23# Symbols
24status = :healthy

#Control Flow

ruby
1# If statements
2cpu_usage = 85
3
4if cpu_usage > 90
5  puts "CRITICAL: High CPU!"
6elsif cpu_usage > 75
7  puts "WARNING: Elevated CPU"
8else
9  puts "OK: Normal CPU"
10end
11
12# Each loop
13servers.each do |server|
14  puts "Checking #{server}"
15end
16
17# Select (filter)
18healthy_servers = servers.select { |s| check_health(s) }
19
20# Map (transform)
21server_names = servers.map { |s| s.upcase }

#Methods (Functions)

ruby
1def check_server_health(hostname, port = 80)
2  require 'socket'
3  
4  begin
5    socket = TCPSocket.new(hostname, port)
6    socket.close
7    true
8  rescue
9    false
10  end
11end
12
13# Usage
14if check_server_health("google.com", 443)
15  puts "Server is healthy!"
16end

#Classes

ruby
1class Server
2  attr_accessor :name, :ip, :port, :healthy
3  
4  def initialize(name, ip, port = 80)
5    @name = name
6    @ip = ip
7    @port = port
8    @healthy = true
9  end
10  
11  def check_health
12    puts "Checking health of #{@name}..."
13    @healthy
14  end
15  
16  def restart
17    puts "Restarting #{@name}..."
18  end
19  
20  def to_s
21    "Server(#{@name}, #{@ip}:#{@port})"
22  end
23end
24
25# Usage
26server = Server.new("web-01", "10.0.1.100", 8080)
27puts server.check_health

#File Operations

ruby
1# Reading a file
2content = File.read("/etc/hosts")
3puts content
4
5# Reading line by line
6File.foreach("/var/log/syslog") do |line|
7  puts line if line.downcase.include?("error")
8end
9
10# Writing to a file
11File.write("/tmp/config.txt", "key=value\n")
12
13# Working with YAML
14require 'yaml'
15
16# Read YAML
17config = YAML.load_file("config.yaml")
18puts config["database"]["host"]
19
20# Write YAML
21data = { servers: ["web-01", "web-02"], count: 2 }
22File.write("output.yaml", data.to_yaml)
23
24# Working with JSON
25require 'json'
26
27# Read JSON
28json_data = JSON.parse(File.read("data.json"))
29
30# Write JSON
31File.write("output.json", JSON.pretty_generate(data))

#Working with APIs

ruby
1require 'net/http'
2require 'json'
3require 'uri'
4
5# GET request
6def fetch_user(username)
7  uri = URI("https://api.github.com/users/#{username}")
8  response = Net::HTTP.get_response(uri)
9  
10  if response.is_a?(Net::HTTPSuccess)
11    JSON.parse(response.body)
12  else
13    nil
14  end
15end
16
17user = fetch_user("octocat")
18puts "Name: #{user['name']}"
19puts "Repos: #{user['public_repos']}"
20
21# POST request with headers
22def create_server(name, region)
23  uri = URI("https://api.example.com/servers")
24  http = Net::HTTP.new(uri.host, uri.port)
25  http.use_ssl = true
26  
27  request = Net::HTTP::Post.new(uri)
28  request["Authorization"] = "Bearer #{ENV['API_TOKEN']}"
29  request["Content-Type"] = "application/json"
30  request.body = { name: name, region: region }.to_json
31  
32  response = http.request(request)
33  JSON.parse(response.body)
34end

#DevOps Tools in Ruby

#Chef Example

ruby
1# Recipe: webserver.rb
2package 'nginx' do
3  action :install
4end
5
6service 'nginx' do
7  action [:enable, :start]
8end
9
10template '/etc/nginx/nginx.conf' do
11  source 'nginx.conf.erb'
12  notifies :restart, 'service[nginx]'
13end

#Vagrant Example

ruby
1# Vagrantfile
2Vagrant.configure("2") do |config|
3  config.vm.box = "ubuntu/focal64"
4  
5  config.vm.network "private_network", ip: "192.168.33.10"
6  
7  config.vm.provider "virtualbox" do |vb|
8    vb.memory = "2048"
9    vb.cpus = 2
10  end
11  
12  config.vm.provision "shell", inline: <<-SHELL
13    apt-get update
14    apt-get install -y docker.io
15  SHELL
16end

#Summary

ConceptKey Points
SetupUse rbenv for version management
SyntaxClean, readable, blocks
FilesBuilt-in File class, YAML/JSON
APIsNet::HTTP for requests
ToolsChef, Puppet, Vagrant

[!TIP] Pro Tip: Ruby's strength is in readable DSLs (Domain Specific Languages) like Chef recipes and Vagrantfiles!