Skip to content

Commit 0439c3b

Browse files
Merge pull request #42 from jasdel/ec2/securityGroups
Add EC2 Security Group AWS SDK For Go example.
2 parents 9f1a09c + 2808cc7 commit 0439c3b

File tree

3 files changed

+266
-0
lines changed

3 files changed

+266
-0
lines changed
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
/*
2+
Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
4+
This file is licensed under the Apache License, Version 2.0 (the "License").
5+
You may not use this file except in compliance with the License. A copy of
6+
the License is located at
7+
8+
http://aws.amazon.com/apache2.0/
9+
10+
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
12+
specific language governing permissions and limitations under the License.
13+
*/
14+
15+
package main
16+
17+
import (
18+
"flag"
19+
"fmt"
20+
"os"
21+
22+
"github.com/aws/aws-sdk-go/aws"
23+
"github.com/aws/aws-sdk-go/aws/awserr"
24+
"github.com/aws/aws-sdk-go/aws/session"
25+
"github.com/aws/aws-sdk-go/service/ec2"
26+
)
27+
28+
// Creates a new security group with the given name and description for
29+
// open port 80 and 22 access. Associating the security group with the
30+
// first VPC in the account if a VPC ID is not provided.
31+
//
32+
// Usage:
33+
// go run ec2_describe_security_groups.go -n name -d description -vpc vpcID
34+
func main() {
35+
var name, desc, vpcID string
36+
flag.StringVar(&name, "n", "", "Group Name")
37+
flag.StringVar(&desc, "d", "", "Group Description")
38+
flag.StringVar(&vpcID, "vpc", "", "(Optional) VPC ID to associate security group with")
39+
flag.Parse()
40+
41+
if len(name) == 0 || len(desc) == 0 {
42+
flag.PrintDefaults()
43+
exitErrorf("Group name and description require")
44+
}
45+
46+
// Initialize a session that the SDK will use to load configuration,
47+
// credentials, and region from the shared config file. (~/.aws/config).
48+
sess := session.Must(session.NewSessionWithOptions(session.Options{
49+
SharedConfigState: session.SharedConfigEnable,
50+
}))
51+
52+
// Create an EC2 service client.
53+
svc := ec2.New(sess)
54+
55+
// If the VPC ID wasn't provided in the CLI retrieve the first in the account.
56+
if len(vpcID) == 0 {
57+
// Get a list of VPCs so we can associate the group with the first VPC.
58+
result, err := svc.DescribeVpcs(nil)
59+
if err != nil {
60+
exitErrorf("Unable to describe VPCs, %v", err)
61+
}
62+
if len(result.Vpcs) == 0 {
63+
exitErrorf("No VPCs found to associate security group with.")
64+
}
65+
vpcID = aws.StringValue(result.Vpcs[0].VpcId)
66+
}
67+
68+
// Create the security group with the VPC, name and description.
69+
createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{
70+
GroupName: aws.String(name),
71+
Description: aws.String(desc),
72+
VpcId: aws.String(vpcID),
73+
})
74+
if err != nil {
75+
if aerr, ok := err.(awserr.Error); ok {
76+
switch aerr.Code() {
77+
case "InvalidVpcID.NotFound":
78+
exitErrorf("Unable to find VPC with ID %q.", vpcID)
79+
case "InvalidGroup.Duplicate":
80+
exitErrorf("Security group %q already exists.", name)
81+
}
82+
}
83+
exitErrorf("Unable to create security group %q, %v", name, err)
84+
}
85+
fmt.Printf("Created security group %s with VPC %s.\n",
86+
aws.StringValue(createRes.GroupId), vpcID)
87+
88+
// Add permissions to the security group
89+
_, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{
90+
GroupName: aws.String(name),
91+
IpPermissions: []*ec2.IpPermission{
92+
// Can use setters to simplify seting multiple values without the
93+
// needing to use aws.String or associated helper utilities.
94+
(&ec2.IpPermission{}).
95+
SetIpProtocol("tcp").
96+
SetFromPort(80).
97+
SetToPort(80).
98+
SetIpRanges([]*ec2.IpRange{
99+
{CidrIp: aws.String("0.0.0.0/0")},
100+
}),
101+
(&ec2.IpPermission{}).
102+
SetIpProtocol("tcp").
103+
SetFromPort(22).
104+
SetToPort(22).
105+
SetIpRanges([]*ec2.IpRange{
106+
(&ec2.IpRange{}).
107+
SetCidrIp("0.0.0.0/0"),
108+
}),
109+
},
110+
})
111+
if err != nil {
112+
exitErrorf("Unable to set security group %q ingress, %v", name, err)
113+
}
114+
115+
fmt.Println("Successfully set security group ingress")
116+
117+
}
118+
119+
func exitErrorf(msg string, args ...interface{}) {
120+
fmt.Fprintf(os.Stderr, msg+"\n", args...)
121+
os.Exit(1)
122+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
4+
This file is licensed under the Apache License, Version 2.0 (the "License").
5+
You may not use this file except in compliance with the License. A copy of
6+
the License is located at
7+
8+
http://aws.amazon.com/apache2.0/
9+
10+
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
12+
specific language governing permissions and limitations under the License.
13+
*/
14+
15+
package main
16+
17+
import (
18+
"fmt"
19+
"os"
20+
"path/filepath"
21+
22+
"github.com/aws/aws-sdk-go/aws"
23+
"github.com/aws/aws-sdk-go/aws/awserr"
24+
"github.com/aws/aws-sdk-go/aws/session"
25+
"github.com/aws/aws-sdk-go/service/ec2"
26+
)
27+
28+
// Deletes a security group by the ID passed in.
29+
//
30+
// Usage:
31+
// go run ec2_delete_security_group.go group_id
32+
func main() {
33+
if len(os.Args) != 2 {
34+
exitErrorf("Security Group ID required\nUsage: %s group_id",
35+
filepath.Base(os.Args[0]))
36+
}
37+
groupID := os.Args[1]
38+
39+
// Initialize a session that the SDK will use to load configuration,
40+
// credentials, and region from the shared config file. (~/.aws/config).
41+
sess := session.Must(session.NewSessionWithOptions(session.Options{
42+
SharedConfigState: session.SharedConfigEnable,
43+
}))
44+
45+
// Create an EC2 service client.
46+
svc := ec2.New(sess)
47+
48+
// Delete the security group.
49+
_, err := svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
50+
GroupId: aws.String(groupID),
51+
})
52+
if err != nil {
53+
if aerr, ok := err.(awserr.Error); ok {
54+
switch aerr.Code() {
55+
case "InvalidGroupId.Malformed":
56+
fallthrough
57+
case "InvalidGroup.NotFound":
58+
exitErrorf("%s.", aerr.Message())
59+
}
60+
}
61+
exitErrorf("Unable to get descriptions for security groups, %v.", err)
62+
}
63+
64+
fmt.Printf("Successfully delete security group %q.\n", groupID)
65+
}
66+
67+
func exitErrorf(msg string, args ...interface{}) {
68+
fmt.Fprintf(os.Stderr, msg+"\n", args...)
69+
os.Exit(1)
70+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
4+
This file is licensed under the Apache License, Version 2.0 (the "License").
5+
You may not use this file except in compliance with the License. A copy of
6+
the License is located at
7+
8+
http://aws.amazon.com/apache2.0/
9+
10+
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
11+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
12+
specific language governing permissions and limitations under the License.
13+
*/
14+
15+
package main
16+
17+
import (
18+
"fmt"
19+
"os"
20+
"path/filepath"
21+
22+
"github.com/aws/aws-sdk-go/aws"
23+
"github.com/aws/aws-sdk-go/aws/awserr"
24+
"github.com/aws/aws-sdk-go/aws/session"
25+
"github.com/aws/aws-sdk-go/service/ec2"
26+
)
27+
28+
// Describes the security groups by IDs that are passed into the CLI. Takes
29+
// a space separated list of group IDs as input.
30+
//
31+
// Usage:
32+
// go run ec2_describe_security_groups.go groupId1 groupId2 ...
33+
func main() {
34+
if len(os.Args) < 2 {
35+
exitErrorf("Security Group ID required\nUsage: %s group_id ...",
36+
filepath.Base(os.Args[0]))
37+
}
38+
groupIds := os.Args[1:]
39+
40+
// Initialize a session that the SDK will use to load configuration,
41+
// credentials, and region from the shared config file. (~/.aws/config).
42+
sess := session.Must(session.NewSessionWithOptions(session.Options{
43+
SharedConfigState: session.SharedConfigEnable,
44+
}))
45+
46+
// Create an EC2 service client.
47+
svc := ec2.New(sess)
48+
49+
// Retrieve the security group descriptions
50+
result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
51+
GroupIds: aws.StringSlice(groupIds),
52+
})
53+
if err != nil {
54+
if aerr, ok := err.(awserr.Error); ok {
55+
switch aerr.Code() {
56+
case "InvalidGroupId.Malformed":
57+
fallthrough
58+
case "InvalidGroup.NotFound":
59+
exitErrorf("%s.", aerr.Message())
60+
}
61+
}
62+
exitErrorf("Unable to get descriptions for security groups, %v", err)
63+
}
64+
65+
fmt.Println("Security Group:")
66+
for _, group := range result.SecurityGroups {
67+
fmt.Println(group)
68+
}
69+
}
70+
71+
func exitErrorf(msg string, args ...interface{}) {
72+
fmt.Fprintf(os.Stderr, msg+"\n", args...)
73+
os.Exit(1)
74+
}

0 commit comments

Comments
 (0)