|
| 1 | +package scaleway |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "github.com/hashicorp/packer-plugin-sdk/multistep" |
| 8 | + packersdk "github.com/hashicorp/packer-plugin-sdk/packer" |
| 9 | + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" |
| 10 | + "github.com/scaleway/scaleway-sdk-go/scw" |
| 11 | +) |
| 12 | + |
| 13 | +type stepCreatePrivateNICs struct{} |
| 14 | + |
| 15 | +func (s *stepCreatePrivateNICs) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { |
| 16 | + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) |
| 17 | + ui := state.Get("ui").(packersdk.Ui) |
| 18 | + c := state.Get("config").(*Config) |
| 19 | + serverID := state.Get("server_id").(string) |
| 20 | + |
| 21 | + if len(c.PrivateNetworkIDs) == 0 { |
| 22 | + return multistep.ActionContinue |
| 23 | + } |
| 24 | + |
| 25 | + for _, pnID := range c.PrivateNetworkIDs { |
| 26 | + ui.Say(fmt.Sprintf("Attaching private network %s...", pnID)) |
| 27 | + |
| 28 | + nicResp, err := instanceAPI.CreatePrivateNIC(&instance.CreatePrivateNICRequest{ |
| 29 | + Zone: scw.Zone(c.Zone), |
| 30 | + ServerID: serverID, |
| 31 | + PrivateNetworkID: pnID, |
| 32 | + }, scw.WithContext(ctx)) |
| 33 | + if err != nil { |
| 34 | + return putErrorAndHalt(state, ui, fmt.Errorf("error attaching private network %s: %w", pnID, err)) |
| 35 | + } |
| 36 | + |
| 37 | + _, err = instanceAPI.WaitForPrivateNIC(&instance.WaitForPrivateNICRequest{ |
| 38 | + ServerID: serverID, |
| 39 | + PrivateNicID: nicResp.PrivateNic.ID, |
| 40 | + Zone: scw.Zone(c.Zone), |
| 41 | + }, scw.WithContext(ctx)) |
| 42 | + if err != nil { |
| 43 | + return putErrorAndHalt(state, ui, fmt.Errorf("error waiting for private NIC %s: %w", nicResp.PrivateNic.ID, err)) |
| 44 | + } |
| 45 | + |
| 46 | + ui.Say(fmt.Sprintf("Private network %s attached successfully", pnID)) |
| 47 | + } |
| 48 | + |
| 49 | + return multistep.ActionContinue |
| 50 | +} |
| 51 | + |
| 52 | +func (s *stepCreatePrivateNICs) Cleanup(_ multistep.StateBag) { |
| 53 | + // Private NICs are automatically removed when the server is deleted. |
| 54 | +} |
0 commit comments