network

package
v1.57.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AddRouteCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "add-route --destination <destination> --gateway <ip> <network>",
			Short:                 "Add a route to a Network",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("destination", net.IPNet{}, "Destination Network or host (required)")
		_ = cmd.MarkFlagRequired("destination")

		cmd.Flags().IP("gateway", net.IP{}, "Gateway IP address (required)")
		_ = cmd.MarkFlagRequired("gateway")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]

		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		opts := hcloud.NetworkAddRouteOpts{
			Route: hcloud.NetworkRoute{
				Gateway:     gateway,
				Destination: &destination,
			},
		}
		action, _, err := s.Client().Network().AddRoute(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}
		cmd.Printf("Route added to Network %d\n", network.ID)

		return nil
	},
}
View Source
var AddSubnetCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "add-subnet [options] --type <cloud|server|vswitch> --network-zone <zone> <network>",
			Short:                 "Add a subnet to a Network",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().String("type", "", "Type of subnet (required)")
		_ = cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("cloud", "server", "vswitch"))
		_ = cmd.MarkFlagRequired("type")

		cmd.Flags().String("network-zone", "", "Name of Network zone (required)")
		_ = cmd.RegisterFlagCompletionFunc("network-zone", cmpl.SuggestCandidatesF(client.Location().NetworkZones))
		_ = cmd.MarkFlagRequired("network-zone")

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Range to allocate IPs from")

		cmd.Flags().Int64("vswitch-id", 0, "ID of the vSwitch")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		subnetType, _ := cmd.Flags().GetString("type")
		networkZone, _ := cmd.Flags().GetString("network-zone")
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		vSwitchID, _ := cmd.Flags().GetInt64("vswitch-id")
		idOrName := args[0]

		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}
		subnet := hcloud.NetworkSubnet{
			Type:        hcloud.NetworkSubnetType(subnetType),
			NetworkZone: hcloud.NetworkZone(networkZone),
		}

		if ipRange.IP != nil && ipRange.Mask != nil {
			subnet.IPRange = &ipRange
		}
		if subnetType == "vswitch" {
			subnet.VSwitchID = vSwitchID
		}

		opts := hcloud.NetworkAddSubnetOpts{
			Subnet: subnet,
		}
		action, _, err := s.Client().Network().AddSubnet(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}
		cmd.Printf("Subnet added to Network %d\n", network.ID)

		return nil
	},
}
View Source
var ChangeIPRangeCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "change-ip-range --ip-range <ip-range> <network>",
			Short:                 "Change the IP range of a Network",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "New IP range (required)")
		_ = cmd.MarkFlagRequired("ip-range")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		opts := hcloud.NetworkChangeIPRangeOpts{
			IPRange: &ipRange,
		}

		action, _, err := s.Client().Network().ChangeIPRange(s, network, opts)
		if err != nil {
			return err
		}

		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}
		cmd.Printf("IP range of Network %d changed\n", network.ID)
		return nil
	},
}
View Source
var CreateCmd = base.CreateCmd[*hcloud.Network]{
	BaseCobraCommand: func(hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "create [options] --name <name> --ip-range <ip-range>",
			Short: "Create a Network",
		}

		cmd.Flags().String("name", "", "Network name (required)")
		_ = cmd.MarkFlagRequired("name")

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Network IP range (required)")
		_ = cmd.MarkFlagRequired("ip-range")

		cmd.Flags().Bool("expose-routes-to-vswitch", false, "Expose routes from this Network to the vSwitch connection. It only takes effect if a vSwitch connection is active. (true, false)")

		cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")

		cmd.Flags().StringSlice("enable-protection", []string{}, "Enable protection (delete) (default: none)")
		_ = cmd.RegisterFlagCompletionFunc("enable-protection", cmpl.SuggestCandidates("delete"))
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, _ []string) (*hcloud.Network, any, error) {
		name, _ := cmd.Flags().GetString("name")
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		labels, _ := cmd.Flags().GetStringToString("label")
		exposeRoutesToVSwitch, _ := cmd.Flags().GetBool("expose-routes-to-vswitch")
		protection, _ := cmd.Flags().GetStringSlice("enable-protection")

		protectionOpts, err := getChangeProtectionOpts(true, protection)
		if err != nil {
			return nil, nil, err
		}

		createOpts := hcloud.NetworkCreateOpts{
			Name:                  name,
			IPRange:               &ipRange,
			Labels:                labels,
			ExposeRoutesToVSwitch: exposeRoutesToVSwitch,
		}

		network, _, err := s.Client().Network().Create(s, createOpts)
		if err != nil {
			return nil, nil, err
		}

		cmd.Printf("Network %d created\n", network.ID)

		if err := changeProtection(s, cmd, network, true, protectionOpts); err != nil {
			return nil, nil, err
		}

		network, _, err = s.Client().Network().GetByID(s, network.ID)
		if err != nil {
			return nil, nil, err
		}
		if network == nil {
			return nil, nil, fmt.Errorf("Network not found: %d", network.ID)
		}

		return network, util.Wrap("network", hcloud.SchemaFromNetwork(network)), nil
	},
}
View Source
var DeleteCmd = base.DeleteCmd{
	ResourceNameSingular: "Network",
	ResourceNamePlural:   "Networks",
	ShortDescription:     "Delete a network",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().Network().Get(s, idOrName)
	},
	Delete: func(s state.State, _ *cobra.Command, resource interface{}) (*hcloud.Action, error) {
		network := resource.(*hcloud.Network)
		_, err := s.Client().Network().Delete(s, network)
		return nil, err
	},
}
View Source
var DescribeCmd = base.DescribeCmd[*hcloud.Network]{
	ResourceNameSingular: "Network",
	ShortDescription:     "Describe a Network",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.Network, any, error) {
		n, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return nil, nil, err
		}
		return n, hcloud.SchemaFromNetwork(n), nil
	},
	PrintText: func(_ state.State, _ *cobra.Command, out io.Writer, network *hcloud.Network) error {
		fmt.Fprintf(out, "ID:\t%d\n", network.ID)
		fmt.Fprintf(out, "Name:\t%s\n", network.Name)
		fmt.Fprintf(out, "Created:\t%s (%s)\n", util.Datetime(network.Created), humanize.Time(network.Created))
		fmt.Fprintf(out, "IP Range:\t%s\n", network.IPRange.String())
		fmt.Fprintf(out, "Expose Routes to vSwitch:\t%s\n", util.YesNo(network.ExposeRoutesToVSwitch))

		fmt.Fprintln(out)
		fmt.Fprintf(out, "Subnets:\n")
		if len(network.Subnets) == 0 {
			fmt.Fprintf(out, "  No subnets\n")
		} else {
			for i, subnet := range network.Subnets {
				if i > 0 {
					fmt.Fprintln(out)
				}
				fmt.Fprintf(out, "  - Type:\t%s\n", subnet.Type)
				fmt.Fprintf(out, "    Network Zone:\t%s\n", subnet.NetworkZone)
				fmt.Fprintf(out, "    IP Range:\t%s\n", subnet.IPRange.String())
				fmt.Fprintf(out, "    Gateway:\t%s\n", subnet.Gateway.String())
				if subnet.Type == hcloud.NetworkSubnetTypeVSwitch {
					fmt.Fprintf(out, "    vSwitch ID:\t%d\n", subnet.VSwitchID)
				}
			}
		}

		fmt.Fprintln(out)
		fmt.Fprintf(out, "Routes:\n")
		if len(network.Routes) == 0 {
			fmt.Fprintf(out, "  No routes\n")
		} else {
			for _, route := range network.Routes {
				fmt.Fprintf(out, "  - Destination:\t%s\n", route.Destination.String())
				fmt.Fprintf(out, "    Gateway:\t%s\n", route.Gateway.String())
			}
		}

		fmt.Fprintln(out)
		fmt.Fprintf(out, "Protection:\n")
		fmt.Fprintf(out, "  Delete:\t%s\n", util.YesNo(network.Protection.Delete))

		fmt.Fprintln(out)
		util.DescribeLabels(out, network.Labels, "")
		return nil
	},
}

DescribeCmd defines a command for describing a network.

View Source
var DisableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "disable-protection <network> delete",
			Args:  util.ValidateLenient,
			Short: "Disable resource protection for a network",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.Network().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		opts, err := getChangeProtectionOpts(false, args[1:])
		if err != nil {
			return err
		}

		return changeProtection(s, cmd, network, false, opts)
	},
}
View Source
var EnableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "enable-protection <network> delete",
			Args:  util.ValidateLenient,
			Short: "Enable resource protection for a network",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.Network().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		opts, err := getChangeProtectionOpts(true, args[1:])
		if err != nil {
			return err
		}

		return changeProtection(s, cmd, network, true, opts)
	},
}
View Source
var ExposeRoutesToVSwitchCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "expose-routes-to-vswitch [--disable] <network>",
			Short:                 "Expose routes to connected vSwitch",
			Long:                  "Enabling this will expose routes to the connected vSwitch. Set the --disable flag to remove the exposed routes.",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().Bool("disable", false, "Remove any exposed routes from the connected vSwitch")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		disable, _ := cmd.Flags().GetBool("disable")
		opts := hcloud.NetworkUpdateOpts{
			ExposeRoutesToVSwitch: hcloud.Ptr(!disable),
		}

		_, _, err = s.Client().Network().Update(s, network, opts)
		if err != nil {
			return err
		}

		if disable {
			cmd.Printf("Exposing routes to connected vSwitch of Network %s disabled\n", network.Name)
		} else {
			cmd.Printf("Exposing routes to connected vSwitch of Network %s enabled\n", network.Name)
		}

		return nil
	},
}
View Source
var LabelCmds = base.LabelCmds[*hcloud.Network]{
	ResourceNameSingular:   "Network",
	ShortDescriptionAdd:    "Add a label to a Network",
	ShortDescriptionRemove: "Remove a label from a Network",
	NameSuggestions:        func(c hcapi2.Client) func() []string { return c.Network().Names },
	LabelKeySuggestions:    func(c hcapi2.Client) func(idOrName string) []string { return c.Network().LabelKeys },
	Fetch: func(s state.State, idOrName string) (*hcloud.Network, error) {
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return nil, err
		}
		if network == nil {
			return nil, fmt.Errorf("Network not found: %s", idOrName)
		}
		return network, nil
	},
	SetLabels: func(s state.State, network *hcloud.Network, labels map[string]string) error {
		opts := hcloud.NetworkUpdateOpts{
			Labels: labels,
		}
		_, _, err := s.Client().Network().Update(s, network, opts)
		return err
	},
	GetLabels: func(network *hcloud.Network) map[string]string {
		return network.Labels
	},
	GetIDOrName: func(network *hcloud.Network) string {
		return strconv.FormatInt(network.ID, 10)
	},
}
View Source
var ListCmd = &base.ListCmd[*hcloud.Network, schema.Network]{
	ResourceNamePlural: "Networks",
	JSONKeyGetByName:   "networks",
	DefaultColumns:     []string{"id", "name", "ip_range", "servers", "age"},
	SortOption:         nil,

	Fetch: func(s state.State, _ *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]*hcloud.Network, error) {
		opts := hcloud.NetworkListOpts{ListOpts: listOpts}
		if len(sorts) > 0 {
			opts.Sort = sorts
		}
		return s.Client().Network().AllWithOpts(s, opts)
	},

	OutputTable: func(t *output.Table[*hcloud.Network], _ hcapi2.Client) {
		t.
			AddAllowedFields(&hcloud.Network{}).
			AddFieldFn("servers", func(network *hcloud.Network) string {
				serverCount := len(network.Servers)
				if serverCount == 1 {
					return fmt.Sprintf("%v server", serverCount)
				}
				return fmt.Sprintf("%v servers", serverCount)
			}).
			AddFieldFn("ip_range", func(network *hcloud.Network) string {
				return network.IPRange.String()
			}).
			AddFieldFn("labels", func(network *hcloud.Network) string {
				return util.LabelsToString(network.Labels)
			}).
			AddFieldFn("protection", func(network *hcloud.Network) string {
				var protection []string
				if network.Protection.Delete {
					protection = append(protection, "delete")
				}
				return strings.Join(protection, ", ")
			}).
			AddFieldFn("created", func(network *hcloud.Network) string {
				return util.Datetime(network.Created)
			}).
			AddFieldFn("age", func(network *hcloud.Network) string {
				return util.Age(network.Created, time.Now())
			})
	},
	Schema: hcloud.SchemaFromNetwork,
}
View Source
var RemoveRouteCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "remove-route --destination <destination> --gateway <ip> <network>",
			Short:                 "Remove a route from a Network",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("destination", net.IPNet{}, "Destination Network or host (required)")
		_ = cmd.MarkFlagRequired("destination")

		cmd.Flags().IP("gateway", net.IP{}, "Gateway IP address (required)")
		_ = cmd.MarkFlagRequired("gateway")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		opts := hcloud.NetworkDeleteRouteOpts{
			Route: hcloud.NetworkRoute{
				Gateway:     gateway,
				Destination: &destination,
			},
		}
		action, _, err := s.Client().Network().DeleteRoute(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}
		cmd.Printf("Route removed from Network %d\n", network.ID)

		return nil
	},
}
View Source
var RemoveSubnetCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "remove-subnet --ip-range <ip-range> <network>",
			Short:                 "Remove a subnet from a Network",
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Subnet IP range (required)")
		_ = cmd.MarkFlagRequired("ip-range")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("Network not found: %s", idOrName)
		}

		opts := hcloud.NetworkDeleteSubnetOpts{
			Subnet: hcloud.NetworkSubnet{
				IPRange: &ipRange,
			},
		}
		action, _, err := s.Client().Network().DeleteSubnet(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}
		cmd.Printf("Subnet %s removed from Network %d\n", ipRange.String(), network.ID)

		return nil
	},
}
View Source
var UpdateCmd = base.UpdateCmd{
	ResourceNameSingular: "Network",
	ShortDescription:     "Update a Network.\n\nTo enable or disable exposing routes to the vSwitch connection you can use the subcommand \"hcloud network expose-routes-to-vswitch\".",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().Network().Get(s, idOrName)
	},
	DefineFlags: func(cmd *cobra.Command) {
		cmd.Flags().String("name", "", "Network name")
	},
	Update: func(s state.State, _ *cobra.Command, resource interface{}, flags map[string]pflag.Value) error {
		floatingIP := resource.(*hcloud.Network)
		updOpts := hcloud.NetworkUpdateOpts{
			Name: flags["name"].String(),
		}
		_, _, err := s.Client().Network().Update(s, floatingIP, updOpts)
		if err != nil {
			return err
		}
		return nil
	},
}

Functions

func NewCommand

func NewCommand(s state.State) *cobra.Command

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL