Skip to content

Instantly share code, notes, and snippets.

@bdwyertech
Created October 30, 2015 22:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdwyertech/df3d5ef2bdb4ef642642 to your computer and use it in GitHub Desktop.
Save bdwyertech/df3d5ef2bdb4ef642642 to your computer and use it in GitHub Desktop.
DigitalOcean Metadata Query - Ruby
# DigitalOcean Metadata Chef Library
# rubocop:disable LineLength
require 'net/http'
# Public: This defines a module to retrieve Metadata from DigitalOcean
module DoMetadata
DO_METADATA_ADDR = '169.254.169.254' unless defined?(DO_METADATA_ADDR)
DO_SUPPORTED_VERSIONS = %w( v1 )
DO_DEFAULT_API_VERSION = 'v1'
def self.http_client
Net::HTTP.start(DO_METADATA_ADDR).tap { |h| h.read_timeout = 600 }
end
# Get metadata for a given path and API version
def metadata_get(id, api_version = DO_DEFAULT_API_VERSION, json = false)
path = "/metadata/#{api_version}/#{id}"
path = "/metadata/#{api_version}.json" if json
response = http_client.get(path)
case response.code
when '200'
response.body
when '404'
Chef::Log.info("Encountered 404 response retreiving DO metadata path: #{path} ; continuing.")
nil
else
fail "Encountered error retrieving DO metadata (#{path} returned #{response.code} response)"
end
end
module_function :metadata_get
# Retrieve the JSON metadata, and return it as a Ruby hash
def parse_json_metadata(api_version = DO_DEFAULT_API_VERSION)
retrieved_metadata = metadata_get(nil, api_version, true)
return unless retrieved_metadata
JSON.parse(retrieved_metadata) if retrieved_metadata
end
module_function :parse_json_metadata
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment