Skip to content

feat(baremetal): add support for add flexible ip #3670

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
🎲🎲🎲 EXIT CODE: 0 🎲🎲🎲
🟥🟥🟥 STDERR️️ 🟥🟥🟥️
Create and attach a new flexible IP to a server

USAGE:
scw baremetal server add-flexible-ip <server-id ...> [arg=value ...]

ARGS:
server-id ID of the server to which the newly created flexible IP will be attached.
[description] Flexible IP description (max. of 255 characters)
[ip-type] Define whether the flexible IP is an IPv4 or IPv6 (IPv4 | IPv6)
[tags.{index}] Tags to associate to the flexible IP
[zone=fr-par-1] Zone to target. If none is passed will use default zone from the config (fr-par-1 | fr-par-2 | nl-ams-1)

FLAGS:
-h, --help help for add-flexible-ip

GLOBAL FLAGS:
-c, --config string The path to the config file
-D, --debug Enable debug mode
-o, --output string Output format: json or human, see 'scw help output' for more info (default "human")
-p, --profile string The config profile to use
29 changes: 16 additions & 13 deletions cmd/scw/testdata/test-all-usage-baremetal-server-usage.golden
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,24 @@ USAGE:
scw baremetal server <command>

AVAILABLE COMMANDS:
create Create an Elastic Metal server
delete Delete an Elastic Metal server
get Get a specific Elastic Metal server
get-metrics Return server metrics
install Install an Elastic Metal server
list List Elastic Metal servers for an Organization
list-events List server events
reboot Reboot an Elastic Metal server
start Start an Elastic Metal server
stop Stop an Elastic Metal server
update Update an Elastic Metal server
update-ip Update IP
create Create an Elastic Metal server
delete Delete an Elastic Metal server
get Get a specific Elastic Metal server
get-metrics Return server metrics
install Install an Elastic Metal server
list List Elastic Metal servers for an Organization
list-events List server events
reboot Reboot an Elastic Metal server
start Start an Elastic Metal server
stop Stop an Elastic Metal server
update Update an Elastic Metal server
update-ip Update IP

UTILITY COMMANDS:
add-flexible-ip Attach a new flexible IP to a server

WORKFLOW COMMANDS:
wait Wait for a server to reach a stable state (delivery and installation)
wait Wait for a server to reach a stable state (delivery and installation)

FLAGS:
-h, --help help for server
Expand Down
24 changes: 24 additions & 0 deletions docs/commands/baremetal.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Elastic Metal API.
- [List the Private Networks of a server](#list-the-private-networks-of-a-server)
- [Set multiple Private Networks on a server](#set-multiple-private-networks-on-a-server)
- [Server management commands](#server-management-commands)
- [Attach a new flexible IP to a server](#attach-a-new-flexible-ip-to-a-server)
- [Create an Elastic Metal server](#create-an-elastic-metal-server)
- [Delete an Elastic Metal server](#delete-an-elastic-metal-server)
- [Get a specific Elastic Metal server](#get-a-specific-elastic-metal-server)
Expand Down Expand Up @@ -478,6 +479,29 @@ scw baremetal private-network set [arg=value ...]
A server is a denomination of a type of instances provided by Scaleway.


### Attach a new flexible IP to a server

Create and attach a new flexible IP to a server

**Usage:**

```
scw baremetal server add-flexible-ip <server-id ...> [arg=value ...]
```


**Args:**

| Name | | Description |
|------|---|-------------|
| server-id | Required | ID of the server to which the newly created flexible IP will be attached. |
| description | | Flexible IP description (max. of 255 characters) |
| ip-type | One of: `IPv4`, `IPv6` | Define whether the flexible IP is an IPv4 or IPv6 |
| tags.{index} | | Tags to associate to the flexible IP |
| zone | Default: `fr-par-1`<br />One of: `fr-par-1`, `fr-par-2`, `nl-ams-1` | Zone to target. If none is passed will use default zone from the config |



### Create an Elastic Metal server

Create a new Elastic Metal server. Once the server is created, proceed with the [installation of an OS](#post-3e949e).
Expand Down
2 changes: 2 additions & 0 deletions internal/interactive/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package interactive

import (
"bytes"
"context"
"fmt"
"os"
Expand Down Expand Up @@ -78,6 +79,7 @@ func (m *ListPrompt) Execute(ctx context.Context) (int, error) {
ctx: ctx,
defaultReader: os.Stdin,
}))
opts = append(opts, tea.WithOutput(bytes.NewBuffer([]byte{})))
}

p := tea.NewProgram(m, opts...)
Expand Down
1 change: 1 addition & 0 deletions internal/namespaces/baremetal/v1/custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ func GetCommands() *core.Commands {

cmds.Merge(core.NewCommands(
serverWaitCommand(),
serverAddFlexibleIP(),
))

human.RegisterMarshalerFunc(baremetal.ServerPingStatus(""), human.EnumMarshalFunc(serverPingStatusMarshalSpecs))
Expand Down
112 changes: 112 additions & 0 deletions internal/namespaces/baremetal/v1/custom_server_fip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package baremetal

import (
"context"
"fmt"
"reflect"

"github.com/scaleway/scaleway-cli/v2/internal/core"
flexibleip "github.com/scaleway/scaleway-cli/v2/internal/namespaces/flexibleip/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/api/baremetal/v1"
fip "github.com/scaleway/scaleway-sdk-go/api/flexibleip/v1alpha1"
"github.com/scaleway/scaleway-sdk-go/scw"
)

type serverAddFlexibleIPRequest struct {
ServerID string
Description string
IPType string
Tags []string
Zone scw.Zone
}

func serverAddFlexibleIP() *core.Command {
return &core.Command{
Short: "Attach a new flexible IP to a server",
Long: "Create and attach a new flexible IP to a server",
Namespace: "baremetal",
Resource: "server",
Verb: "add-flexible-ip",
Groups: []string{"utility"},
ArgsType: reflect.TypeOf(serverAddFlexibleIPRequest{}),
ArgSpecs: core.ArgSpecs{
{
Name: "server-id",
Short: `ID of the server to which the newly created flexible IP will be attached.`,
Required: true,
Deprecated: false,
Positional: true,
},
{
Name: "description",
Short: `Flexible IP description (max. of 255 characters)`,
Required: false,
Deprecated: false,
Positional: false,
},
{
Name: "ip-type",
Short: `Define whether the flexible IP is an IPv4 or IPv6`,
Required: false,
Deprecated: false,
Positional: false,
EnumValues: ipTypeOption,
ValidateFunc: func(_ *core.ArgSpec, value interface{}) error {
if value == "IPv4" || value == "IPv6" || value == "" {
return nil
}
return &core.CliError{
Err: fmt.Errorf("error looks like the IP type isn't correct"),
Hint: "Two type available : IPv6 or IPv4",
}
},
},
{
Name: "tags.{index}",
Short: `Tags to associate to the flexible IP`,
Required: false,
Deprecated: false,
Positional: false,
},
core.ZoneArgSpec(scw.ZoneFrPar1, scw.ZoneFrPar2, scw.ZoneNlAms1),
},
Run: func(ctx context.Context, argsI interface{}) (interface{}, error) {
request := argsI.(*serverAddFlexibleIPRequest)
client := core.ExtractClient(ctx)
api := baremetal.NewAPI(client)
server, err := api.GetServer(&baremetal.GetServerRequest{
Zone: request.Zone,
ServerID: request.ServerID,
}, scw.WithContext(ctx))
if err != nil {
return nil, err
}
args := request
if args.IPType == "" {
args, err = promptIPFlexibleServer(ctx, request)
}
if err != nil {
return nil, err
}
apiFip := fip.NewAPI(client)
IsIPv6 := args.IPType == "IPv6"
flexibleIP, err := apiFip.CreateFlexibleIP(&fip.CreateFlexibleIPRequest{
ServerID: &server.ID,
Zone: server.Zone,
ProjectID: server.ProjectID,
Description: args.Description,
Tags: args.Tags,
IsIPv6: IsIPv6,
})
if err != nil {
return nil, err
}
return apiFip.WaitForFlexibleIP(&fip.WaitForFlexibleIPRequest{
FipID: flexibleIP.ID,
Zone: flexibleIP.Zone,
Timeout: scw.TimeDurationPtr(flexibleip.FlexibleIPTimeout),
RetryInterval: core.DefaultRetryInterval,
})
},
}
}
43 changes: 43 additions & 0 deletions internal/namespaces/baremetal/v1/custom_server_fip_prompt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package baremetal

import (
"context"
"fmt"

"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/terminal"
)

var ipTypeOption = []string{"IPv4", "IPv6"}

func promptIPFlexibleServer(ctx context.Context, req *serverAddFlexibleIPRequest) (*serverAddFlexibleIPRequest, error) {
if !interactive.IsInteractive {
return nil, &core.CliError{
Err: fmt.Errorf("failed to create and attach a new flexible IP"),
Hint: "Missing argument 'ip-type'",
}
}
var err error
quitMessage := terminal.Style("Type Ctrl+c or q to quit", color.FgHiBlue, color.Bold)
fmt.Println(quitMessage)
req.IPType, err = promptChooseIPType(ctx)
if err != nil {
return nil, err
}
return req, nil
}

func promptChooseIPType(ctx context.Context) (string, error) {
prompt := interactive.ListPrompt{
Prompt: "Choose your internet protocol",
Choices: ipTypeOption,
DefaultIndex: 0,
}
ipTypeIndex, err := prompt.Execute(ctx)
if err != nil {
return "", err
}
return ipTypeOption[ipTypeIndex], nil
}
54 changes: 54 additions & 0 deletions internal/namespaces/baremetal/v1/custom_server_fip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package baremetal_test

import (
"testing"

"github.com/scaleway/scaleway-cli/v2/internal/core"
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-cli/v2/internal/namespaces/baremetal/v1"
flexibleip "github.com/scaleway/scaleway-cli/v2/internal/namespaces/flexibleip/v1alpha1"
)

func Test_CreateFlexibleIPInteractive(t *testing.T) {
promptResponse := []string{
`" "`,
}
interactive.IsInteractive = true
cmds := baremetal.GetCommands()
cmds.Merge(flexibleip.GetCommands())
t.Run("Simple Interactive", core.Test(&core.TestConfig{
Commands: cmds,
BeforeFunc: core.BeforeFuncCombine(
createServerAndWaitDefault("Server"),
),
Cmd: "scw baremetal server add-flexible-ip {{ .Server.ID }}",
Check: core.TestCheckCombine(
core.TestCheckGolden(),
),
AfterFunc: core.AfterFuncCombine(
deleteServerDefault("Server"),
core.ExecAfterCmd("scw fip ip delete {{ .CmdResult.ID }}"),
),
PromptResponseMocks: promptResponse,
}))
}

func Test_CreateFlexibleIP(t *testing.T) {
interactive.IsInteractive = false
cmds := baremetal.GetCommands()
cmds.Merge(flexibleip.GetCommands())
t.Run("Simple", core.Test(&core.TestConfig{
Commands: cmds,
BeforeFunc: core.BeforeFuncCombine(
createServerAndWaitDefault("Server"),
),
Cmd: "scw baremetal server add-flexible-ip {{ .Server.ID }} ip-type=IPv4",
Check: core.TestCheckCombine(
core.TestCheckGolden(),
),
AfterFunc: core.AfterFuncCombine(
deleteServerDefault("Server"),
core.ExecAfterCmd("scw fip ip delete {{ .CmdResult.ID }}"),
),
}))
}
14 changes: 12 additions & 2 deletions internal/namespaces/baremetal/v1/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package baremetal_test

import (
"fmt"

"github.com/scaleway/scaleway-cli/v2/internal/core"
)

Expand All @@ -10,6 +12,10 @@ func createServerAndWait(metaKey string) core.BeforeFunc {
return core.ExecStoreBeforeCmd(metaKey, "scw baremetal server create zone=nl-ams-1 type=GP-BM2-S -w")
}

func createServerAndWaitDefault(metaKey string) core.BeforeFunc {
return core.ExecStoreBeforeCmd(metaKey, "scw baremetal server create type=EM-B112X-SSD -w")
}

func createServer(metaKey string) core.BeforeFunc {
return core.ExecStoreBeforeCmd(metaKey, "scw baremetal server create zone=nl-ams-1 type=GP-BM2-S")
}
Expand All @@ -19,7 +25,11 @@ func createServer(metaKey string) core.BeforeFunc {
//
//nolint:unparam
func deleteServer(metaKey string) core.AfterFunc {
return core.ExecAfterCmd("scw baremetal server delete zone=nl-ams-1 {{ ." + metaKey + ".ID }}")
return core.ExecAfterCmd(fmt.Sprintf("scw baremetal server delete zone=nl-ams-1 {{ ." + metaKey + ".ID }}"))
}

func deleteServerDefault(metaKey string) core.AfterFunc {
return core.ExecAfterCmd(fmt.Sprintf("scw baremetal server delete {{ ." + metaKey + ".ID }}"))
}

// add an ssh key with a given meta key
Expand All @@ -34,5 +44,5 @@ func addSSH(metaKey string, key string) core.BeforeFunc {

// delete an ssh key with a given meta key
func deleteSSH(metaKey string) core.AfterFunc {
return core.ExecAfterCmd("scw iam ssh-key delete {{ ." + metaKey + ".ID }}")
return core.ExecAfterCmd(fmt.Sprintf("scw iam ssh-key delete {{ ." + metaKey + ".ID }}"))
}
Loading