Cloudwatch - Build an alarm using fog

Building a cloudwatch alarm using the ruby gem fog took me a while to figure out. It wasn't as clear cut as other fog methods. Below you'll see how to create the metric and then build the alarm for that metric.

require 'fog'
connection = => access_key, :aws_secret_access_key => secret_key, :region => "us-east-1")
result = connection.put_metric_data("AWS/EC2", ["MetricName"=>"my_custom_metric", "Value"=>1.0, "Unit"=>"Count"])

if result.status != 200
  puts "Failed creating metric"

#You'll need to wait a very long time if this is a new metric
waiting = nil

while waiting.nil?
  sleep 10
  connection.metrics #this reload's the metrics available from the API
  waiting = connection.metrics.get("AWS/EC2","my_custom_metric")

#Now let's create the alarm
alarm_config = {}"AlarmName","custom_metric_alarm")"AlarmActions",[])"MetricName","my_custom_metric")"Namespace","AWS/EC2")"AlarmDescription","Notifies me when custom metric is too high")"Statistic","Average")"Unit",nil)"ComparisonOperator","GreaterThanOrEqualToThreshold") #check Amazon docs for others"Period",300) #seconds"EvaluationPeriods",1)"Threshold",10.0)"Dimensions",[])
result = connection.put_metric_alarm(alarm_config)

if result.status != 200
  puts "Alarm creation failed"

#You can get the alarm like this
my_alarm = cs.alarms.get("custom_metric_alarm")

You'll notice "AWS/EC2" in many of the above methods, this is the namespace Amazon needs to have to place it in the proper location. There are many namespaces and you can also create custom namespaces. Like "ApplicationName:server_stats"

Also, I didn't put an example above, but when creating an Alarm you can specify an Action for it to take. "AlarmActions" is an array of strings that point to an ARN for an autoscaling group policy or email.