In this article, we will are going to learn how to Stop an Amazon EC2 instance using AWS Go SDK with example in details.
In certain situations, you might need to stop an EC2 instance to save costs, perform maintenance, or for other reasons.
Please note that stopping an EC2 instance will cause any unsaved data on the instance’s ephemeral storage to be lost. To avoid data loss, ensure your data is backed up or stored on EBS volumes.
Table of Contents:
- Prerequisites for stopping an EC2 instance using Go SDK
- Setting up the AWS Go SDK
- Stopping an EC2 instance using Go SDK
- Best practices for stopping EC2 instances
Prerequisites to Stop an Amazon EC2 instance using AWS Go SDK:
- An active AWS account
- An EC2 instance running in your account
- Necessary permissions to stop the instance
- Go language installed on your machine
- AWS Go SDK installed and configured
Setting up the AWS Go SDK:
To set up the AWS Go SDK, follow these steps:
- Install the AWS Go SDK by running the following command:
go get -u github.com/aws/aws-sdk-go
- Configure your AWS credentials by setting up the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION environment variables or by using a shared credentials file.
Stopping an EC2 instance using Go SDK:
Example:
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
// Create a new AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Error creating session:", err)
return
}
// Create a new EC2 service client
svc := ec2.New(sess)
// Specify the instance ID to stop
instanceID := "i-1234567890abcdef0"
// Stop the instance
input := &ec2.StopInstancesInput{
InstanceIds: []*string{
aws.String(instanceID),
},
}
result, err := svc.StopInstances(input)
if err != nil {
fmt.Println("Error stopping instance:", err)
return
}
fmt.Println("Instance stopped:", result.StoppingInstances)
}
Replace “i-1234567890abcdef0” with your instance ID and adjust the region according to your instance’s location.
Best practices for stopping EC2 instances:
- Always backup or store data on EBS volumes to prevent data loss when stopping instances.
- Use resource tags to identify instances that can be safely stopped.
- Schedule instance stopping during off-peak hours to minimize disruption.
- Monitor and track stopped instances to ensure they are restarted when needed.
To learn more about golang, Please refer given below link.
https://www.techieindoor.com/golang-tutorial/
References:
https://en.wikipedia.org/wiki/Go_(programming_language)