primaryip

package
v1.64.0 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AssignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "assign --server <server> <primary-ip>",
			Short: "Assign a Primary IP to an assignee (usually a Server)",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names(true, false, nil)),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("server", "", "Name or ID of the Server")
		_ = cmd.RegisterFlagCompletionFunc("server", cmpl.SuggestCandidatesF(client.Server().Names))
		_ = cmd.MarkFlagRequired("server")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		serverIDOrName, _ := cmd.Flags().GetString("server")

		server, _, err := s.Client().Server().Get(s, serverIDOrName)
		if err != nil {
			return err
		}
		if server == nil {
			return fmt.Errorf("Server not found: %s", serverIDOrName)
		}
		opts := hcloud.PrimaryIPAssignOpts{
			ID:           primaryIP.ID,
			AssigneeType: "server",
			AssigneeID:   server.ID,
		}

		action, _, err := s.Client().PrimaryIP().Assign(s, opts)
		if err != nil {
			return err
		}

		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}

		cmd.Printf("Primary IP %d assigned to %s %d\n", opts.ID, cases.Title(language.English).String(opts.AssigneeType), opts.AssigneeID)
		return nil
	},
}
View Source
var ChangeProtectionCmds = base.ChangeProtectionCmds[*hcloud.PrimaryIP, hcloud.PrimaryIPChangeProtectionOpts]{
	ResourceNameSingular: "Primary IP",

	NameSuggestions: func(client hcapi2.Client) func() []string {
		return client.PrimaryIP().Names(false, false, nil)
	},

	ProtectionLevelsOptional: true,
	ProtectionLevels: map[string]func(opts *hcloud.PrimaryIPChangeProtectionOpts, value bool){
		"delete": func(opts *hcloud.PrimaryIPChangeProtectionOpts, value bool) {
			opts.Delete = value
		},
	},

	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.PrimaryIP, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},

	ChangeProtectionFunction: func(s state.State, primaryIP *hcloud.PrimaryIP, opts hcloud.PrimaryIPChangeProtectionOpts) (*hcloud.Action, *hcloud.Response, error) {
		opts.ID = primaryIP.ID
		return s.Client().PrimaryIP().ChangeProtection(s, opts)
	},

	IDOrName: func(primaryIP *hcloud.PrimaryIP) string {
		return fmt.Sprint(primaryIP.ID)
	},
}
View Source
var CreateCmd = base.CreateCmd[*hcloud.PrimaryIP]{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "create [options] --type <ipv4|ipv6> --name <name>",
			Short: "Create a Primary IP",
			Long: `Create a Primary IP.

The --datacenter flag is deprecated. Use --location or --assignee-id instead.
See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters.

The --assignee-type flag will be required together with the --assignee-id flag. Using 
the default value (server) for the --assignee-type flag is deprecated. Consider 
explicitly setting the --assignee-type flag.

See https://docs.hetzner.cloud/changelog#2026-04-27-primary-ips-will-return-unassigned
and https://docs.hetzner.cloud/changelog#2026-04-27-primary-ips-make-assignee_type-optional.
`,
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("type", "", "Type (ipv4 or ipv6) (required)")
		_ = cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("ipv4", "ipv6"))
		_ = cmd.MarkFlagRequired("type")

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

		cmd.Flags().Int64("assignee-id", 0, "Assignee (usually a Server) to assign Primary IP to")
		cmd.Flags().String("assignee-type", "server", "Assignee Type to assign Primary IP to (default: server)")
		_ = cmd.RegisterFlagCompletionFunc("assignee-type", cmpl.SuggestCandidates("server"))

		cmd.Flags().String("location", "", "Location (ID or name) of Primary IP")
		_ = cmd.RegisterFlagCompletionFunc("location", cmpl.SuggestCandidatesF(client.Location().Names))

		cmd.Flags().String("datacenter", "", "Datacenter (name) (deprecated)")
		_ = cmd.RegisterFlagCompletionFunc("datacenter", cmpl.SuggestCandidatesF(client.Datacenter().Names))

		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"))

		cmd.Flags().Bool("auto-delete", false, "Delete Primary IP if assigned resource is deleted (true, false)")

		cmd.MarkFlagsOneRequired("assignee-id", "datacenter", "location")
		cmd.MarkFlagsMutuallyExclusive("assignee-id", "datacenter", "location")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, _ []string) (*hcloud.PrimaryIP, any, error) {
		typ, _ := cmd.Flags().GetString("type")
		name, _ := cmd.Flags().GetString("name")
		assigneeID, _ := cmd.Flags().GetInt64("assignee-id")
		assigneeType, _ := cmd.Flags().GetString("assignee-type")
		datacenter, _ := cmd.Flags().GetString("datacenter")
		locationIDOrName, _ := cmd.Flags().GetString("location")
		labels, _ := cmd.Flags().GetStringToString("label")
		protection, _ := cmd.Flags().GetStringSlice("enable-protection")
		autoDelete, _ := cmd.Flags().GetBool("auto-delete")

		protectionOpts, err := ChangeProtectionCmds.GetChangeProtectionOpts(true, protection)
		if err != nil {
			return nil, nil, err
		}

		createOpts := hcloud.PrimaryIPCreateOpts{
			Type:   hcloud.PrimaryIPType(typ),
			Name:   name,
			Labels: labels,
		}
		if assigneeID != 0 {
			createOpts.AssigneeID = &assigneeID
			if !cmd.Flags().Changed("assignee-type") {
				cmd.PrintErrln(
					"Warning: " +
						"The --assignee-type flag will be required together " +
						"with the --assignee-id flag and will no longer default " +
						"to 'server'. Consider explicitly setting the " +
						"--assignee-type flag.",
				)
			}
			createOpts.AssigneeType = assigneeType
		}
		if cmd.Flags().Changed("auto-delete") {
			createOpts.AutoDelete = &autoDelete
		}
		if cmd.Flags().Changed("location") {
			location, _, err := s.Client().Location().Get(s, locationIDOrName)
			if err != nil {
				return nil, nil, err
			}
			if location == nil {
				return nil, nil, fmt.Errorf("Location not found: %s", locationIDOrName)
			}
			createOpts.Location = location.Name
		}
		if cmd.Flags().Changed("datacenter") {
			cmd.PrintErrln("Warning: The --datacenter flag is deprecated. Use --location or --assignee-id instead.")

			parts := strings.Split(datacenter, "-")

			if len(parts) != 2 {
				return nil, nil, fmt.Errorf("Datacenter name is not valid, expected format $LOCATION-$DATACENTER, but got: %s", datacenter)
			}

			locationName := parts[0]
			createOpts.Location = locationName
		}

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

		if result.Action != nil {
			if err := s.WaitForActions(s, cmd, result.Action); err != nil {
				return nil, nil, err
			}
		}

		cmd.Printf("Primary IP %d created\n", result.PrimaryIP.ID)

		if len(protection) > 0 {
			if err := ChangeProtectionCmds.ChangeProtection(s, cmd, result.PrimaryIP, true, protectionOpts); err != nil {
				return nil, nil, err
			}
		}

		primaryIP, _, err := s.Client().PrimaryIP().GetByID(s, result.PrimaryIP.ID)
		if err != nil {
			return nil, nil, err
		}
		if primaryIP == nil {
			return nil, nil, fmt.Errorf("Primary IP not found: %d", result.PrimaryIP.ID)
		}

		return primaryIP, util.Wrap("primary_ip", hcloud.SchemaFromPrimaryIP(primaryIP)), nil
	},
	PrintResource: func(_ state.State, cmd *cobra.Command, primaryIP *hcloud.PrimaryIP) {
		cmd.Printf("IP%s: %s\n", primaryIP.Type[2:], primaryIP.IP)
	},
}
View Source
var DeleteCmd = base.DeleteCmd[*hcloud.PrimaryIP]{
	ResourceNameSingular: "Primary IP",
	ResourceNamePlural:   "Primary IPs",
	ShortDescription:     "Delete a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names(false, false, nil) },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.PrimaryIP, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	Delete: func(s state.State, _ *cobra.Command, primaryIP *hcloud.PrimaryIP) ([]*hcloud.Action, error) {
		_, err := s.Client().PrimaryIP().Delete(s, primaryIP)
		return nil, err
	},
}
View Source
var DescribeCmd = base.DescribeCmd[*hcloud.PrimaryIP]{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Describe a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names(false, false, nil) },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.PrimaryIP, any, error) {
		ip, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return nil, nil, err
		}
		return ip, hcloud.SchemaFromPrimaryIP(ip), nil
	},
	PrintText: func(s state.State, _ *cobra.Command, out io.Writer, primaryIP *hcloud.PrimaryIP) error {
		fmt.Fprintf(out, "ID:\t%d\n", primaryIP.ID)
		fmt.Fprintf(out, "Name:\t%s\n", primaryIP.Name)
		fmt.Fprintf(out, "Created:\t%s (%s)\n", util.Datetime(primaryIP.Created), humanize.Time(primaryIP.Created))
		fmt.Fprintf(out, "Type:\t%s\n", primaryIP.Type)
		fmt.Fprintf(out, "IP:\t%s\n", primaryIP.IP.String())
		fmt.Fprintf(out, "Blocked:\t%s\n", util.YesNo(primaryIP.Blocked))
		fmt.Fprintf(out, "Auto delete:\t%s\n", util.YesNo(primaryIP.AutoDelete))

		fmt.Fprintln(out)
		fmt.Fprintf(out, "Assignee:\n")
		if primaryIP.AssigneeID != 0 {
			fmt.Fprintf(out, "  ID:\t%d\n", primaryIP.AssigneeID)
			fmt.Fprintf(out, "  Type:\t%s\n", primaryIP.AssigneeType)
		} else {
			fmt.Fprintf(out, "  Not assigned\n")
		}

		fmt.Fprintln(out)
		fmt.Fprintf(out, "DNS:\n")
		if len(primaryIP.DNSPtr) == 0 {
			fmt.Fprintf(out, "  No reverse DNS entries\n")
		} else {
			for ip, dns := range primaryIP.DNSPtr {
				fmt.Fprintf(out, "  %s:\t%s\n", ip, dns)
			}
		}

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

		fmt.Fprintln(out)
		util.DescribeLabels(out, primaryIP.Labels, "")

		fmt.Fprintln(out)
		fmt.Fprintf(out, "Location:\n")
		fmt.Fprintf(out, "%s", util.PrefixLines(location.DescribeLocation(primaryIP.Location), "  "))

		if primaryIP.Datacenter != nil {
			fmt.Fprintln(out)
			fmt.Fprintf(out, "Datacenter:\n")
			fmt.Fprintf(out, "%s", util.PrefixLines(datacenter.DescribeDatacenter(s.Client(), primaryIP.Datacenter, true), "  "))
		}

		return nil
	},
}
View Source
var LabelCmds = base.LabelCmds[*hcloud.PrimaryIP]{
	ResourceNameSingular:   "Primary IP",
	ShortDescriptionAdd:    "Add a label to a Primary IP",
	ShortDescriptionRemove: "Remove a label from a Primary IP",
	NameSuggestions:        func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names(false, false, nil) },
	LabelKeySuggestions:    func(c hcapi2.Client) func(idOrName string) []string { return c.PrimaryIP().LabelKeys },
	Fetch: func(s state.State, idOrName string) (*hcloud.PrimaryIP, error) {
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return nil, err
		}
		if primaryIP == nil {
			return nil, fmt.Errorf("primaryIP not found: %s", idOrName)
		}
		return primaryIP, nil
	},
	SetLabels: func(s state.State, primaryIP *hcloud.PrimaryIP, labels map[string]string) error {
		opts := hcloud.PrimaryIPUpdateOpts{
			Labels: &labels,
		}
		_, _, err := s.Client().PrimaryIP().Update(s, primaryIP, opts)
		return err
	},
	GetLabels: func(primaryIP *hcloud.PrimaryIP) map[string]string {
		return primaryIP.Labels
	},
	GetIDOrName: func(primaryIP *hcloud.PrimaryIP) string {
		return strconv.FormatInt(primaryIP.ID, 10)
	},
}
View Source
var ListCmd = &base.ListCmd[*hcloud.PrimaryIP, schema.PrimaryIP]{
	ResourceNamePlural: "Primary IPs",
	JSONKeyGetByName:   "primary_ips",
	DefaultColumns:     []string{"id", "type", "name", "ip", "assignee", "dns", "auto_delete", "age"},
	SortOption:         config.OptionSortPrimaryIP,

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

	OutputTable: func(t *output.Table[*hcloud.PrimaryIP], client hcapi2.Client) {
		t.
			AddAllowedFields(&hcloud.PrimaryIP{}).
			AddFieldFn("ip", func(primaryIP *hcloud.PrimaryIP) string {

				if primaryIP.Network != nil {
					return primaryIP.Network.String()
				}
				return primaryIP.IP.String()
			}).
			AddFieldFn("dns", func(primaryIP *hcloud.PrimaryIP) string {
				var dns string
				if len(primaryIP.DNSPtr) == 1 {
					for _, v := range primaryIP.DNSPtr {
						dns = v
					}
				}
				if len(primaryIP.DNSPtr) > 1 {
					dns = fmt.Sprintf("%d entries", len(primaryIP.DNSPtr))
				}
				return util.NA(dns)
			}).
			AddFieldFn("assignee", func(primaryIP *hcloud.PrimaryIP) string {
				assignee := ""
				if primaryIP.AssigneeID != 0 {
					switch primaryIP.AssigneeType {
					case "server":
						assignee = fmt.Sprintf("Server %s", client.Server().ServerName(primaryIP.AssigneeID))
					}
				}
				return util.NA(assignee)
			}).
			AddFieldFn("protection", func(primaryIP *hcloud.PrimaryIP) string {
				var protection []string
				if primaryIP.Protection.Delete {
					protection = append(protection, "delete")
				}
				return strings.Join(protection, ", ")
			}).
			AddFieldFn("auto_delete", func(primaryIP *hcloud.PrimaryIP) string {
				return util.YesNo(primaryIP.AutoDelete)
			}).
			AddFieldFn("labels", func(primaryIP *hcloud.PrimaryIP) string {
				return util.LabelsToString(primaryIP.Labels)
			}).
			AddFieldFn("created", func(primaryIP *hcloud.PrimaryIP) string {
				return util.Datetime(primaryIP.Created)
			}).
			AddFieldFn("age", func(primaryIP *hcloud.PrimaryIP) string {
				return util.Age(primaryIP.Created, time.Now())
			})
	},

	Schema: hcloud.SchemaFromPrimaryIP,
}
View Source
var SetRDNSCmd = base.SetRdnsCmd[*hcloud.PrimaryIP]{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Change reverse DNS of a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names(false, false, nil) },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.PrimaryIP, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	GetDefaultIP: func(primaryIP *hcloud.PrimaryIP) net.IP {
		return primaryIP.IP
	},
}
View Source
var UnAssignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "unassign <primary-ip>",
			Short: "Unassign a Primary IP from an assignee (usually a server)",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names(false, true, nil)),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		action, _, err := s.Client().PrimaryIP().Unassign(s, primaryIP.ID)
		if err != nil {
			return err
		}

		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}

		cmd.Printf("Primary IP %d was unassigned successfully\n", primaryIP.ID)
		return nil
	},
}
View Source
var UpdateCmd = base.UpdateCmd[*hcloud.PrimaryIP]{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Update a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names(false, false, nil) },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (*hcloud.PrimaryIP, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	DefineFlags: func(cmd *cobra.Command) {
		cmd.Flags().String("name", "", "Primary IP name")
		cmd.Flags().Bool("auto-delete", false, "Delete this Primary IP when the resource it is assigned to is deleted (true, false)")
	},
	Update: func(s state.State, cmd *cobra.Command, primaryIP *hcloud.PrimaryIP, flags map[string]pflag.Value) error {
		updOpts := hcloud.PrimaryIPUpdateOpts{
			Name: flags["name"].String(),
		}

		if cmd.Flags().Changed("auto-delete") {
			autoDelete, _ := cmd.Flags().GetBool("auto-delete")
			updOpts.AutoDelete = hcloud.Ptr(autoDelete)
		}

		_, _, err := s.Client().PrimaryIP().Update(s, primaryIP, 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