This example stops an Amazon EC2 instance.

go run StopInstancesv2.go -i INSTANCE-ID

  • INSTANCE-ID is the ID of the instance to stop.

The unit test accepts a similar value in config.json.

Source code

// Copyright, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
package main

import (


// EC2StopInstancesAPI defines the interface for the StopInstances function.
// We use this interface to test the function using a mocked service.
type EC2StopInstancesAPI interface {
	StopInstances(ctx context.Context,
		params *ec2.StopInstancesInput,
		optFns ...func(*ec2.Options)) (*ec2.StopInstancesOutput, error)

// StopInstance stops an Amazon Elastic Compute Cloud (Amazon EC2) instance.
// Inputs:
//     c is the context of the method call, which includes the AWS Region.
//     api is the interface that defines the method call.
//     input defines the input arguments to the service call.
// Output:
//     If success, a StopInstancesOutput object containing the result of the service call and nil.
//     Otherwise, nil and an error from the call to StopInstances.
func StopInstance(c context.Context, api EC2StopInstancesAPI, input *ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error) {
	resp, err := api.StopInstances(c, input)

    var apiErr smithy.APIError
    if errors.As(err, &apiErr) && apiErr.ErrorCode() == "DryRunOperation" {
        fmt.Println("User has permission to stop instances.")
        input.DryRun = false
        return api.StopInstances(c, input)

	return resp, err

func main() {
	instanceID := flag.String("i", "", "The ID of the instance to stop")

	if *instanceID == "" {
		fmt.Println("You must supply an instance ID (-i INSTANCE-ID")

	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		panic("configuration error, " + err.Error())

	client := ec2.NewFromConfig(cfg)

	input := &ec2.StopInstancesInput{
		InstanceIds: []string{
		DryRun: true,

	_, err = StopInstance(context.TODO(), client, input)
	if err != nil {
		fmt.Println("Got an error stopping the instance")

	fmt.Println("Stopped instance with ID " + *instanceID)

See the complete example in GitHub.