Img_9_lg

Amazon インタフェースメソッド

このページは Amazon Web Services へのインタフェースに対するメソッドの説明です。



Perl メソッド

Net::Amazon:: EC2 を使用した EC2 インスタンスの問い合わせ

下記のPerl コードは、Amazon のインスタンスとそのアトリビュートをリストします。
use Net::Amazon::EC2;
my $accesskey = "accesskey";    # Get this from your Amazon account

my $secretkey = "secretkey";
my $ec2 = Net::Amazon::EC2->new(

    AWSAccessKeyId => $accesskey,
    SecretAccessKey => $secretkey
     );
my $running_instances = $ec2->describe_instances();

foreach my $reservation (@$running_instances) {
    foreach my $instance ($reservation->instances_set) {

        print "Instance ".$instance->{'instance_id'}."\n";
        print "Status is ".$instance->{'instance_state'}->{'name'}."\n";

        print "AMI-id is ".$instance->{'image_id'}."\n";
        print "publicDNS is ".$instance->{'dns_name'}."\n";

                print "privateDNS is ".$instance->{'private_dns_name'}."\n";
        print "instance_type is ".$instance->{'instance_type'}."\n";

        print "launch_time is ".$instance->{'launch_time'}."\n";
        print "availability_zone is ".$instance->{'placement'}->{'availability_zone'}."\n";

        }
}
 

Amazon CloudWatch メトリックスの取得

下記の Perl コードのサンプルは、CloudWatch の統計を取得するため、Amazon に問い合わせします。
このコードは、下記の URL の Amazon EC2 の Perl ライブラリからのサンプルを修正したものです:
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1671

set_cloudwatch ルーチンは CloudWatch 機能を有効にします。 CloudWatch を有効にすると、AWS 課金が増えることにご注意ください。
 use Amazon::EC2::Client;
 use Amazon::EC2::Model::MonitorInstancesRequest;

 use Amazon::EC2::Model::UnmonitorInstancesRequest;
 
 my $accesskey = "accesskey"; # Get this from your Amazon account

 my $secretkey = "secretkey";
 my @inst_cw_enable = (); # Array of instance IDs to enable CloudWatch

 my @inst_cw_disable= (); # Array of instance IDs to disable CloudWatch
 set_cloudwatch($accesskey,$secretkey,\@inst_cw_enable,\@inst_cw_disable);

 
 sub set_cloudwatch {
      my $accesskey = shift;
      my $secretkey = shift;

      my $enableinstancesarray = shift;
      my $disableinstancesarray = shift;

      my $service = Amazon::EC2::Client->new($accesskey, $secretkey);

      if (scalar(@$enableinstancesarray) > 0) {
           my $request = Amazon::EC2::Model::MonitorInstancesRequest->new();

           $request->setInstanceId($enableinstancesarray);
           invokeMonitorInstances($service, $request);
      }

      if (scalar(@$disableinstancesarray) > 0) {
           my $request = Amazon::EC2::Model::UnmonitorInstancesRequest->new();

           $request->setInstanceId($disableinstancesarray);
           invokeUnmonitorInstances($service, $request);
      }

      return
 }
 
sub invokeMonitorInstances {
    my ($service, $request) = @_;

    eval {
              my $response = $service->monitorInstances($request);

              if ($debug) {
                print ("Service Response\n");
                print ("=============================================================================\n");

                print("        MonitorInstancesResponse\n");
                if ($response->isSetResponseMetadata()) {
                    print("            ResponseMetadata\n");

                    my $responseMetadata = $response->getResponseMetadata();
                    if ($responseMetadata->isSetRequestId())

                    {
                        print("                RequestId\n");
                        print("                    " . $responseMetadata->getRequestId() . "\n");

                    }
                }
                if ($response->isSetMonitorInstancesResult()) {
                    print("            MonitorInstancesResult\n");

                    my $monitorInstancesResult = $response->getMonitorInstancesResult();
                    my $instanceMonitoringList = $monitorInstancesResult->getInstanceMonitoring();

                    foreach (@$instanceMonitoringList) {
                        my $instanceMonitoring = $_;
                        print("                InstanceMonitoring\n");

                        if ($instanceMonitoring->isSetInstanceId())
                        {
                            print("                    InstanceId\n");
                            print("                        " . $instanceMonitoring->getInstanceId() . "\n");

                        }
                        if ($instanceMonitoring->isSetMonitoring()) {
                            print("                    Monitoring\n");

                            my $monitoring = $instanceMonitoring->getMonitoring();
                            if ($monitoring->isSetMonitoringState())

                            {
                                print("                        MonitoringState\n");
                                print("                            " . $monitoring->getMonitoringState() . "\n");

                            }
                        }
                    }
                }
              } # End debug
    };
    my $ex = $@;

    if ($ex) {
        require Amazon::EC2::Exception;
        if (ref $ex eq "Amazon::EC2::Exception") {

            print("Caught Exception: " . $ex->getMessage() . "\n");
            print("Response Status Code: " . $ex->getStatusCode() . "\n");

            print("Error Code: " . $ex->getErrorCode() . "\n");
            print("Error Type: " . $ex->getErrorType() . "\n");

            print("Request ID: " . $ex->getRequestId() . "\n");
            print("XML: " . $ex->getXML() . "\n");

        } else {
            croak $@;
        }
    }
}
 
  sub invokeUnmonitorInstances {

      my ($service, $request) = @_;
      eval {

              my $response = $service->unmonitorInstances($request);
              if ($debug) {

                print ("Service Response\n");
                print ("=============================================================================\n");
 
                print("        UnmonitorInstancesResponse\n");

                if ($response->isSetResponseMetadata()) {
                    print("            ResponseMetadata\n");
                    my $responseMetadata = $response->getResponseMetadata();

                    if ($responseMetadata->isSetRequestId())
                    {
                        print("                RequestId\n");
                        print("                    " . $responseMetadata->getRequestId() . "\n");

                    }
                }
                if ($response->isSetUnmonitorInstancesResult()) {
                    print("            UnmonitorInstancesResult\n");

                    my $unmonitorInstancesResult = $response->getUnmonitorInstancesResult();
                    my $instanceMonitoringList = $unmonitorInstancesResult->getInstanceMonitoring();

                    foreach (@$instanceMonitoringList) {
                        my $instanceMonitoring = $_;
                        print("                InstanceMonitoring\n");

                        if ($instanceMonitoring->isSetInstanceId())
                        {
                            print("                    InstanceId\n");
                            print("                        " . $instanceMonitoring->getInstanceId() . "\n");

                        }
                        if ($instanceMonitoring->isSetMonitoring()) {
                            print("                    Monitoring\n");

                            my $monitoring = $instanceMonitoring->getMonitoring();
                            if ($monitoring->isSetMonitoringState())

                            {
                                print("                        MonitoringState\n");
                                print("                            " . $monitoring->getMonitoringState() . "\n");

                            }
                        }
                    }
                }
              }  # End debug
 
     };
    my $ex = $@;

    if ($ex) {
        require Amazon::EC2::Exception;
        if (ref $ex eq "Amazon::EC2::Exception") {

            print("Caught Exception: " . $ex->getMessage() . "\n");
            print("Response Status Code: " . $ex->getStatusCode() . "\n");

            print("Error Code: " . $ex->getErrorCode() . "\n");
            print("Error Type: " . $ex->getErrorType() . "\n");

            print("Request ID: " . $ex->getRequestId() . "\n");
            print("XML: " . $ex->getXML() . "\n");

        } else {
            croak $@;
        }
    }
 }


get_instance_metrics は、有効にされた CloudWatch 計測値を取得します。

use Digest::SHA qw (hmac_sha1_base64 hmac_sha256_base64);

use XML::Simple;
use LWP::UserAgent;
use URI;

use URI::Escape;
 
 my $accesskey = "accesskey"; # Get this from your Amazon account

 my $secretkey = "secretkey";
 get_instance_metrics($instanceid,$accesskey,$secretkey);   # Get the metrics for this $instanceid

 
 sub get_instance_metrics {
        my $instanceid = shift;
    my $AWS_ACCESS_KEY_ID = shift;

    my $AWS_SECRET_ACCESS_KEY = shift;
    my @metrics = qw(CPUUtilization NetworkIn NetworkOut DiskWriteOps DiskReadBytes DiskReadOps DiskWriteBytes);

    foreach my $metric (@metrics) {
        my $parameters1 = undef;

        $parameters1->{"Action"}="GetMetricStatistics";
        $parameters1->{"AWSAccessKeyId"}=$AWS_ACCESS_KEY_ID;
        $parameters1->{"SignatureVersion"}="2";

        $parameters1->{"SignatureMethod"}="HmacSHA1";
        $parameters1->{"Version"}="2009-05-15";
        $parameters1->{"Period"}="300";        # Default period = 300 secs

        $parameters1->{"MeasureName"}=$metric;
        $parameters1->{"Service"}="EC2";
        $parameters1->{"Dimensions.member.1.Name"}="InstanceId";

        $parameters1->{"Dimensions.member.1.Value"}=$instanceid;
        $parameters1->{"Statistics.member.1"}="Minimum";
        $parameters1->{"Statistics.member.2"}="Average";

        $parameters1->{"Statistics.member.3"}="Maximum";
        $parameters1->{"Statistics.member.4"}="Sum";
        $parameters1->{"Namespace"}="AWS/EC2";

        $parameters1->{"Timestamp"}=_getFormattedTimestamp();
        $parameters1->{"StartTime"}=_getFormattedTimestamp(5);    # Get start time from 5 minutes ago

        $parameters1->{"EndTime"}=_getFormattedTimestamp();
        my $signature = _signParameters($parameters1, $AWS_SECRET_ACCESS_KEY);

        $parameters1->{"Signature"}=$signature;
        my $url = 'http://monitoring.amazonaws.com';

        my $ua = LWP::UserAgent->new;
        my $request= HTTP::Request->new("POST", $url);

        $request->content_type("application/x-www-form-urlencoded; charset=utf-8");
        my $data = "";
        foreach my $parameterName (sort { $a cmp $b } keys %{$parameters1}) {

            $data .= $parameterName .  "="  . _urlencode($parameters1->{$parameterName}, 0);

                $data .= "&";
        }
        chop ($data);
        print "Request URL data = $data\n\n" if ($debug);

        $request->content($data);
        my $response = $ua->request($request);

        print $response."\n"  if ($debug);
        #   This section parses the response
        my $dataref = undef;    # This reference will contain results for this timestamp

        my $timestamp = undef;
        foreach my $resp (keys %{$response}) {

            #print "$resp=$response->{$resp}\n";
            foreach my $line (split "\n",$response->{$resp}) {

        #        print "LINE=$line\n";
                if ($line =~ /<Timestamp>(.*?)<\/Timestamp>/) {

                    $timestamp = $1;
                }
                if ($line =~ /<Minimum>(.*?)<\/Minimum>/) {

                    $dataref->{$timestamp}->{Minimum} = $1 if $timestamp;
                }

                if ($line =~ /<Maximum>(.*?)<\/Maximum>/) {
                    $dataref->{$timestamp}->{Maximum} = $1 if $timestamp;

                }
                if ($line =~ /<Average>(.*?)<\/Average>/) {
                    $dataref->{$timestamp}->{Average} = $1 if $timestamp;

                }
                if ($line =~ /<Sum>(.*?)<\/Sum>/) {
                    $dataref->{$timestamp}->{Sum} = $1 if $timestamp;

                }
                if ($line =~ /<Samples>(.*?)<\/Samples>/) {
                    $dataref->{$timestamp}->{Samples} = $1 if $timestamp;

                }
                if ($line =~ /<Unit>(.*?)<\/Unit>/) {
                    $dataref->{$timestamp}->{Unit} = $1 if $timestamp;

                }
            }
        }
        #
        # Do something with $dataref here
        #
        #

    }
}
 
 
sub _urlencode {
    my ($value, $path) = @_;

    use URI::Escape qw(uri_escape_utf8);
    my $escapepattern = "^A-Za-z0-9\-_.~";

    if ($path) {
        $escapepattern = $escapepattern .  "/";

    }
    return uri_escape_utf8($value, $escapepattern);
}
 
    #

    # Formats date as ISO 8601 timestamp
    #
sub _getFormattedTimestamp {
    my $offsetminutes = shift;

    if (!defined($offsetminutes) or ($offsetminutes !~ /^\d+$/)) {
        $offsetminutes = 0;

    }
    $offsetminutes = $offsetminutes * 60;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time - $offsetminutes);

    return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.000Z",$year+1900,$mon+1,$mday,$hour,$min,$sec);

}
sub _signParameters {
    my ($parameters, $key)  = @_;

    my $algorithm = "HmacSHA1";
    my $data = "";

    $data = _calculateStringToSignV2($parameters);
    #print "Signature Data = $data\n\n";
    return _sign($data, $key, $algorithm);

}
 
 
sub _calculateStringToSignV2  {
    my ($parameters)  = @_;

    my $endpoint = URI->new($url);
    my $data = "POST";

    $data .= "\n";
    #$data .= $endpoint->host();
    $data .= "monitoring.amazonaws.com";

    $data .= "\n";
    my $path =  $endpoint->path || "/";

    $data .= _urlencode($path, 1);
    $data .= "\n";

    my @parameterKeys =   keys %$parameters;
    foreach my $parameterName (sort { $a cmp $b } @parameterKeys ) {

        no warnings "uninitialized";
        $data .= $parameterName .  "="  . _urlencode($parameters->{$parameterName});

        $data .= "&";
    }
    chop ($data);
    return $data;

}
 
sub  _sign {
    my ($data, $key, $algorithm) = @_;

    my $output = "";
    $output  =  hmac_sha1_base64 ($data, $key);

    return $output . "=";
}
 
 

Ruby メソッド

EC2 インスタンスの問い合わせ

下記のサンプルコードは、Amazon のインスタンスとそのアトリビュートをリストします。 AWS gem は、http://github.com/grempe/amazon-ec2 から取得できます。

require 'AWS';
ec2 = AWS::EC2::Base.new( :access_key_id => access_key_id, :secret_access_key => secret_access_key )

$instanceFound = false
options = Hash.new
resp = ec2.describe_instances()
if !resp.reservationSet.nil?  then

    resp.reservationSet.item.each { |x|
      x.instancesSet.item.each { |i|

          puts i.instanceId+" is "+i.instanceState.name
      }
    }

else
    puts "No instances found"
end
 
 
 
Tap In クラウド管理サービス 特徴とメリット 活用事例 Tap In クラウドコントロールサービス
イベント管理アーキテクチャ 管理対象テクノロジー ビューア Amazon CloudWatch との統合 3tera Applogic との統合 GoGrid との統合 プロセス自動化
Tap In Systems について 経営 コンタクト
ドキュメント ダウンロード 技術論文 技術ウィキサイト フォーラム