Menu Close

Stop an Amazon EC2 instance using AWS Go SDK

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:

  1. Prerequisites for stopping an EC2 instance using Go SDK
  2. Setting up the AWS Go SDK
  3. Stopping an EC2 instance using Go SDK
  4. Best practices for stopping EC2 instances

Prerequisites to Stop an Amazon EC2 instance using AWS Go SDK:

  1. An active AWS account
  2. An EC2 instance running in your account
  3. Necessary permissions to stop the instance
  4. Go language installed on your machine
  5. 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
  • 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:


package main

import (






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)



	// 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{




	result, err := svc.StopInstances(input)

	if err != nil {

		fmt.Println("Error stopping instance:", err)



	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.


Posted in AWS, Cloud, golang

Leave a Reply

Your email address will not be published. Required fields are marked *