Skip to content

Instantly share code, notes, and snippets.

@l50
Last active October 3, 2020 00:36
Show Gist options
  • Save l50/88c09169ab7d21e7ce715a18741db26c to your computer and use it in GitHub Desktop.
Save l50/88c09169ab7d21e7ce715a18741db26c to your computer and use it in GitHub Desktop.
Ec2 Creation with Lambda via Golang
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-lambda-go/lambda"
"fmt"
"os"
"log"
)
func createInstance() {
// Get credentials from ~/.aws/credentials
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
// Create EC2 service client
svc := ec2.New(sess)
// Specify the details of the instance that you want to create
runResult, err := svc.RunInstances(&ec2.RunInstancesInput{
ImageId: aws.String(os.Getenv("AMI")),
InstanceType: aws.String(os.Getenv("INSTANCE_TYPE")),
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
SecurityGroupIds: aws.StringSlice([]string{os.Getenv("SECURITY_GROUP")}),
KeyName: aws.String(os.Getenv("KEYNAME")),
SubnetId: aws.String(os.Getenv("SUBNET_ID")),
})
if err != nil {
fmt.Println("Could not create instance", err)
return
}
fmt.Println("Created instance", *runResult.Instances[0].InstanceId)
// Add tags to the created instance
_, errtag := svc.CreateTags(&ec2.CreateTagsInput{
Resources: []*string{runResult.Instances[0].InstanceId},
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String("GoInstance"),
},
},
})
if errtag != nil {
log.Println("Could not create tags for instance", runResult.Instances[0].InstanceId, errtag)
return
}
fmt.Println("Successfully tagged instance")
}
func main() {
lambda.Start(createInstance)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment