Menu Close

Create a VPC in AWS using Go SDK

In this article, we will are going to learn how to Create a VPC in AWS using Go SDK with example in details.

Creating a Virtual Private Cloud (VPC) on Amazon Web Services (AWS) is essential for securing and managing your cloud infrastructure.

Prerequisites to Create a VPC in AWS using Go SDK :

  1. You should have an AWS account
  2. Go installed on your local machine (v1.16 or later).
  3. A basic understanding of Go programming

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 to create VPC:

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"

)


// Creating a VPC
func createVPC(svc *ec2.EC2, cidrBlock string) (*ec2.Vpc, error) {

    input := &ec2.CreateVpcInput{

        CidrBlock: aws.String(cidrBlock),

    }


    result, err := svc.CreateVpc(input)

    if err != nil {

        fmt.Println("Error creating VPC:", err)

        return nil, err

    }


    return result.Vpc, nil

}


func main() {
    //  Initialize 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

    }


    svc := ec2.New(sess)

    
    // Create VPC
    vpc, err := createVPC(svc, "10.0.0.0/16")

    
    if err != nil {

        fmt.Println("Error creating VPC:", err)

        return

    }


    fmt.Println("VPC created:", *vpc.VpcId)

}

Save your Go file and run it using the go run command. You should see output similar to the following:

Output:

VPC created: vpc-xxxxxxxx

This indicates that your VPC was successfully created.

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)

Posted in AWS, Cloud, golang

Leave a Reply

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