Giter Club home page Giter Club logo

go-netbox's Introduction

go-netbox

GoDoc Build Status Report Card

go-netbox is —to nobody's surprise— the official Go API client for the Netbox IPAM and DCIM service.

This project follows Semantic Versioning. The version of the library built for a Netbox version has the same tag, followed by a hyphen and the build number (an incremental integer), as several versions of the library may exist for the same version of Netbox.

Installation

Use go get to add the library as a dependency to your project. Do not forget to run go mod init first if necessary.

go get github.com/netbox-community/go-netbox/v4

# Or install a specific version
go get github.com/netbox-community/go-netbox/[email protected]

Note: dependencies should be managed with Go modules.

Usage

Instantiate the client

The package has a constructor for creating a client by providing a URL and an authentication token.

package main

import (
	"context"
	"log"

	"github.com/netbox-community/go-netbox/v4"
)

func main() {
	ctx := context.Background()

	c := netbox.NewAPIClientFor("https://demo.netbox.dev", "v3ry$3cr3t")

	log.Printf("%+v", c)
}

Use the client

With the client already instantiated, it is possible to consume any API feature.

For example, to list the first 10 active virtual machines:

package main

import (
	"context"
	"log"

	"github.com/netbox-community/go-netbox/v4"
)

func main() {
	ctx := context.Background()

	c := netbox.NewAPIClientFor("https://demo.netbox.dev", "v3ry$3cr3t")

	res, _, err := c.VirtualizationAPI.
		VirtualizationVirtualMachinesList(ctx).
		Status([]string{"active"}).
		Limit(10).
		Execute()

	if err != nil {
		log.Fatal(err)
	}

	log.Printf("%v", res.Results)
}

See docs or reference for more information on all possible usages.

Development

The project comes with a containerized development environment that may be used on any platform. It is only required to have Git and Docker Desktop (or, separately, Docker and Docker Compose) installed on the machine.

To start the development environment, run the following command.

make

Then, to attach a shell in the container, run the command below.

make shell

Finally, to stop the development environment, run the following command.

make down

Considerations

The library is entirely generated from the Netbox OpenAPI specification using openapi-generator. Therefore, files listed here should not be directly modified, as they will be overwritten in the next regeneration (see next section).

In order to fix a bug in the generated code, the corresponding error in the OpenAPI spec must be fixed. To do so, the following steps may be followed:

  1. Optional. Patch the OpenAPI spec in this repo by editing this script, so that a corrected version can be published as soon as possible.
  2. Fix the OpenAPI spec in the Netbox repository, either by reporting an issue or by creating a pull request.

Regenerate the library

To update the OpenAPI specification to the latest Netbox version and regenerate the library, run the following command.

make build

If regeneration of the library is needed for a specific Netbox version other than the latest one, pass the corresponding argument.

make build NETBOX_VERSION=3.0.0

In order to obtain the OpenAPI specification, the version of netbox-docker corresponding to the given Netbox version is used. However, it is also possible to provide a specific version of netbox-docker.

make build NETBOX_VERSION=3.0.0 NETBOX_DOCKER_VERSION=1.3.1

go-netbox's People

Contributors

abhide avatar awlx avatar chdxd1 avatar davcamer avatar ddymko avatar dspeichert avatar kobayashi avatar maltej avatar mdlayher avatar michaelxniu avatar mraerino avatar olekgo avatar smutel avatar tobikris avatar v0ctor avatar yuuki0xff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-netbox's Issues

Cannot retrieve Childdevice

Hey,

I just tested go-netbox and had a problem retrieving devices that act as child device. The definition of swagger.json says that parent_device has to be a string but the netbox api returns a json object like:

"parent_device": {
    "id": 123,
    "url": "https://netbox-url/api/dcim/devices/123/",
    "name": "parent device name",
    "display_name": "parent device display name",
    "device_bay": {
        "id": 1,
        "url": "https://netbox-url/api/dcim/device-bays/1/",
        "name": "device bay name"
    }
}

Regards

hensoko

Create a new tag

Hello,

Could you please create a new tag for this library ?
I am using Gopkg.toml and dep command and it seems that I can only lock version with tags, not master.

Thanks.

Error to use virtualization interface model

Hello,

Using this piece of code with netbox 2.9.7:

params := ipam.NewIpamIPAddressesListParams().WithID(&resourceID)

I received the error message below:

Error: json: cannot unmarshal number into Go struct field IPAddress.assigned_object of type string

When I checked in the JSON api I got:

"assigned_object": {
        "id": 5,
        "url": "http://127.0.0.1:32768/api/virtualization/interfaces/5/",
        "virtual_machine": {
            "id": 6,
            "url": "http://127.0.0.1:32768/api/virtualization/virtual-machines/6/",
            "name": "test"
        },
        "name": "default"
    },

which is not compatible with the definition in the code:

AssignedObject map[string]string `json:"assigned_object,omitempty"`

Regards.

IPAM management

There doesn't currently look to be any related code for IPAM management. Is this correct? If so, is this actively being worked on? If not, what did I miss?

Writable_prefix tenant and site as int64

I am using this module to create prefixes using Terraform but I have to specify the site and tenant as the ID (int64)

It would be helpful to be able to either specify "site_id" or "site_name" which would be TypeString.

Remove description from ip address

Hello,

I created an IP address with go-netbox with the parameters below:

  • address: 192.168.56.1/24
  • description = "Address created by terraform"
  • tenant_id: 5

When I want to update the description, it's working fine:

params := &models.WritableIPAddress{}

address := "192.168.56.1/24"
params.Address = &address

description := "Description updated"
params.Description = description

resource := ipam.NewIpamIPAddressesUpdateParams().WithData(params)
_, err = client.Ipam.IpamIPAddressesUpdate(resource, nil)
if err != nil {
  return err
}

Here is what I see throw tcpdump:

{"address":"192.168.56.1/24","created":"0001-01-01","description":"Description updated","last_updated":"0001-01-01T00:00:00.000Z","nat_outside":null,"tags":[]}

But if I would like to remove the description from that IP address, it does not work.
I use the same code than above but I don't set description.
Here is what I see throw tcpdump:

{"address":"192.168.56.1/24","created":"0001-01-01","last_updated":"0001-01-01T00:00:00.000Z","nat_outside":null,"tags":[]}

If I check in Netbox, the description is still there.

Also what is the difference between PartialUpdate and Update functions ?

Thanks.

Swagger out of date with v2.8

Swagger json is on 2.7, there are a lot of new changes in Netbox v2.8 with regards to the OAS spec.

Can we get a new build of the swagger.json added to this repo?

WritableDeviceInterface Enabled is not added to query

	params := models.WritableDeviceInterface{
		Name:        &swInterface.name,
		MacAddress:  &swInterface.info.IfaceObj.Mac,
		Device:      &parentDeviceID,
		Enabled:     false,
		FormFactor:  formFactor,
		TaggedVlans: []int64{},
		Tags:        []string{},
		Mtu:         &mtu64,
	}

Setting Enabled to false will result in it not being added to the query, however setting it to true will add it when using the update/create interface functions.

Several fields have number as type in swagger.json

Hi,

I recently noticed that several properties in the swagger.json have the type number where I expected integer. This is especially the case for several ID properties like device_id in operation dcim_interfaces_list.

Is there a special reason for this?

I also noticed that several _id fields have string as type when being used as query param.

latest release missing the netbox.go and test files

It appears that the latest release is missing the github.com/netbox-community/go-netbox/netbox/netbox.go and test files. The file contains the NewNetboxAt and NewNetboxWithAPIKey functions documented in the README

Version this SDK based on Netbox releases

TLDR: Add tags to this SDK that match previous releases of Netbox, so that we can import a version that works based on our version of Netbox.

netbox and go-netbox versioning mismatch:

The crux of the issue here is that Netbox does not seem to fully respect Semantic Versioning.
An example (among others) that bit me: Going from 2.6 --> 2.7 , the following API breaking change was introduced:

"status": {
    "value": 1,
    "label": "Active"
},

In NetBox v2.7, it now looks like this:

"status": {
    "value": "active",
    "label": "Active",
    "id": 1
},

As Go, and OpenAPI are statically typed, this results in a predictible unmarshal error if you try to use what is currently on master for go-netbox with Netbox v2.6:

json: cannot unmarshal number into Go struct field PrefixStatus.results.status.value of type string

If API Changes were purely additive in Netbox, this wouldn't be an issue (as defined by SemVer as using the same major version).

Since this SDK is not versioned, there are PR and commits coming in for all version of Netbox. For example, this PR attempts to fix the SDK for the issue above for Netbox v2.6 users:
#70

As this PR describes, it was initially there, then got overwritten (with the v2.7 changes). After this PR got applied, master went back to v2.6 for a little while, then another PR replaced it with the v2.7 breaking changes again:

How to resolve this

The simplest is to assume that master is always up to date with the latest netbox API. I would suggest making sure that all the PR that get accepted are relevant for the latest netbox API as well.

For previous Netbox version, a tag/label should be added to specific commit that are known to be the latest working commits for those versions. A table of compatibility should then ideally be available. For example, the kubernetes go-client does this pretty well IMO:

https://github.com/kubernetes/client-go#compatibility-matrix

Setting optional attributes to their "empty" value

Hi,

this is a generalization of tickets like #105 and #106 because it applies to way more attributes than mentioned in these issues.

The problem
Setting an optional attribute to its "empty" value (false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string) will remove the attribute from the resulting JSON that is sent to netbox. This means that these values can not be set to their empty values via go-netbox.

The cause
This happens because in the swagger.json for optional attributes looks like this (e.g. WritableVirtualMachineWithConfigContext):

"platform": {
          "title": "Platform",
          "type": "integer",
          "x-nullable": true
        },

which translates to

	// Platform
	Platform *int64 `json:"platform,omitempty"`

which in turn will cause Go's json marshaller to omit empty values, which is intended behavior.

This is explained further in https://goswagger.io/faq/faq_model.html#non-required-or-nullable-property

A solution
One possible solution which I employ in a personal fork of go-netbox is to add

        "platform": {
          "title": "Platform",
          "type": "integer",
          "x-nullable": true,
          "x-omitempty": false
        },

which will remove the omitempty annotation from the Go struct.

The problem with this solution is that it requires post-procession of the netbox-generated swaggerfile for all optional attributes.
I do not know the stance of this repo's maintainers about post-processing the swagger.json file. It definitely feels less "pure" when compared to just fetching the swagger.json from netbox and regenerating the client. On the other hand, a client that cannot update certain attributes to their empty value is really not valuable.

Ideally, this would be fixed upstream by making netbox return a correct swagger file, but their swagger support is on a best-effort basis only.

Can't use with version v2.6.3

Hi,

I'm just trying to try the package but I got an issue when trying to get the list of racks:

package main

import (
	"context"
	"fmt"
	"os"
	"github.com/netbox-community/go-netbox/netbox"
	"github.com/netbox-community/go-netbox/netbox/client/dcim"
)

func main() {
	c := netbox.NewNetboxWithAPIKey("localhost:6565", "mytokenwhatever")
	var limit int64 = 10
	var params dcim.DcimRacksListParams = dcim.DcimRacksListParams{
		Context: context.Background(),
		Limit:   &limit,
	}
	rs, err := c.Dcim.DcimRacksList(&params, nil)
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	fmt.Printf("%v\n", *(rs.Payload.Count))
}

And I got :

json: cannot unmarshal number into Go struct field RackStatus.results.status.value of type string
exit status 1

The error is right, I tried to call the api with postman and I got :

"status": {
   "value": 0,
   "label": "Reserved"
},

But when looking at https://github.com/netbox-community/go-netbox/blob/master/netbox/models/rack.go, I see that RackStatus.value need a string.

I tried to use the latest and netbox_v2.6 versions of this package, same thing!

Any idea or a workaround for that?

Thx for your work 😄

Swagger model: Rack.Width.Value of wrong type

Environment

  • Go 1.14.2

  • NetBox version 2.7.11

Steps to reproduce

curl -s -H "Authorization: Token ${NETBOX_TOKEN}" -H "Content-Type: application/json" "https://${NETBOX_HOST}/api/dcim/racks/1/"

Expected behaviour

Received object should unmarshall into model of rack

Observed behaviour

Object width received looks like this:
{
"value": 19,
"label": "19 inches"
},
where rack model expects a string value @ rack.width.value

Error creating ipam prefix

When I create a new ipam prefix with this library, I received an error message as below:

Error: json: cannot unmarshal number into Go struct field PrefixFamily.family.value of type string

The json received by Netbox is like the following:

{
  "id":1,
  "family":{
    "value":4,
    "label": "IPv4"
  },
  "prefix":"192.168.56.0/24",
  "site":null,
  "vrf":null,
  "tenant":null,
  "vlan": {
    "id":2,
    "url":"http://127.0.0.1:32768/api/ipam/vlans/2/",
    "vid":100,
    "name":"Test_Vlan",
    "display_name":"100 (Test_Vlan)"},
    "status": {
      "value":"container",
      "label":"Container",
      "id":0
    },
    "role":null,
    "is_pool":false,
    "description":"Prefix created by terraform",
    "tags":["tag1"],
    "custom_fields":{},
    "created":"2020-03-14",
    "last_updated":"2020-03-14T16:26:39.044374Z"
}

IPAM: IP Address lookup with multiple configured tags

Hi folks,

Pretty new to the scene, but I was wondering how one looks-up an IP address / IP address based on the configured tags.
When I use the following snippet, it is working fine:

`
tags1 := "test"

 params := ipam.NewIpamIPAddressesListParams()
 params.SetTagn(&tags1)

 ipOk, err := c.IpamIPAddressesList(params, nil)
 if err != nil {
     log.Fatalf("[ERROR:] ", err)
 }

`

Question: How do I look up an IP address / IP addresses that have multiple tags configured?

Thank you :)

Upstream patches of forked go-netbox client

Hey there,

we're using netbox with go for quite some time now but started working on a fork of go-netbox as the swagger.json was often out of date. I'm currently preparing simple patches that can be applied hopefully against new versions of swagger.json to fix several (type of *_id fields / number fields) and wonder how I can help upstream.

You can find my changes in feature/modernize.

Regards

Non trusted certificate failure

On my MacBook Pro, when running the example custom host go code, I get an error apparently due to certificate trust issues.

Get "https://netbox.cyber.range/api/dcim/racks/": x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "cyber.range")

Is there a way to ignore ssl verification?

Unable to remove some parameters from vm interface

Hello,

I would like to remove these parameters from an interface:

  • MacAddress => the library does not accept empty string
  • Mtu => 0 is not accepted to remove the MTU set for an interface
  • Mode => empty string is not accepted to remove this parameter

Thanks.

IpamPrefixesList fails unmarshaling

Environment

Go 1.13.7
NetBox version 2.8.1

Steps to reproduce

List all prefixes with IpamPrefixesList

    listParm := ipam.NewIpamPrefixesListParams()
    found, err := nb.Ipam.IpamPrefixesList(listParm, nil)

Expected behavior

Should unmarshal successfully

Observed behavior
cannot unmarshal number into Go struct field PrefixFamily.results.family.value of type string

Proposed fix
Very similar to ea0bfe4#diff-702be237a87f80c305c9755b62bc42f9

Change line 24789 in swagger.json to indicate type:"integer"

API v2

Is anyone working on the porting go-netbox to APIv2?
I would have time to start on it.

Unable to set false for enforce_unique flag for VRF

Seems like setting enforce_unique=false while creating VRF seems to have no effect.
enforce_unique is always set to true.

Repro Steps:

        name := "test_vrf"
        rd := "test_rd"
        description "= "test description"
	vrfParams := ipam.NewIpamVrfsCreateParams().WithData(
		&models.WritableVRF{
			Description:   description,
			EnforceUnique: false,
			Name:          &name,
			Rd:            &rd,
		},

Check in the UI, enforce_unique will still be set to true.

IpamPrefixesAvailableIpsRead fails

Environment

Go 1.14.2
NetBox version 2.7.12

Steps to reproduce

Get available IPs from existing prefix `IpamPrefixesAvailableIpsRead`
    p := ipam.NewIpamPrefixesAvailableIpsReadParams()
    p.ID = prefixID
    pp, err := c.Ipam.IpamPrefixesAvailableIpsRead(p, nil) 
    if err != nil {
        return 0, err
    }

Expected behaviour

Should unmarshal to []*model.NestedIPAddress

Observed behaviour

incorrect type
Fails to unmarshal into model.Prefix with error: json: cannot unmarshal array into Go value of type models.Prefix

Context Deadline

Hello,

I've been trying to use the Go client for Netbox without any success, I cannot get anything else than context deadline exceeded (instantly) when trying to query the Netbox host

A very simple code

package main

import (
	"fmt"
	"github.com/digitalocean/go-netbox/netbox"
	"github.com/digitalocean/go-netbox/netbox/client/ipam"
	"log"
)

func main() {
	nbox := netbox.NewNetboxWithAPIKey("10.1.0.1", "xxx")

	ipString := "10.1.0.1"
	ipInIPAM, err := nbox.IPAM.IPAMIPAddressesList(
			&ipam.IPAMIPAddressesListParams{
				Q: &ipString,
			}, nil)
		if err != nil {
			log.Fatalf("Error: %v", err)
		}
		fmt.Println(ipInIPAM)
}

Would returns

2019/05/09 09:31:00 Error: Get http://10.1.0.1/api/ipam/ip-addresses/?q=10.1.0.1: context deadline exceeded

But the URL is perfectly reachable and working fine

$ curl http://10.1.0.1/api/ipam/ip-addresses/?q=10.1.0.1
{"count":0,"next":null,"previous":null,"results":[]}

Am I missing something ? Also when the Go code runs, the query doesn't run at all (Not visible in HTTP logs)

Thanks.

Enabled (true / false) does not work with vm interface

Hello,

When using this piece of code:

description := "Interface de test"
name := "default"
enabled := false
taggedvlans := []

newResource := &models.WritableVMInterface{
    Description:    description,
    Enabled:        enabled,
    Name:           &name,
    TaggedVlans:    taggedVlans,
    VirtualMachine: 8,
  }

resource := virtualization.NewVirtualizationInterfacesCreateParams().WithData(newResource)
resourceCreated, err := client.Virtualization.VirtualizationInterfacesCreate(resource, nil)

The JSON sent to Netbox is the following:

{"description":"Interface de test","name":"default","tagged_vlans":[],"virtual_machine":8}

We can see that the parameter enabled is not sent to Netbox.

Regards.

Error when geting available ip from prefix informing description.

HI,

In POSTMAN this work:

POST /api/ipam/prefixes/1/available-ips/ HTTP/1.1
Host: 172.17.1.1
authorization: Token aae35cabcfe231ebc8734a798f1cac63439a7a2b
Cache-Control: no-cache
content-type: application/json
Postman-Token: c11a2409-fd58-4dbf-b49c-2b4f557c7a5c

{
"description":"Inclusion - Terraform"
}

When i try to use this from go-netbox (i am new with golang):

import (
	"log"

	api "github.com/digitalocean/go-netbox/netbox"
	"github.com/digitalocean/go-netbox/netbox/client/ipam"
	"github.com/digitalocean/go-netbox/netbox/models"
	"github.com/go-openapi/runtime"
)

func main() {
	c := api.NewNetboxWithAPIKey("172.17.1.1", "aae35cabcfe231ebc8734a798f1cac63439a7a2b")
	var parm = ipam.NewIPAMPrefixesAvailableIpsCreateParams()
	prefixes_id := 2
	description := "Teste de inclusao de IP - Terraform"
	var mp = &models.Prefix{}
	mp.Description = description
	var res models.PrefixStatus
	value := int64(1)
	res.Value = &value
	mp.Status = &res
	a, err4 := mp.MarshalBinary()
	log.Printf("obj mp: %v\n", string(a))
	if err4 != nil {
		log.Printf("err3: %v\n", err4)
	}
	parm.SetData(mp)
	parm.SetID(int64(prefixes_id))
	log.Printf("[DEBUG] JP descriptioin %v\n", description)
	log.Println("[DEBUG] JP - Executado...")
	out, err := c.IPAM.IPAMPrefixesAvailableIpsCreate(parm, nil)

	if err != nil {
		log.Println("[DEBUG] JP - Err ao criar IP *************************************")
		log.Printf("[DEBUG] JP - Err: %v \n", err)
	}
	if out != nil {
		log.Println("[DEBUG] JP - Out ok ao criar IP **********************************")
		log.Printf("Created %v\n", out.Payload.Created)
		log.Printf("Custom Fields: %v\n", out.Payload.CustomFields)
		log.Printf("Description: %v\n", out.Payload.Description)
		log.Printf("Family: %v\n", out.Payload.Family)
		log.Printf("ID: %v\n", out.Payload.ID)
		log.Printf("IsPool: %v\n", out.Payload.IsPool)
		log.Printf("LastUpdated: %v\n", out.Payload.LastUpdated)
		log.Printf("Prefix: %v\n", out.Payload.Prefix)
		log.Printf("Role: %v\n", out.Payload.Role)
		log.Printf("Site: %v\n", out.Payload.Site)
		log.Printf("Status: %v\n", out.Payload.Status)
		if out.Payload.Tenant != nil {
			log.Printf("Tenant: %v\n", out.Payload.Tenant)
		}
		if out.Payload.Vlan != nil {
			log.Printf("Vlan Name: %v\n", out.Payload.Vlan.Name)
		}
		log.Print(out.Payload.Vrf)
		log.Printf("[DEBUG] JP - Out: %v \n", out)
		log.Println("[DEBUG] JP - *****************************************************")
	}
}

The result is:

2018/08/23 13:59:33 obj mp: {"created":"0001-01-01","description":"Teste de inclusao de IP - Terraform","last_updated":"0001-01-01T00:00:00.000Z","prefix":null,"role":null,"site":null,"status":{"label":null,"value":1},"tenant":null,"vlan":null,"vrf":null}
2018/08/23 13:59:33 [DEBUG] JP descriptioin Teste de inclusao de IP - Terraform
2018/08/23 13:59:33 [DEBUG] JP - Executado...
2018/08/23 13:59:33 [DEBUG] JP - Err ao criar IP *************************************
2018/08/23 13:59:33 [DEBUG] JP - Err: unknown error (status 500): {resp:0xc42032a000} 

The problem is in JSON serialization? Is possible to do like de POSTMAN example (only serializing the Description)?

Thanks,
jp

Fix Travis

Travis seems not to work anymore we should fix that.

Device ConfigContext rendered as wrong type

This is only a problem when a device has a "config context" attached to it.

{"count":1,"next":null,"previous":null,"results":[{"id":511,"name":... ,
"config_context":{
    "name":"Somewhere",
    "devices":[
        "thing1", "thing2", "thing3"
    ]
},"created":"2019-04-29","last_updated":"2019-04-29T17:40:30
.440516Z"}]}
FATA[0000] Cannot get devices list: json: cannot unmarshal array into Go struct field DeviceWithConfigContext.results.config_context of type string
exit status 1

I believe the problem is in the swagger spec here: https://github.com/netbox-community/go-netbox/blob/master/swagger.json#L32639

Resulting in an incorrect type here: https://github.com/netbox-community/go-netbox/blob/master/netbox/models/device_with_config_context.go#L52

I believe it should be (works locally at least):

ConfigContext *ConfigContext `json:"config_context,omitempty"`

I haven't touched go in a while, but I'll try to PR this once I figure out the config gen.

Versioning proposal

Currently we are not tagging this library in a way that is compatible with what go mod suggests.
It would be good to use semver.

If we want to include the netbox version in the release tag, we could use the condensed form, like 27 for 2.7, because api breakage happens on minor, not patch versions

Proposal 1: break in 0.x

  • always stay on 0.x
  • upgrade minor with netbox (non-patch) versions
  • semver allows breaking changes in minor version when on 0.x

This would mean we'd have versions like 0.27.1 for the second patch release supporting netbox 2.7.

Proposal 2: breaking per go spec

  • add major packages like v27 as subdirectories
  • pro: we'd have a client for every netbox version
  • pro: allows larger changes inside the library, e.g. v27.2.0
  • con: a lot of subdirs potentially

This would mean people needed to use the library in this way: github.com/netbox-community/go-netbox/v27


In both cases it would still be possible to version changes in the library via increasing the patch number. But any breaking changes would need to be synchronized with netbox releases.

Create tags with go-netbox and netbox 2.9

Hello,

Is-it possible to create a tag using go-netbox in netbox 2.9 ?
Since netbox 2.9, tags are implemented differently in go-netbox (NestedTags).
I didn't found any writable_tag.go ...

Thanks.

Question about errors

Hello,

I am using this library to create a terraform provider.
The error of this library is sent to the terraform provider.
The only error message displayed by my terraform provider is like:

Error: unknown error (status 400): {resp:0xc0008ae870}

However when I am doing a tcpdump I see that we can have more human readable message like:

{"detail":"Unable to delete object. The following dependent objects were found: 192.168.56.0/24 (ipam.prefix)"}

Do we have this kind of message in the error object returned by this library ?

Thanks.

Dcim.DcimInterfacesList tries to unmarshall number into string

When running:

params := dcim.NewDcimInterfacesListParamsWithTimeout(time.Second * 10)
params.SetMacAddress(&hwaddr)
ifList, err := netboxClient4.Dcim.DcimInterfacesList(params, nil)

We get:

json: cannot unmarshal number into Go struct field Interface.results.connected_endpoint of type string

I wasn't able to pinpoint what call exactly gets that (yet) because running the API call via e.g. curl does return a string value for that field ("connected_endpoint_type": "dcim.interface",).

However, the model does expect a string and does not get one somehow.

Go client stubs sending too many parameters

Hi Folks,

I'd like to change just the status of a specific IP address but am having trouble with the golang client stubs sending too many address parameters. My code looks like this:

update := &models.WritableIPAddress{Status: "active"}
fmt.Println(*update)
p := ipam.NewIpamIPAddressesPartialUpdateParams()
p.ID = first.ID
p.Data = update

_, err = c.Ipam.IpamIPAddressesPartialUpdate(p, nil)

but what goes over the wire looks like:

{"address":null,"created":"0001-01-01","last_updated":"0001-01-01T00:00:00.000Z","nat_outside":null,"status":"active","tags":null}

This causes a 400 response.

I looked at https://pkg.go.dev/github.com/netbox-community/go-netbox/netbox/models?tab=doc#WritableIPAddress and the extra fields that I'm getting in the json don't have "omitempty" in their declaration. Should I be using something different than models.WritableIPAddress so that only the parameters that I set get serialized or am I doing something tragically wrong?

Thanks!

IPAM IP Addresses Error/bug: 400] map[tags:[All list items must be of string type.]])

Hi folks,

Please consider the following snippet:

 12 func main() {
 13     conn := netbox.NewNetboxWithAPIKey("127.0.0.1:8000", "0123456789abcdef0123456789abcdef01234567") // Making debugging easier ;)
 14     c := conn.Ipam
 15     
 16     var tagList []*models.NestedTag
 17     tags := []string{"test1", "test2"}
 18     address := "10.0.0.3/32"
 19         
 20     for _, v := range tags {
 21         tagItem := models.NestedTag{Name: &v}
 22         tagList = append(tagList, &tagItem)
 23     }
 24     
 25     params := ipam.NewIpamIPAddressesCreateParams()
 26     params.WithData(&models.WritableIPAddress{
 27         Address: &address,
 28         Tags:    tagList,
 29     })
 30     
 31     ip, err := c.IpamIPAddressesCreate(params, nil)
 32     if err != nil {
 33         log.Fatalf("Error creating IP Address: ", err)
 34     }
 35 
 36     fmt.Println(ip.Payload.ID)
 37 }

I am pretty new to the scene, so forgive the ugliness, but this results in the following error:

Error creating IP Address: %!(EXTRA *ipam.IpamIPAddressesCreateDefault=[POST /ipam/ip-addresses/][400] ipam_ip-addresses_create default  map[tags:[All list items must be of string type.]])
exit status 1

I believe this error is related to the 'type' change that got introduced in PR#92 (#92). This PR changes the type of the Tags field of the 'netbox/models/writable_ip_address.go' file from []string to []NestedTag. (cc @awlx)

I am happy to open a PR and revert the type change, but as I mentioned, I am pretty new and I would like to receive some feedback on this first :).

Cheers,

API scheme change by netbox 2.7.x

netbox community decided (netbox-community/netbox#3569) to change the scheme of various API routes slightly. this now causes type errors.

json: cannot unmarshal string into Go struct field SiteStatus.results.status.value of type int64

// SiteStatus Status
// swagger:model SiteStatus
type SiteStatus struct {

        // label
        // Required: true
        Label *string `json:"label"`

        // value
        // Required: true
        Value *string `json:"value"`
}

example route: /api/dcim/sites/ | jq '.results[] | .id, .name, .status'

"AWS"
{
"value": "active",
"label": "Active",
"id": 1
}

The client is not compliant with netbox latest API

Just trying to create a simple VLAN throws json unmarshalling issues:

json: cannot unmarshal object into Go struct field WritableVLAN.status of type int64

Just curl against the API is pretty clear that the status field should be either struct or map[string]inerface{}

 "status": {
    "value": 1,
    "label": "Active"
  },

This is a major bug guys...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.