えまログ

機械学習、プログラミング、数学に関する記事を書いていきます。

aws SDK for .NETでの認証方法

C#でEC2インスタンスの監視するアプリを作りたかったのですが、認証に失敗して躓いたので記事に残そうと思います。

認証方法

以下の3つがあります。今回は1のSDKストアを使用します。
方法1.SDKストアを使う
ユーザーのホームディレクトリに認証情報ファイルを暗号化して作成し、それを参照します。

方法2.Credentialファイルを使う
キーIDとシークレットキーIDを書いたテキストファイルを指定すれば良いので簡単ですが、ファイルを見ればIDがわかってしまうのでおすすめしません。

方法3.環境変数を使う
こちらもIDが見えるのでおすすめしません。

以下、手順です。

1. プロファイル作成

以下を一度実行すればプロファイルが作成されます。

using Amazon.Runtime.CredentialManagement;
using System;


namespace CreateProfile
{
    class Program
    {
        static void Main(string[] args)
        {
            string profileName = "[プロファイル名]";
            string keyId = "[KEY_ID]";
            string secretKey = "SECRET_KEY";
            WriteProfile(profileName, keyId, secretKey);
        }

        static void WriteProfile(string profileName, string keyId, string secretKey)
        {
            Console.WriteLine($"Create the [{profileName}] profile");
            var options = new CredentialProfileOptions
            {
                AccessKey = keyId,
                SecretKey = secretKey
            };
            var profile = new CredentialProfile(profileName, options);
            var netSdkStore = new NetSDKCredentialsFile();
            netSdkStore.RegisterProfile(profile);
        }
    }
}

成功すると、 [%USERPROFILE%\AppData\Local\AWSToolkit\RegisteredAccounts.json に認証情報ファイルが暗号化した状態で保存されます。

キャプチャ

2. プロファイルを利用してインスタンスのステータスを監視する

以下のように実装しました。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;

using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;

namespace CheckStatus
{

    class Program
    {
        static void Main(string[] args)
        {
            var instanceId = "i-0xxxxxxxxxxxxxxx";
            var instanceIds = new List<string> { instanceId };
            DescribeInstancesResponse responseDescribe;
            var requestDescribe = new DescribeInstancesRequest
            {
                InstanceIds = instanceIds,
            };

            var ec2Client = new AmazonEC2Client(RegionEndpoint.APNortheast1);
            
            int wait = 2000; // miliseconds
            while (true)
            {
                Console.Write("");
                var response = ec2Client.DescribeInstancesAsync(requestDescribe).Result.Reservations;
                foreach(var reservations in response)
                {
                    foreach (var instance in reservations.Instances)
                    {
                        Console.WriteLine("{0}: {1}",instance.InstanceId, instance.State.Name);
                        //     0 : pending
                        //     16 : running
                        //     32 : shutting-down
                        //     48 : terminated
                        //     64 : stopping
                        //     80 : stopped
                        //     You can ignore the high byte value by zeroing out all of the bits above 2^8 or
                        //     256 in decimal.
                    }
                    Thread.Sleep(wait);
                }
            } 
        }
    }
}

設定は以下のようになっています。"AWSProfileName"="sample_profile"と指定しておけば自動で参照してくれます。

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="AWSProfileName" value="sample_profile"/>
    </appSettings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

実行結果

停止していたインスタンスをマネジメントコンソールから起動→停止したときの挙動です。

i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: pending
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: running
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopping
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped
i-0xxxxxxxxxxxxxxx: stopped

この記事は以下を参考にしました。

docs.aws.amazon.com