|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: MPL-2.0 |
| 3 | + |
| 4 | +package cvm |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + |
| 10 | + "github.com/hashicorp/packer-plugin-sdk/multistep" |
| 11 | + cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312" |
| 12 | +) |
| 13 | + |
| 14 | +type stepCheckSourceImageFamily struct { |
| 15 | + sourceImageId string |
| 16 | + sourceImageName string |
| 17 | +} |
| 18 | + |
| 19 | +func (s *stepCheckSourceImageFamily) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { |
| 20 | + if s.sourceImageId != "" || s.sourceImageName != "" { |
| 21 | + return multistep.ActionContinue |
| 22 | + } |
| 23 | + config := state.Get("config").(*Config) |
| 24 | + client := state.Get("cvm_client").(*cvm.Client) |
| 25 | + |
| 26 | + Say(state, config.SourceImageFamily, "Try to check the source image and get the latest valid image of the image family") |
| 27 | + |
| 28 | + req := cvm.NewDescribeImageFromFamilyRequest() |
| 29 | + req.ImageFamily = &config.SourceImageFamily |
| 30 | + |
| 31 | + var resp *cvm.DescribeImageFromFamilyResponse |
| 32 | + err := Retry(ctx, func(ctx context.Context) error { |
| 33 | + var err error |
| 34 | + resp, err = client.DescribeImageFromFamily(req) |
| 35 | + return err |
| 36 | + }) |
| 37 | + if err != nil { |
| 38 | + return Halt(state, err, "Failed to get source image info from the image family") |
| 39 | + } |
| 40 | + |
| 41 | + if resp != nil && resp.Response != nil && resp.Response.Image != nil { |
| 42 | + image := resp.Response.Image |
| 43 | + if image.ImageId != nil && !*image.ImageDeprecated { |
| 44 | + state.Put("source_image", image) |
| 45 | + Message(state, fmt.Sprintf("Get the latest image from the image family, id: %v", *image.ImageId), "Image found") |
| 46 | + return multistep.ActionContinue |
| 47 | + } |
| 48 | + } else { |
| 49 | + return Halt(state, fmt.Errorf("failed to get source image: %v", resp.ToJsonString()), "No image family found") |
| 50 | + } |
| 51 | + |
| 52 | + return Halt(state, fmt.Errorf("No image found under current instance_type(%s) restriction", config.InstanceType), "") |
| 53 | +} |
| 54 | + |
| 55 | +func (s *stepCheckSourceImageFamily) Cleanup(bag multistep.StateBag) {} |
0 commit comments