Here, we will are going to learn how to create or provision an AWS EC2 Instance using Go SDK with example in details.
AWS EC2 allows users to run virtual machines (instances) in the cloud, providing scalable computing power on demand. This article will explore how to create an AWS EC2 Instance using Go SDK, a powerful tool for developers building applications with the Go programming language.
Prerequisites:
- An AWS account with the necessary permissions to create and manage EC2 instances.
- Go installed on your local machine (v1.16 or later).
To begin, you’ll need to install the AWS SDK for Go. Open your terminal and run:
go get -u github.com/aws/aws-sdk-go
This command downloads and installs the SDK for Go.
Example of creating an EC2 Instance:
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 createEC2Instance(sess *session.Session) (*ec2.Instance, error) {
svc := ec2.New(sess)
input := &ec2.RunInstancesInput{
ImageId: aws.String("ami-0c55b159cbfafe1f0"), // Amazon Linux 2 AMI ID
InstanceType: aws.String("t2.micro"),
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
KeyName: aws.String("your-key-pair-name"),
}
result, err := svc.RunInstances(input)
if err != nil {
return nil, err
}
return result.Instances[0], nil
}
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
})
if err != nil {
fmt.Println("Error creating session:", err)
return
}
instance, err := createEC2Instance(sess)
if err != nil {
fmt.Println("Error creating instance:", err)
return
}
fmt.Printf("Created instance with ID: %s\n", *instance.InstanceId)
}
Output:
go run main.go
Upon successful execution, you will see the created instance ID as output. You can verify the instance creation in the AWS Management Console.
To learn more about golang, Please refer given below link.
https://techieindoor.com/golang-tutorial/
References:
https://en.wikipedia.org/wiki/Go_(programming_language)