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…


This content originally appeared on DEV Community and was authored by Bervianto Leo Pratama

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
}
  • 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
}

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

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=

Build

go build

Run Locally

go run server.go

Test

go test ./... -cover

LICENSE

MIT

Thanks for reading. Happy exploring!

GIF


This content originally appeared on DEV Community and was authored by Bervianto Leo Pratama


Print Share Comment Cite Upload Translate Updates
APA

Bervianto Leo Pratama | Sciencx (2022-07-24T14:11:16+00:00) Starting and Stopping EC2 Instances using AWS SDK for Go. Retrieved from https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/

MLA
" » Starting and Stopping EC2 Instances using AWS SDK for Go." Bervianto Leo Pratama | Sciencx - Sunday July 24, 2022, https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/
HARVARD
Bervianto Leo Pratama | Sciencx Sunday July 24, 2022 » Starting and Stopping EC2 Instances using AWS SDK for Go., viewed ,<https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/>
VANCOUVER
Bervianto Leo Pratama | Sciencx - » Starting and Stopping EC2 Instances using AWS SDK for Go. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/
CHICAGO
" » Starting and Stopping EC2 Instances using AWS SDK for Go." Bervianto Leo Pratama | Sciencx - Accessed . https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/
IEEE
" » Starting and Stopping EC2 Instances using AWS SDK for Go." Bervianto Leo Pratama | Sciencx [Online]. Available: https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/. [Accessed: ]
rf:citation
» Starting and Stopping EC2 Instances using AWS SDK for Go | Bervianto Leo Pratama | Sciencx | https://www.scien.cx/2022/07/24/starting-and-stopping-ec2-instances-using-aws-sdk-for-go/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.