Created
April 5, 2022 11:47
-
-
Save lzap/93e665a4691227d0aff7057e310f6c74 to your computer and use it in GitHub Desktop.
AWS SDK V2 test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"errors" | |
"fmt" | |
"github.com/aws/aws-sdk-go-v2/aws" | |
"github.com/aws/aws-sdk-go-v2/credentials" | |
"github.com/aws/aws-sdk-go-v2/service/ec2" | |
"github.com/aws/aws-sdk-go-v2/service/ec2/types" | |
"github.com/aws/smithy-go" | |
) | |
func DescribeSecurityGroups(client *ec2.Client) { | |
resp, err := client.DescribeSecurityGroups(context.TODO(), | |
&ec2.DescribeSecurityGroupsInput{}) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("security groups:") | |
for _, sg := range resp.SecurityGroups { | |
fmt.Printf("%s %s %s\n", *sg.GroupId, *sg.GroupName, *sg.Description) | |
} | |
} | |
// pagination, unfortunately AWS always return in random order | |
func DescribeInstanceTypes(client *ec2.Client, nextToken string) string { | |
input := &ec2.DescribeInstanceTypesInput{} | |
if len(nextToken) > 0 { | |
input.NextToken = aws.String(nextToken) | |
} | |
input.MaxResults = aws.Int32(5) | |
resp, err := client.DescribeInstanceTypes(context.TODO(), input) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("\ninstance types:") | |
for _, it := range resp.InstanceTypes { | |
fmt.Printf("%s\n", it.InstanceType) | |
} | |
return *resp.NextToken | |
} | |
func CreateLaunchTemplate(client *ec2.Client) { | |
image := "ami-08c308b1bb265e927" | |
input := &ec2.CreateLaunchTemplateInput{} | |
input.LaunchTemplateName = aws.String("test") | |
input.LaunchTemplateData = &types.RequestLaunchTemplateData{} | |
input.LaunchTemplateData.ImageId = &image | |
_, err := client.CreateLaunchTemplate(context.TODO(), input) | |
if err != nil { | |
var opError *smithy.GenericAPIError | |
if errors.As(err, &opError) && opError.Code == "InvalidLaunchTemplateName.AlreadyExistsException" { | |
// launch template already exists, skip this | |
} else { | |
panic(err) | |
} | |
} | |
} | |
func main() { | |
// TODO: invalidate | |
options := ec2.Options{ | |
Region: "eu-north-1", | |
Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("xxx", "xxx", "")), | |
} | |
client := ec2.New(options) | |
DescribeSecurityGroups(client) | |
CreateLaunchTemplate(client) | |
first := DescribeInstanceTypes(client, "") | |
second := DescribeInstanceTypes(client, first) | |
DescribeInstanceTypes(client, second) | |
DescribeInstanceTypes(client, first) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment