0
0

GOのAWS SDKでEC2のインスタンスを作成

Posted at

はじめに

GoのAWS SDKを使用してEC2のインスタンスを作成してみました。これまでも、インスタンスの起動、停止用のツールとして使用していましたが、もうちょっと深く学習してみようと思い、EC2インスタンスの作成を行ってみました。

環境

  • Windows 11
  • AWS SDK for Go v2

前提

AWSサービスにプログラムからアクセスするため、AWS側でAccess Key IDとSecret Access Keyを事前に作成し、~/.aws/credentialsファイルを準備しました。SDKでもcredentialsファイルからプロファイルを読み込むことができます。

【credentialsファイル】

[myregion]
aws_access_key_id = <Access Key ID>
aws_secret_access_key = <Secret Access Key>

また、EC2で使用するKeyPaire、Subnet、SecurityGroupも事前にAWSで作成しています。プログラムで作成できますが、力不足のためやってません。

コード(インスタンス作成部分)

	sess := session.Must(session.NewSessionWithOptions(session.Options{
		Profile: "myregion", // specify profile
	}))
	svc := ec2.New(sess, aws.NewConfig().WithRegion("ap-northeast-1"))
	result, err := svc.RunInstances(&ec2.RunInstancesInput{
		ImageId:      aws.String("ami-00c79d83cf718a893"),
		InstanceType: aws.String("t2.micro"),
		MinCount:     aws.Int64(1),
		MaxCount:     aws.Int64(1),
		KeyName:      aws.String("testkey"),
		//SecurityGroupIds: []*string{aws.String("sg-05c48f49dbf81efeb")},
		NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
			{
				DeviceIndex:              aws.Int64(0), // required
				AssociatePublicIpAddress: aws.Bool(true),
				SubnetId:                 aws.String("subnet-05f2a9a81d40d433d"),
				Groups:                   []*string{aws.String("sg-05c48f49dbf81efeb")},
			},
		},
	})

	if err != nil {
		log.Fatalf("Unable to create instance, %v", err)
	}
	fmt.Println(result)

① ~/.aws/credentialsファイルに指定した"myregion" プロファイルを使用してAWSセッションを作成
② "ap-northeast-1" リージョン用の EC2 サービスクライアントを初期化
③ ec2.RunInstancesで指定されたパラメタにもとづきインスタンスを作成
④ 作成するEC2インスタンスの情報がresultにJSON形式で設定される

ec2.InstanceNetworkInterfaceSpecificationで、作成するEC2インスタンスのパラメタを設定していますが、
指定できるパラメタについては、APIのリファレンスを確認しました。

パラメタには、次のものを指定しています。Key Pair、subnet、Secrurity Groupは事前にAWS側で作成したものからIDを拾ってきています。また、AssociatePublicIpAddressをtrueにしておくことで、pubic IPが割り振られます。

  • AMI: ami-00c79d83cf718a893
  • Instance Type: t2.micro
  • Key Pair: testkey
  • Subnet: subnet-05f2a9a81d40d433d
  • Security Group: sg-05c48f49dbf81efeb

ちなみに、AMIに指定するIDは、AWSのコンソールから確認できますが、SDKを使用して次のようなコードで取得することもできます。次の例では、amazonが所有する、AMIのImageID、Imageの名前、作成日を10件分出力さしています。

	params := &ec2.DescribeImagesInput{
		Owners:     []*string{aws.String("amazon")},
		MaxResults: aws.Int64(10),
	}

	res, err := svc.DescribeImages(params)
	if err != nil {
		fmt.Println(err.Error())
	}
	for _, image := range res.Images {
		fmt.Println(*image.ImageId, *image.Name, *image.CreationDate)
	}

おわりに

AWSを操作するのみであれば、CLI、スクリプト言語のほうがお手軽ですが、Goを使用してツールを作った場合、実行ファイルにしてインストールすることなく別の端末に配置して使用できるところが便利だと思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0