Menu
AWS SDK for Go
Developer Guide

Working with Security Groups in Amazon EC2

These Go examples show you how to:

  • Retrieve information about your security groups

  • Create a security group to access an Amazon EC2 instance

  • Delete an existing security group

You can download complete versions of these example files from the aws-doc-sdk-examples repository on GitHub.

Scenario

An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more instances. You add rules to each security group to allow traffic to or from its associated instances. You can modify the rules for a security group at any time; the new rules are automatically applied to all instances that are associated with the security group.

The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the Amazon EC2 client class:

Prerequisites

Describing Your Security Groups

This example describes the security groups by IDs that are passed into the routine. It takes a space separated list of group IDs as input.

To get started, create a new Go file named ec2_describe_security_groups.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatch" )

In the main function, get the security group ID that is passed in.

Copy
func main() { if len(os.Args) < 2 { exitErrorf("Security Group ID required\nUsage: %s group_id ...", filepath.Base(os.Args[0])) } groupIds := os.Args[1:]

Initialize a session and create an EC2 service client.

Copy
sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) // Create an EC2 service client. svc := ec2.New(sess)

Obtain and print out the security group descriptions. You will explicity check for errors caused by an invalid group ID.

Copy
result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ GroupIds: aws.StringSlice(groupIds), }) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case "InvalidGroupId.Malformed": fallthrough case "InvalidGroup.NotFound": exitErrorf("%s.", aerr.Message()) } } exitErrorf("Unable to get descriptions for security groups, %v", err) } fmt.Println("Security Group:") for _, group := range result.SecurityGroups { fmt.Println(group) } }

The following utility function is used by this example.

Copy
func exitErrorf(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) }

Creating a Security Group

You can create new Amazon EC2 security groups. To do this, you use the CreateSecurityGroup method.

This example creates a new security group with the given name and description for access to open ports 80 and 22. If a VPC ID is not provided, it associates the security group with the first VPC in the account.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
package main import ( "flag" "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" )

Get the parameters (name, description, and optional ID of the VPC) that are passed in to the routine.

Copy
func main() { var name, desc, vpcID string flag.StringVar(&name, "n", "", "Group Name") flag.StringVar(&desc, "d", "", "Group Description") flag.StringVar(&vpcID, "vpc", "", "(Optional) VPC ID to associate security group with") flag.Parse() if len(name) == 0 || len(desc) == 0 { flag.PrintDefaults() exitErrorf("Group name and description require") }

Create a session.

Copy
sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) // Create an EC2 service client. svc := ec2.New(sess)

If the VPC ID was not provided, you have to retrieve the first one in the account.

Copy
if len(vpcID) == 0 { // Get a list of VPCs so we can associate the group with the first VPC. result, err := svc.DescribeVpcs(nil) if err != nil { exitErrorf("Unable to describe VPCs, %v", err) } if len(result.Vpcs) == 0 { exitErrorf("No VPCs found to associate security group with.") } vpcID = aws.StringValue(result.Vpcs[0].VpcId) }

Then create the security group with the VPC ID, name, and description.

Copy
createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{ GroupName: aws.String(name), Description: aws.String(desc), VpcId: aws.String(vpcID), }) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case "InvalidVpcID.NotFound": exitErrorf("Unable to find VPC with ID %q.", vpcID) case "InvalidGroup.Duplicate": exitErrorf("Security group %q already exists.", name) } } exitErrorf("Unable to create security group %q, %v", name, err) } fmt.Printf("Created security group %s with VPC %s.\n", aws.StringValue(createRes.GroupId), vpcID)

Add permissions to the security group.

Copy
_, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{ GroupName: aws.String(name), IpPermissions: []*ec2.IpPermission{ (&ec2.IpPermission{}). SetIpProtocol("tcp"). SetFromPort(80). SetToPort(80). SetIpRanges([]*ec2.IpRange{ {CidrIp: aws.String("0.0.0.0/0")}, }), (&ec2.IpPermission{}). SetIpProtocol("tcp"). SetFromPort(22). SetToPort(22). SetIpRanges([]*ec2.IpRange{ (&ec2.IpRange{}). SetCidrIp("0.0.0.0/0"), }), }, }) if err != nil { exitErrorf("Unable to set security group %q ingress, %v", name, err) } fmt.Println("Successfully set security group ingress") }

The following utility function is used by this example.

Copy
func exitErrorf(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) }

Deleting a Security Group

You can delete an Amazon EC2 security group in code. To do this, you use the DeleteSecurityGroup method.

This example deletes a security group with the given group ID.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
package main import ( "fmt" "os" "path/filepath" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" )

Get the group ID that is passed in to the routine.

Copy
func main() { if len(os.Args) != 2 { exitErrorf("Security Group ID required\nUsage: %s group_id", filepath.Base(os.Args[0])) } groupID := os.Args[1]

Create a session.

Copy
svc := ec2.New(sess)

Then delete the security group with the group ID that is passed in.

Copy
_, err := svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{ GroupId: aws.String(groupID), }) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case "InvalidGroupId.Malformed": fallthrough case "InvalidGroup.NotFound": exitErrorf("%s.", aerr.Message()) } } exitErrorf("Unable to get descriptions for security groups, %v.", err) } fmt.Printf("Successfully delete security group %q.\n", groupID) }

This example uses the following utility function.

Copy
func exitErrorf(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) }