DEV Community

Starting and Stopping EC2 Instances using AWS SDK for Go

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. 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. To check my changes, you may check this commit.

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
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
}
Enter fullscreen mode Exit fullscreen mode
  • Stopping an instance
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
}
Enter fullscreen mode Exit fullscreen mode

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

export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=ap-southeast-3
Enter fullscreen mode Exit fullscreen mode

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 logo bervProject / go-microservice-boilerplate

Go Microservice Boilerplate

go-microservice-boilerplate

codecov

Go Microservice Boilerplate

Environment

DB_CONNECTION_STRING=
PORT=
Enter fullscreen mode Exit fullscreen mode

Build

go build
Enter fullscreen mode Exit fullscreen mode

Run Locally

go run server.go
Enter fullscreen mode Exit fullscreen mode

Test

go test ./... -cover
Enter fullscreen mode Exit fullscreen mode

LICENSE

MIT

Thanks for reading. Happy exploring!

GIF

Top comments (0)