Starting and Stopping EC2 Instances using AWS SDK for Go
Tags: go, aws, awssdk, ec2
Published: 2022-07-24 14:11:16

The previous post was about AWS SDK for Go and explained to utilize S3 for uploading files. You will explore more AWS SDK for Go to start and stop EC2 instances, usually, you will use this using Lambda like [this post](https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/). But, I will use the AWS SDK for my Go services. Let's get started!

## Initial Project

You may try to start the project from [this commit](https://github.com/bervProject/go-microservice-boilerplate/tree/9f74c96fd798a7e2172f57019db08d370a6f9082). To check my changes, you may check [this commit](https://github.com/bervProject/go-microservice-boilerplate/commit/cfc1c2c42577e5ed9840da97f68f3cfad27f9b13).

## Setup/Install AWS SDK for Go

Other dependencies (exclude S3) you may check from the previous post.

`go get github.com/aws/aws-sdk-go-v2/service/ec2`

## The functions

Currently, the example uses a hardcoded list of instances that I want to start and stop.

* Starting an instance

```go
func (ec2Handler *EC2Handler) StartInstance(ctx context.Context) (err error) {
	instanceId := "i-0b33f0e5d8d00d6f3" // list your instances here, if you want to have a list instead of 1 instance. You may need to update the input from InstanceIds: []string{instanceId} to InstancedIds: instanceIds and rename the variable to instanceIds also do some changes in the for loop.
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Fatal(err)
	}
	ec2Client := ec2.NewFromConfig(cfg)
	input := &ec2.DescribeInstanceStatusInput{
		InstanceIds: []string{instanceId},
	}
	output, err := ec2Client.DescribeInstanceStatus(ctx, input)
	if err != nil {
		log.Println(err)
		return
	}
	isRunning := false
	for _, instanceStatus := range output.InstanceStatuses {
		log.Printf("%s: %s\n", *instanceStatus.InstanceId, instanceStatus.InstanceState.Name)
		if *instanceStatus.InstanceId == instanceId && instanceStatus.InstanceState.Name == "running" {
			isRunning = true
		}
	}
	if !isRunning {
		runInstance := &ec2.StartInstancesInput{
			InstanceIds: []string{instanceId},
		}
		log.Printf("Start %s", instanceId)
		if outputStart, errInstance := ec2Client.StartInstances(ctx, runInstance); errInstance != nil {
			return
		} else {
			log.Println(outputStart.StartingInstances)
		}
	} else {
		log.Printf("Skip starting %s", instanceId)
	}
	return
}
```

* Stopping an instance

```go
func (ec2Handler *EC2Handler) StopInstance(ctx context.Context) (err error) {
	instanceId := "i-0b33f0e5d8d00d6f3"
	cfg, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Fatal(err)
	}
	ec2Client := ec2.NewFromConfig(cfg)
	input := &ec2.DescribeInstanceStatusInput{
		InstanceIds: []string{instanceId},
	}
	output, err := ec2Client.DescribeInstanceStatus(ctx, input)
	if err != nil {
		log.Println(err)
		return
	}
	isStop := false
	for _, instanceStatus := range output.InstanceStatuses {
		log.Printf("%s: %s\n", *instanceStatus.InstanceId, instanceStatus.InstanceState.Name)
		if *instanceStatus.InstanceId == instanceId && instanceStatus.InstanceState.Name == "stop" {
			isStop = true
		}
	}
	if !isStop {
		stopInstance := &ec2.StopInstancesInput{
			InstanceIds: []string{instanceId},
		}
		log.Printf("Stop %s", instanceId)
		if outputStop, errInstance := ec2Client.StopInstances(ctx, stopInstance); errInstance != nil {
			return
		} else {
			log.Println(outputStop.StoppingInstances)
		}
	} else {
		log.Printf("Skip stop %s", instanceId)
	}
	return
}
```

Don't forget to set up the credentials. Currently, I use environment variables.

```bash
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=ap-southeast-3
```

Quite easy, right? You may use AWS SDK for Go for another use case. If you want to explore more the repository, you may visit this link.

{% github bervProject/go-microservice-boilerplate %}

Thanks for reading. Happy exploring!

![GIF](https://media.giphy.com/media/l46Cq3dy04lgkRVOE/giphy.gif)