Home > Backend Development > Golang > How do I change the instance type in an EC2 launch template using the AWS SDK?

How do I change the instance type in an EC2 launch template using the AWS SDK?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-05 23:33:12
forward
1042 people have browsed it

如何使用 AWS SDK 更改 EC2 启动模板中的实例类型?

Question content

I want to change something in the launch template, such as the instance type. This means creating a new version while doing so.

I have browsed the SDK documentation for Go and Python. Neither seems to have parameters that allow me to achieve the same goal.

I am referring to these: Go functions, Python functions

Please help me...


Correct answer


ec2 Launch templates are immutable. If you need to modify the current launch template version, you must create a new version.

The following is an example of using AWS SDK v2 to create a new version and set it as the default version.

Install these two packages:

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

Assuming you created an aws configuration:

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)
}
Copy after login

The above is the detailed content of How do I change the instance type in an EC2 launch template using the AWS SDK?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template