MCPcopy Create free account
hub / github.com/awsdocs/aws-doc-sdk-examples / main

Function main

go/example_code/ec2/ec2_create_security_group.go:27–120  ·  view source on GitHub ↗

snippet-end:[ec2.go.create_security_group.imports] Creates a new security group with the given name and description for open port 80 and 22 access. Associating the security group with the first VPC in the account if a VPC ID is not provided. Usage: go run ec2_describe_security_groups.go -n name -

()

Source from the content-addressed store, hash-verified

25//
26// go run ec2_describe_security_groups.go -n name -d description -vpc vpcID
27func main() {
28 // snippet-start:[ec2.go.create_security_group.vars]
29 namePtr := flag.String("n", "", "Group Name")
30 descPtr := flag.String("d", "", "Group Description")
31 vpcIDPtr := flag.String("vpc", "", "(Optional) VPC ID to associate security group with")
32
33 flag.Parse()
34
35 if *namePtr == "" || *descPtr == "" {
36 flag.PrintDefaults()
37 exitErrorf("Group name and description require")
38 }
39 // snippet-end:[ec2.go.create_security_group.vars]
40
41 // Initialize a session that the SDK will use to load
42 // credentials from the shared credentials file ~/.aws/credentials.
43 // snippet-start:[ec2.go.create_security_group.session]
44 sess := session.Must(session.NewSessionWithOptions(session.Options{
45 SharedConfigState: session.SharedConfigEnable,
46 }))
47
48 svc := ec2.New(sess)
49 // snippet-end:[ec2.go.create_security_group.session]
50
51 // If the VPC ID wasn't provided in the CLI retrieve the first in the account.
52 // snippet-start:[ec2.go.create_security_group.vpcid]
53 if *vpcIDPtr == "" {
54 // Get a list of VPCs so we can associate the group with the first VPC.
55 result, err := svc.DescribeVpcs(nil)
56 if err != nil {
57 exitErrorf("Unable to describe VPCs, %v", err)
58 }
59 if len(result.Vpcs) == 0 {
60 exitErrorf("No VPCs found to associate security group with.")
61 }
62
63 *vpcIDPtr = aws.StringValue(result.Vpcs[0].VpcId)
64 }
65 // snippet-end:[ec2.go.create_security_group.vpcid]
66
67 // Create the security group with the VPC, name and description.
68 // snippet-start:[ec2.go.create_security_group.create]
69 createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{
70 GroupName: aws.String(*namePtr),
71 Description: aws.String(*descPtr),
72 VpcId: aws.String(*vpcIDPtr),
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.", *vpcIDPtr)
79 case "InvalidGroup.Duplicate":
80 exitErrorf("Security group %q already exists.", *namePtr)
81 }
82 }
83 exitErrorf("Unable to create security group %q, %v", *namePtr, err)
84 }

Callers

nothing calls this directly

Calls 5

DescribeVpcsMethod · 0.80
CreateSecurityGroupMethod · 0.80
exitErrorfFunction · 0.70
StringMethod · 0.45

Tested by

no test coverage detected