Skip to content

Commit

Permalink
Simplify implementation for getting primary IP by name or ID
Browse files Browse the repository at this point in the history
  • Loading branch information
sjagoe committed Jan 9, 2024
1 parent 11fb87e commit 71101ac
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 19 deletions.
24 changes: 7 additions & 17 deletions builder/hcloud/step_create_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"os"
"sort"
"strconv"
"strings"

"github.com/hashicorp/packer-plugin-sdk/multistep"
Expand Down Expand Up @@ -273,26 +272,17 @@ func getImageWithSelectors(ctx context.Context, client *hcloud.Client, c *Config
}

func getPrimaryIP(ctx context.Context, client *hcloud.Client, publicIP string) (*hcloud.PrimaryIP, string, error) {
var hcloudPublicIP *hcloud.PrimaryIP
publicIPID, err := strconv.ParseInt(publicIP, 10, 64)
if err == nil {
hcloudPublicIP, _, err = client.PrimaryIP.GetByID(ctx, publicIPID)
if err != nil {
return nil, fmt.Sprintf("Could not fetch primary ip with ID %d", publicIPID), err
}
} else {
hcloudPublicIP, _, err = client.PrimaryIP.GetByName(ctx, publicIP)
hcloudPublicIP, _, err := client.PrimaryIP.Get(ctx, publicIP)
if err != nil {
return nil, fmt.Sprintf("Could not fetch primary ip '%s'", publicIP), err
}
if hcloudPublicIP == nil {
hcloudPublicIP, _, err = client.PrimaryIP.GetByIP(ctx, publicIP)
if err != nil {
return nil, fmt.Sprintf("Could not fetch primary ip '%s'", publicIP), err
}
if hcloudPublicIP == nil {
hcloudPublicIP, _, err = client.PrimaryIP.GetByIP(ctx, publicIP)
if err != nil {
return nil, fmt.Sprintf("Could not fetch primary ip '%s'", publicIP), err
}
if hcloudPublicIP == nil {
return nil, "", fmt.Errorf("Could not find primary ip '%s'", publicIP)
}
return nil, "", fmt.Errorf("Could not find primary ip '%s'", publicIP)
}
}
return hcloudPublicIP, "", nil
Expand Down
4 changes: 2 additions & 2 deletions builder/hcloud/step_create_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ func TestStepCreateServer(t *testing.T) {
err, ok := state.Get(StateError).(error)
assert.True(t, ok)
assert.NotNil(t, err)
assert.Regexp(t, "Could not fetch primary ip with ID .*", err.Error())
assert.Regexp(t, "Could not fetch primary ip .*", err.Error())
},
},
{

Check failure on line 401 in builder/hcloud/step_create_server_test.go

View workflow job for this annotation

GitHub Actions / lint

401-467 lines are duplicate of `builder/hcloud/step_create_server_test.go:120-186` (dupl)
Expand Down Expand Up @@ -759,7 +759,7 @@ func TestStepCreateServer(t *testing.T) {
err, ok := state.Get(StateError).(error)
assert.True(t, ok)
assert.NotNil(t, err)
assert.Regexp(t, "Could not fetch primary ip with ID .*", err.Error())
assert.Regexp(t, "Could not fetch primary ip .*", err.Error())
},
},
})
Expand Down

0 comments on commit 71101ac

Please sign in to comment.