Home > Software engineering >  How to change instance type in EC2 Launch Template using AWS SDK?
How to change instance type in EC2 Launch Template using AWS SDK?

Time:12-02

I'm looking to change certain things in the launch template e.g. the instance type. Which means creating a new version while doing so.

I have gone through the SDK documentation for both Go and Python. Neither seem to have the paramenters that'd let me acheive the same.

I'm refering to these: Go's function, Python's function

Please help me out...

CodePudding user response:

EC2 launch template is immutable. You must create a new version if you need to modify the current launch template version.

Here is an example of creating a new version and then making it the default version using AWS SDK v2.

Install these two packages:

"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"

Assuming you created the AWS config:

func createLaunchTemplateVersion(cfg aws.Config) {
    ec2client := ec2.NewFromConfig(cfg)
    template := ec2types.RequestLaunchTemplateData{
        InstanceType: ec2types.InstanceTypeT2Medium}
    createParams := ec2.CreateLaunchTemplateVersionInput{
        LaunchTemplateData: &template,
        LaunchTemplateName: aws.String("MyTemplate"),
        SourceVersion:      aws.String("1"),
    }
    outputCreate, err := ec2client.CreateLaunchTemplateVersion(context.Background(), &createParams)
    if err != nil {
        log.Fatal(err)
    }
    if outputCreate.Warning != nil {
        log.Fatalf("%v\n", outputCreate.Warning.Errors)
    }
    // set the new launch type version as the default version
    modifyParams := ec2.ModifyLaunchTemplateInput{
        DefaultVersion:     aws.String(strconv.FormatInt(*outputCreate.LaunchTemplateVersion.VersionNumber, 10)),
        LaunchTemplateName: outputCreate.LaunchTemplateVersion.LaunchTemplateName,
    }
    outputModify, err := ec2client.ModifyLaunchTemplate(context.Background(), &modifyParams)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("default version %d\n", *outputModify.LaunchTemplate.DefaultVersionNumber)
}
  • Related