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 -
()
| 25 | // |
| 26 | // go run ec2_describe_security_groups.go -n name -d description -vpc vpcID |
| 27 | func 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 | } |
nothing calls this directly
no test coverage detected