Permalink
Browse files

add method for accessing EC2 instance metadata

  • Loading branch information...
1 parent 0589211 commit 645b9e3d596c84b04de0663b4f26fc4decc2ad06 @aristidb committed Dec 13, 2012
Showing with 36 additions and 0 deletions.
  1. +34 −0 Aws/Ec2/InstanceMetadata.hs
  2. +1 −0 aws.cabal
  3. +1 −0 ghci.hs
@@ -0,0 +1,34 @@
+module Aws.Ec2.InstanceMetadata where
+
+import Control.Applicative
+import Control.Exception
+import Control.Failure
+import Control.Monad.Trans.Resource
+import Data.ByteString.Lazy (ByteString)
+import qualified Data.ByteString.Lazy.Char8 as B8
+import Data.ByteString.Lazy.UTF8 as BU
+import Data.Typeable
+import qualified Network.HTTP.Conduit as HTTP
+
+data InstanceMetadataException
+ = MetadataNotFound String
+ deriving (Show, Typeable)
+
+instance Exception InstanceMetadataException
+
+getInstanceMetadata :: HTTP.Manager -> String -> String -> ResIO ByteString
+getInstanceMetadata mgr p x = do req <- HTTP.parseUrl ("http://169.254.169.254/" ++ p ++ '/' : x)
+ HTTP.responseBody <$> HTTP.httpLbs req mgr
+
+getInstanceMetadataListing :: HTTP.Manager -> String -> ResIO [String]
+getInstanceMetadataListing mgr p = map BU.toString . B8.split '\n' <$> getInstanceMetadata mgr p ""
+
+getInstanceMetadataFirst :: HTTP.Manager -> String -> ResIO ByteString
+getInstanceMetadataFirst mgr p = do listing <- getInstanceMetadataListing mgr p
+ case listing of
+ [] -> failure (MetadataNotFound p)
+ (x:_) -> getInstanceMetadata mgr p x
+
+getInstanceMetadataOrFirst :: HTTP.Manager -> String -> Maybe String -> ResIO ByteString
+getInstanceMetadataOrFirst mgr p (Just x) = getInstanceMetadata mgr p x
+getInstanceMetadataOrFirst mgr p Nothing = getInstanceMetadataFirst mgr p
View
@@ -35,6 +35,7 @@ Library
Aws,
Aws.Aws,
Aws.Core,
+ Aws.Ec2.InstanceMetadata,
Aws.S3,
Aws.S3.Commands,
Aws.S3.Commands.CopyObject,
View
@@ -1,6 +1,7 @@
-- GHCI convenience code
import Aws
+import Aws.Ec2.InstanceMetadata
import qualified Aws.S3 as S3
import qualified Aws.Ses as Ses
import qualified Aws.SimpleDb as Sdb

0 comments on commit 645b9e3

Please sign in to comment.