Shumoku
NetBox 統合

API リファレンス

shumoku-plugin-netbox ライブラリの API ドキュメント

shumoku-plugin-netbox をライブラリとして使用する際の API リファレンスです。

NetBoxClient

NetBox REST API と通信するクライアントクラスです。リストエンドポイントのページネーションは自動処理され、各 fetch メソッドは next リンクをたどって全件を返します。

コンストラクタ

import { NetBoxClient } from 'shumoku-plugin-netbox'

const client = new NetBoxClient({
  url: string,        // NetBox のベース URL 例: "https://netbox.example.com"
  token: string,      // API トークン
  timeout?: number,   // リクエストタイムアウト(ms、デフォルト: 30000)
  debug?: boolean,    // API リクエスト/レスポンスをコンソールに出力(デフォルト: false)
  insecure?: boolean, // TLS 証明書の検証をスキップ(デフォルト: false)
})

環境変数 NETBOX_URL / NETBOX_TOKEN からクライアントを作ることもできます:

const client = NetBoxClient.fromEnv()

QueryParams

多くの fetch メソッドは、NetBox API にそのまま渡されるフィルタパラメータを受け取れます:

interface QueryParams {
  site?: string | string[]         // サイト slug でフィルタ
  site_id?: number                 // サイト ID でフィルタ
  location?: string | string[]     // ロケーション slug でフィルタ
  location_id?: number             // ロケーション ID でフィルタ
  role?: string | string[]         // ロール slug でフィルタ
  role__n?: string | string[]      // ロール slug で除外
  status?: string                  // ステータスでフィルタ(active, planned, staged, failed, offline)
  tag?: string | string[]          // タグ slug でフィルタ
  tag__n?: string | string[]       // タグ slug で除外
  manufacturer?: string            // メーカー slug でフィルタ
  device_type?: string | string[]  // デバイスタイプ slug でフィルタ
  device_type__n?: string | string[] // デバイスタイプ slug で除外
  q?: string                       // 検索クエリ
}

Fetch メソッド

メソッドNetBox エンドポイントフィルタ可
fetchDevices(params?)dcim/devices
fetchInterfaces(params?)dcim/interfaces
fetchCables()dcim/cables
fetchSites(params?)dcim/sites
fetchLocations(params?)dcim/locations
fetchDeviceRoles()dcim/device-roles
fetchTags()extras/tags
fetchVirtualMachines(params?)virtualization/virtual-machines
fetchVMInterfaces(params?)virtualization/interfaces
fetchPrefixes(params?)ipam/prefixes
fetchIPAddresses(params?)ipam/ip-addresses

使用例:

// 全デバイスを取得
const allDevices = await client.fetchDevices()

// 特定サイトのデバイスのみ
const tokyoDevices = await client.fetchDevices({ site: 'tokyo-dc' })

// 複数条件
const filtered = await client.fetchDevices({
  site: 'tokyo-dc',
  role: 'core-router',
  status: 'active',
})

fetchAll / fetchAllWithVMs

トポロジー生成に必要なデータを並列でまとめて取得します:

// デバイス・インターフェース・ケーブル
const { devices, interfaces, cables } = await client.fetchAll()

// 仮想マシンと VM インターフェースも含める
const { devices, interfaces, cables, virtualMachines, vmInterfaces } =
  await client.fetchAllWithVMs()

convertToNetworkGraph

NetBox のデータを Shumoku の NetworkGraph に変換します。

import { convertToNetworkGraph } from 'shumoku-plugin-netbox'

const graph = convertToNetworkGraph(
  deviceResp,      // fetchDevices の結果
  interfaceResp,   // fetchInterfaces の結果
  cableResp,       // fetchCables の結果
  options?,        // ConverterOptions
)

ConverterOptions

interface ConverterOptions {
  // カスタムタグマッピング(DEFAULT_TAG_MAPPING にマージされる)
  tagMapping?: Record<string, TagMapping>

  // 生成するダイアグラムのテーマ
  theme?: 'light' | 'dark'

  // リンクにポート名を表示(デフォルト: true)
  showPorts?: boolean

  // リンクに VLAN 情報を表示
  showVlans?: boolean

  // ケーブルタイプで色分け(デフォルト: true)
  colorByCableType?: boolean

  // デバイスのグループ化方法(デフォルト: 'tag')
  groupBy?: 'tag' | 'site' | 'location' | 'prefix' | 'none'

  // device role をタイプ推測に使用(デフォルト: true)
  useRoleForType?: boolean

  // デバイスのステータスに応じたスタイル(デフォルト: false)
  colorByStatus?: boolean

  // 仮想マシンを含める(convertToNetworkGraphWithVMs で使用)
  includeVMs?: boolean

  // VM をクラスタごとにサブグラフ化
  groupVMsByCluster?: boolean

  // 凡例を表示(true または LegendSettings でカスタマイズ)
  legend?: boolean | LegendSettings
}

使用例:

// 基本の変換
const graph = convertToNetworkGraph(devices, interfaces, cables)

// オプション付き
const graph = convertToNetworkGraph(devices, interfaces, cables, {
  groupBy: 'site',
  colorByCableType: true,
  colorByStatus: true,
  legend: true,
})

convertToNetworkGraphWithVMs

convertToNetworkGraph と同じですが、includeVMs: true のとき仮想マシンもノードとして追加します:

import { convertToNetworkGraphWithVMs } from 'shumoku-plugin-netbox'

const data = await client.fetchAllWithVMs()
const graph = convertToNetworkGraphWithVMs(
  data.devices,
  data.interfaces,
  data.cables,
  data.virtualMachines,
  data.vmInterfaces,
  { includeVMs: true, groupVMsByCluster: true },
)

VM は破線枠のサーバーノードとして描画されます。groupVMsByCluster: true を指定すると、クラスタごとのサブグラフに入ります。


toYaml

NetworkGraph を Shumoku の YAML 文字列にシリアライズします:

import { toYaml } from 'shumoku-plugin-netbox'

const yamlString = toYaml(graph)

出力は現在のリンク構文を使います — エンドポイントは node/port、両端のモジュール standard が一致する場合は standard: の省略記法、そのほか type / vlan / style を出力します:

links:
  - from:
      node: core-sw1
      port: xe-0/0/1
    to:
      node: edge-sw1
      port: xe-0/0/48
    vlan: [10, 20]
    style:
      stroke: "#eab308"

convertToHierarchicalYaml

マルチサイトのネットワークを階層 YAML 出力(サイト/ロケーション/ラックごとのファイル + それらを参照するメインファイル)に変換します。

import { convertToHierarchicalYaml } from 'shumoku-plugin-netbox'

const result = convertToHierarchicalYaml(deviceResp, interfaceResp, cableResp, {
  hierarchyDepth: 'location',
  fileBasePath: './',
})

// result.main:       main.yaml の内容
// result.files:      Map<locationId, yamlContent>
// result.crossLinks: ロケーションをまたぐケーブルのリスト

HierarchicalConverterOptions

ConverterOptions を拡張します:

interface HierarchicalConverterOptions extends ConverterOptions {
  // 階層の深さ(デフォルト: 'location')
  hierarchyDepth?: 'site' | 'location' | 'rack'

  // main.yaml 内の file: 参照のベースパス(デフォルト: './')
  fileBasePath?: string
}

マッピング定数とヘルパー

プラグインが内部で使うマッピングもエクスポートされており、参照・再利用できます:

エクスポート説明
ROLE_TO_TYPENetBox device role slug → Shumoku デバイスタイプ
DEFAULT_TAG_MAPPINGタグ slug → { type, level, subgraph } の階層マッピング
TAG_PRIORITYデバイスのプライマリタグを決める優先順位
CABLE_STYLES / CABLE_COLORSケーブルタイプ → 色・線種
DEVICE_STATUS_STYLESデバイスステータス → ノードスタイル
convertSpeedToBandwidth(kbps)インターフェース速度(kbps)→ 帯域幅ラベル('1G', '10G', …)
getVlanColor(vid)VLAN ID → 決定的な HSL カラー

NetBox レスポンス型(NetBoxDevice, NetBoxCable, NetBoxInterface など)も一式エクスポートされています。


完全な例

import { NetBoxClient, convertToNetworkGraph, toYaml } from 'shumoku-plugin-netbox'
import { prepareRender, renderSvg } from '@shumoku/renderer-svg'
import { renderHtml } from '@shumoku/renderer-html'
import { writeFileSync } from 'node:fs'

async function generateDiagram() {
  // 1. NetBox からデータを取得(環境変数 NETBOX_URL / NETBOX_TOKEN)
  const client = NetBoxClient.fromEnv()
  const { devices, interfaces, cables } = await client.fetchAll()
  console.log(`Fetched ${devices.results.length} devices`)

  // 2. NetworkGraph に変換
  const graph = convertToNetworkGraph(devices, interfaces, cables, {
    groupBy: 'location',
    colorByCableType: true,
    legend: true,
  })

  // 3. 一度 prepare(アイコン解決 + レイアウト)して複数フォーマットに出力
  const prepared = await prepareRender(graph)

  writeFileSync('network.svg', await renderSvg(prepared)) // 静的 SVG
  writeFileSync('network.html', renderHtml(prepared))     // インタラクティブ HTML
  writeFileSync('network.yaml', toYaml(graph))            // Shumoku YAML
  writeFileSync('network.json', JSON.stringify(graph, null, 2)) // NetworkGraph JSON

  console.log('Done!')
}

generateDiagram()

単一フォーマットだけ必要なら、ワンライナーの renderGraphToSvg(graph)@shumoku/renderer-svg)と renderGraphToHtml(graph)@shumoku/renderer-html)で prepare を省略できます。

目次