Friday, October 23, 2015

YAML Loader - Ruby

Sample YAML Loader:


Assume your yaml file 'email_credential.yml' exists in same directory and in the format below:

email:
  smtp_server: smtp.gmail.com
  smtp_port: 587


Here is the simple snippet to load YAML and collect data:

begin
  yml = YAML.load_file("email_credentials.yml")
  
  email = yml['email']['smtp_server']
  eport = yml['email']['smtp_port']
  
rescue Exception => e
  puts "Email credential YAML loading issue \n" + e.to_s
end

Website Monitor - Ruby Script

Simple Ruby Script file to check the web site and post an email using gmail service.

This script contains 2 main parts

  1. Checking website - for response OK and content
  2. Email to admin on failure [using gmail]

Checking Website:

    url = URI.parse(web_url)
  net_conn = Net::HTTP.new(url.host, url.port)
  net_conn.use_ssl = url.scheme == "https"
  res = net_conn.get('/')

   We can check res.code == 200 and verify res.body includes the content we wanted to see.

Email [Using gmail]

  NOTE: Gmail needs TLS encryption; so enable it before start sending msg
   
    smtp = Net::SMTP.new("smtp.gmail.com", 587)
    smtp.enable_starttls #gmail needs this encryption
    smtp.start("DOMAIN_FILLER", <gmail_acc>, <gmail_pwd>, :logindo |s| 
      s.send_message(<msg>, <gmail_acc>, <to>)
    end  

  Sample GMAIL Msg format:
   msg = [
    "From: WebMonitor <from_addr>",
    "To: Admin <to_addr>",
    "Subject: <subject>",
    "",
    "Hi,",
    "!!MORE DETAILED MSG!!"
  ].join("\r\n");


Gist: https://gist.github.com/sivajankan/8278d75c39bc5a8260ae

The script can be added to crontab to do automated testing