Version 1.4 (#14)

* Connect(Setup): Fix indent (using Visual code Formatter)

* Setup(Functions): Fix indent (using Visual Code Formatter)

* Support(Setup): Fix indent (using Visual Code Formatter)

* InvokeNetboxRequest(Helpers): Fix indent (using Visual Code Formatter)

* Add Set-netboxCipherSSL for enable TLS1.1 and TLS1.2 (for PS 5.0)

From PowerAruba/FortiPower Module :)

* Add Set-NetboxUnstrustedSSL for disable SSL chain test (for PS 5.0

From PowerAruba/FortiPwoer Module :)

* Add Get/Set netboxInvokeParms for Get and Set Invoke Params (array)

Like -SkipCertificate, Timeout...

* InvokeNetboxRequest: Add to Splat NetboxInvokeParams

* Connect: Add SkipCertificateCheck parameter (for PS5 and Core)

Also enable TLS 1.1 and 1.2 for PS5

* PSSA: Add Github Actions for launch PSSA (PowerShell Script Analyzer) when launch PR (#11)

Add also vscode/PSScriptAnalyzerSettings.psd1 for Settings for PSSA (can be reuse also for vscode...)

* Update psproj

* Correct typo

* Correct brace formatting

* Add Get/Set timeout functions

* Add Get/Set timeout functions

* Add TimeoutSeconds parameter and logic to Connect-NetboxAPI
- Updated `InvokeNetboxRequest` to use `NetboxConfig.Timeout`
- Updated `Get-NetboxAPIDefinition` to use `NetboxConfig.Timeout`

* Trim whitespaces

* Add Get-NetboxVersion function

* Remove API Definition caching and replace with Netbox version check

* Increment version to 1.4

Co-authored-by: Alexis La Goutte <alexis.lagoutte@gmail.com>
Co-authored-by: Ben Claussen <claussen@neonet.org>
This commit is contained in:
Ben Claussen 2021-07-22 12:00:12 -04:00 committed by GitHub
parent 1f89363cbd
commit 739f5e98e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 539 additions and 198 deletions

16
.github/workflows/pssa.yml vendored Normal file
View file

@ -0,0 +1,16 @@
name: CI
on: [pull_request]
jobs:
lint:
name: Run PSSA
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: lint
uses: docker://devblackops/github-action-psscriptanalyzer:2.3.0
with:
settingsPath: .vscode/PSScriptAnalyzerSettings.psd1
sendComment: false
failOnInfos: true
failOnErrors: true
failOnWarnings: true

5
.vscode/PSScriptAnalyzerSettings.psd1 vendored Normal file
View file

@ -0,0 +1,5 @@
@{
ExcludeRules = @(
'PSUseToExportFieldsInManifest'
)
}

View file

@ -1,4 +1,4 @@
<# <#
.NOTES .NOTES
=========================================================================== ===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.172 Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.172
@ -18,44 +18,46 @@ function InvokeNetboxRequest {
( (
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[System.UriBuilder]$URI, [System.UriBuilder]$URI,
[Hashtable]$Headers = @{ [Hashtable]$Headers = @{
}, },
[pscustomobject]$Body = $null, [pscustomobject]$Body = $null,
[ValidateRange(0, 60)] [ValidateRange(1, 65535)]
[uint16]$Timeout = 5, [uint16]$Timeout = (Get-NetboxTimeout),
[ValidateSet('GET', 'PATCH', 'PUT', 'POST', 'DELETE', 'OPTIONS', IgnoreCase = $true)] [ValidateSet('GET', 'PATCH', 'PUT', 'POST', 'DELETE', 'OPTIONS', IgnoreCase = $true)]
[string]$Method = 'GET', [string]$Method = 'GET',
[switch]$Raw [switch]$Raw
) )
$creds = Get-NetboxCredential $creds = Get-NetboxCredential
$Headers.Authorization = "Token {0}" -f $creds.GetNetworkCredential().Password $Headers.Authorization = "Token {0}" -f $creds.GetNetworkCredential().Password
$splat = @{ $splat = @{
'Method' = $Method 'Method' = $Method
'Uri' = $URI.Uri.AbsoluteUri # This property auto generates the scheme, hostname, path, and query 'Uri' = $URI.Uri.AbsoluteUri # This property auto generates the scheme, hostname, path, and query
'Headers' = $Headers 'Headers' = $Headers
'TimeoutSec' = $Timeout 'TimeoutSec' = $Timeout
'ContentType' = 'application/json' 'ContentType' = 'application/json'
'ErrorAction' = 'Stop' 'ErrorAction' = 'Stop'
'Verbose' = $VerbosePreference 'Verbose' = $VerbosePreference
} }
$splat += Get-NetboxInvokeParams
if ($Body) { if ($Body) {
Write-Verbose "BODY: $($Body | ConvertTo-Json -Compress)" Write-Verbose "BODY: $($Body | ConvertTo-Json -Compress)"
$null = $splat.Add('Body', ($Body | ConvertTo-Json -Compress)) $null = $splat.Add('Body', ($Body | ConvertTo-Json -Compress))
} }
$result = Invoke-RestMethod @splat $result = Invoke-RestMethod @splat
#region TODO: Handle errors a little more gracefully... #region TODO: Handle errors a little more gracefully...
<# <#
try { try {
Write-Verbose "Sending request..." Write-Verbose "Sending request..."
@ -69,7 +71,7 @@ function InvokeNetboxRequest {
Write-Verbose "RAW provided...throwing raw exception" Write-Verbose "RAW provided...throwing raw exception"
throw $_ throw $_
} }
Write-Verbose "Converting response to object" Write-Verbose "Converting response to object"
$myError = GetNetboxAPIErrorBody -Response $_.Exception.Response | ConvertFrom-Json $myError = GetNetboxAPIErrorBody -Response $_.Exception.Response | ConvertFrom-Json
} else { } else {
@ -77,18 +79,18 @@ function InvokeNetboxRequest {
$myError = $_ $myError = $_
} }
} }
Write-Verbose "MyError is $($myError.GetType().FullName)" Write-Verbose "MyError is $($myError.GetType().FullName)"
if ($myError -is [Exception]) { if ($myError -is [Exception]) {
throw $_ throw $_
} elseif ($myError -is [pscustomobject]) { } elseif ($myError -is [pscustomobject]) {
throw $myError.detail throw $myError.detail
} }
#> #>
#endregion TODO: Handle errors a little more gracefully... #endregion TODO: Handle errors a little more gracefully...
# If the user wants the raw value from the API... otherwise return only the actual result # If the user wants the raw value from the API... otherwise return only the actual result
if ($Raw) { if ($Raw) {
Write-Verbose "Returning raw result by choice" Write-Verbose "Returning raw result by choice"

View file

@ -2,56 +2,69 @@
<# <#
.SYNOPSIS .SYNOPSIS
Connects to the Netbox API and ensures Credential work properly Connects to the Netbox API and ensures Credential work properly
.DESCRIPTION .DESCRIPTION
Connects to the Netbox API and ensures Credential work properly Connects to the Netbox API and ensures Credential work properly
.PARAMETER Hostname .PARAMETER Hostname
The hostname for the resource such as netbox.domain.com The hostname for the resource such as netbox.domain.com
.PARAMETER Credential .PARAMETER Credential
Credential object containing the API key in the password. Username is not applicable Credential object containing the API key in the password. Username is not applicable
.PARAMETER Scheme .PARAMETER Scheme
Scheme for the URI such as HTTP or HTTPS. Defaults to HTTPS Scheme for the URI such as HTTP or HTTPS. Defaults to HTTPS
.PARAMETER Port .PARAMETER Port
Port for the resource. Value between 1-65535 Port for the resource. Value between 1-65535
.PARAMETER URI .PARAMETER URI
The full URI for the resource such as "https://netbox.domain.com:8443" The full URI for the resource such as "https://netbox.domain.com:8443"
.PARAMETER SkipCertificateCheck
A description of the SkipCertificateCheck parameter.
.PARAMETER TimeoutSeconds
The number of seconds before the HTTP call times out. Defaults to 30 seconds
.EXAMPLE .EXAMPLE
PS C:\> Connect-NetboxAPI -Hostname "netbox.domain.com" PS C:\> Connect-NetboxAPI -Hostname "netbox.domain.com"
This will prompt for Credential, then proceed to attempt a connection to Netbox This will prompt for Credential, then proceed to attempt a connection to Netbox
.NOTES .NOTES
Additional information about the function. Additional information about the function.
#> #>
[CmdletBinding(DefaultParameterSetName = 'Manual')] [CmdletBinding(DefaultParameterSetName = 'Manual')]
param param
( (
[Parameter(ParameterSetName = 'Manual', [Parameter(ParameterSetName = 'Manual',
Mandatory = $true)] Mandatory = $true)]
[string]$Hostname, [string]$Hostname,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[pscredential]$Credential, [pscredential]$Credential,
[Parameter(ParameterSetName = 'Manual')] [Parameter(ParameterSetName = 'Manual')]
[ValidateSet('https', 'http', IgnoreCase = $true)] [ValidateSet('https', 'http', IgnoreCase = $true)]
[string]$Scheme = 'https', [string]$Scheme = 'https',
[Parameter(ParameterSetName = 'Manual')] [Parameter(ParameterSetName = 'Manual')]
[uint16]$Port = 443, [uint16]$Port = 443,
[Parameter(ParameterSetName = 'URI', [Parameter(ParameterSetName = 'URI',
Mandatory = $true)] Mandatory = $true)]
[string]$URI [string]$URI,
[Parameter(Mandatory = $false)]
[switch]$SkipCertificateCheck = $false,
[ValidateNotNullOrEmpty()]
[ValidateRange(1, 65535)]
[uint16]$TimeoutSeconds = 30
) )
if (-not $Credential) { if (-not $Credential) {
try { try {
$Credential = Get-NetboxCredential -ErrorAction Stop $Credential = Get-NetboxCredential -ErrorAction Stop
@ -62,14 +75,29 @@
} }
} }
} }
$null = Set-NetboxCredential -Credential $Credential $invokeParams = @{ SkipCertificateCheck = $SkipCertificateCheck; }
if ("Desktop" -eq $PSVersionTable.PsEdition) {
#Remove -SkipCertificateCheck from Invoke Parameter (not supported <= PS 5)
$invokeParams.remove("SkipCertificateCheck")
}
#for PowerShell (<=) 5 (Desktop), Enable TLS 1.1, 1.2 and Disable SSL chain trust
if ("Desktop" -eq $PSVersionTable.PsEdition) {
#Enable TLS 1.1 and 1.2
Set-NetboxCipherSSL
if ($SkipCertificateCheck) {
#Disable SSL chain trust...
Set-NetboxuntrustedSSL
}
}
switch ($PSCmdlet.ParameterSetName) { switch ($PSCmdlet.ParameterSetName) {
'Manual' { 'Manual' {
$uriBuilder = [System.UriBuilder]::new($Scheme, $Hostname, $Port) $uriBuilder = [System.UriBuilder]::new($Scheme, $Hostname, $Port)
} }
'URI' { 'URI' {
$uriBuilder = [System.UriBuilder]::new($URI) $uriBuilder = [System.UriBuilder]::new($URI)
if ([string]::IsNullOrWhiteSpace($uriBuilder.Host)) { if ([string]::IsNullOrWhiteSpace($uriBuilder.Host)) {
@ -77,11 +105,14 @@
} }
} }
} }
$null = Set-NetboxHostName -Hostname $uriBuilder.Host $null = Set-NetboxHostName -Hostname $uriBuilder.Host
$null = Set-NetboxCredential -Credential $Credential
$null = Set-NetboxHostScheme -Scheme $uriBuilder.Scheme $null = Set-NetboxHostScheme -Scheme $uriBuilder.Scheme
$null = Set-NetboxHostPort -Port $uriBuilder.Port $null = Set-NetboxHostPort -Port $uriBuilder.Port
$null = Set-NetboxInvokeParams -invokeParams $invokeParams
$null = Set-NetboxTimeout -TimeoutSeconds $TimeoutSeconds
try { try {
Write-Verbose "Verifying API connectivity..." Write-Verbose "Verifying API connectivity..."
$null = VerifyAPIConnectivity $null = VerifyAPIConnectivity
@ -94,18 +125,27 @@
throw $_ throw $_
} }
} }
Write-Verbose "Caching API definition" # Write-Verbose "Caching API definition"
$script:NetboxConfig.APIDefinition = Get-NetboxAPIDefinition # $script:NetboxConfig.APIDefinition = Get-NetboxAPIDefinition
#
if ([version]$script:NetboxConfig.APIDefinition.info.version -lt 2.8) { # if ([version]$script:NetboxConfig.APIDefinition.info.version -lt 2.8) {
# $Script:NetboxConfig.Connected = $false
# throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.APIDefinition.info.version)"
# }
Write-Verbose "Checking Netbox version compatibility"
$script:NetboxConfig.NetboxVersion = Get-NetboxVersion
if ([version]$script:NetboxConfig.NetboxVersion.'netbox-version' -lt 2.8) {
$Script:NetboxConfig.Connected = $false $Script:NetboxConfig.Connected = $false
throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.APIDefinition.info.version)" throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.NetboxVersion.'netbox-version')"
} else {
Write-Verbose "Found compatible version [$($script:NetboxConfig.NetboxVersion.'netbox-version')]!"
} }
$script:NetboxConfig.Connected = $true $script:NetboxConfig.Connected = $true
Write-Verbose "Successfully connected!" Write-Verbose "Successfully connected!"
#Write-Verbose "Caching static choices" #Write-Verbose "Caching static choices"
#$script:NetboxConfig.Choices.Circuits = Get-NetboxCircuitsChoices #$script:NetboxConfig.Choices.Circuits = Get-NetboxCircuitsChoices
#$script:NetboxConfig.Choices.DCIM = Get-NetboxDCIMChoices # Not completed yet #$script:NetboxConfig.Choices.DCIM = Get-NetboxDCIMChoices # Not completed yet
@ -114,6 +154,6 @@
##$script:NetboxConfig.Choices.Secrets = Get-NetboxSecretsChoices # Not completed yet ##$script:NetboxConfig.Choices.Secrets = Get-NetboxSecretsChoices # Not completed yet
##$script:NetboxConfig.Choices.Tenancy = Get-NetboxTenancyChoices ##$script:NetboxConfig.Choices.Tenancy = Get-NetboxTenancyChoices
#$script:NetboxConfig.Choices.Virtualization = Get-NetboxVirtualizationChoices #$script:NetboxConfig.Choices.Virtualization = Get-NetboxVirtualizationChoices
Write-Verbose "Connection process completed" Write-Verbose "Connection process completed"
} }

View file

@ -2,10 +2,10 @@
[CmdletBinding()] [CmdletBinding()]
[OutputType([pscredential])] [OutputType([pscredential])]
param () param ()
if (-not $script:NetboxConfig.Credential) { if (-not $script:NetboxConfig.Credential) {
throw "Netbox Credentials not set! You may set with Set-NetboxCredential" throw "Netbox Credentials not set! You may set with Set-NetboxCredential"
} }
$script:NetboxConfig.Credential $script:NetboxConfig.Credential
} }

View file

@ -1,11 +1,11 @@
function Get-NetboxHostname { function Get-NetboxHostname {
[CmdletBinding()] [CmdletBinding()]
param () param ()
Write-Verbose "Getting Netbox hostname" Write-Verbose "Getting Netbox hostname"
if ($null -eq $script:NetboxConfig.Hostname) { if ($null -eq $script:NetboxConfig.Hostname) {
throw "Netbox Hostname is not set! You may set it with Set-NetboxHostname -Hostname 'hostname.domain.tld'" throw "Netbox Hostname is not set! You may set it with Set-NetboxHostname -Hostname 'hostname.domain.tld'"
} }
$script:NetboxConfig.Hostname $script:NetboxConfig.Hostname
} }

View file

@ -0,0 +1,11 @@
function Get-NetboxInvokeParams {
[CmdletBinding()]
param ()
Write-Verbose "Getting Netbox InvokeParams"
if ($null -eq $script:NetboxConfig.InvokeParams) {
throw "Netbox Invoke Params is not set! You may set it with Set-NetboxInvokeParams -InvokeParams ..."
}
$script:NetboxConfig.InvokeParams
}

View file

@ -0,0 +1,13 @@

function Get-NetboxTimeout {
[CmdletBinding()]
[OutputType([uint16])]
param ()
Write-Verbose "Getting Netbox Timeout"
if ($null -eq $script:NetboxConfig.Timeout) {
throw "Netbox Timeout is not set! You may set it with Set-NetboxTimeout -TimeoutSeconds [uint16]"
}
$script:NetboxConfig.Timeout
}

View file

@ -0,0 +1,15 @@

function Get-NetboxVersion {
[CmdletBinding()]
param ()
$Segments = [System.Collections.ArrayList]::new(@('status'))
$URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{
'format' = 'json'
}
$URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck
InvokeNetboxRequest -URI $URI
}

View file

@ -0,0 +1,8 @@
Function Set-NetboxCipherSSL {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessforStateChangingFunctions", "")]
Param( )
# Hack for allowing TLS 1.1 and TLS 1.2 (by default it is only SSL3 and TLS (1.0))
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
}

View file

@ -1,32 +1,32 @@
function Set-NetboxCredential { function Set-NetboxCredential {
[CmdletBinding(DefaultParameterSetName = 'CredsObject', [CmdletBinding(DefaultParameterSetName = 'CredsObject',
ConfirmImpact = 'Low', ConfirmImpact = 'Low',
SupportsShouldProcess = $true)] SupportsShouldProcess = $true)]
[OutputType([pscredential])] [OutputType([pscredential])]
param param
( (
[Parameter(ParameterSetName = 'CredsObject', [Parameter(ParameterSetName = 'CredsObject',
Mandatory = $true)] Mandatory = $true)]
[pscredential]$Credential, [pscredential]$Credential,
[Parameter(ParameterSetName = 'UserPass', [Parameter(ParameterSetName = 'UserPass',
Mandatory = $true)] Mandatory = $true)]
[securestring]$Token [securestring]$Token
) )
if ($PSCmdlet.ShouldProcess('Netbox Credentials', 'Set')) { if ($PSCmdlet.ShouldProcess('Netbox Credentials', 'Set')) {
switch ($PsCmdlet.ParameterSetName) { switch ($PsCmdlet.ParameterSetName) {
'CredsObject' { 'CredsObject' {
$script:NetboxConfig.Credential = $Credential $script:NetboxConfig.Credential = $Credential
break break
} }
'UserPass' { 'UserPass' {
$script:NetboxConfig.Credential = [System.Management.Automation.PSCredential]::new('notapplicable', $Token) $script:NetboxConfig.Credential = [System.Management.Automation.PSCredential]::new('notapplicable', $Token)
break break
} }
} }
$script:NetboxConfig.Credential $script:NetboxConfig.Credential
} }
} }

View file

@ -1,13 +1,13 @@
function Set-NetboxHostName { function Set-NetboxHostName {
[CmdletBinding(ConfirmImpact = 'Low', [CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)] SupportsShouldProcess = $true)]
[OutputType([string])] [OutputType([string])]
param param
( (
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[string]$Hostname [string]$Hostname
) )
if ($PSCmdlet.ShouldProcess('Netbox Hostname', 'Set')) { if ($PSCmdlet.ShouldProcess('Netbox Hostname', 'Set')) {
$script:NetboxConfig.Hostname = $Hostname.Trim() $script:NetboxConfig.Hostname = $Hostname.Trim()
$script:NetboxConfig.Hostname $script:NetboxConfig.Hostname

View file

@ -0,0 +1,14 @@
function Set-NetboxInvokeParams {
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[array]$InvokeParams
)
if ($PSCmdlet.ShouldProcess('Netbox Invoke Params', 'Set')) {
$script:NetboxConfig.InvokeParams = $InvokeParams
$script:NetboxConfig.InvokeParams
}
}

View file

@ -0,0 +1,17 @@

function Set-NetboxTimeout {
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)]
[OutputType([uint16])]
param
(
[Parameter(Mandatory = $false)]
[ValidateRange(1, 65535)]
[uint16]$TimeoutSeconds = 30
)
if ($PSCmdlet.ShouldProcess('Netbox Timeout', 'Set')) {
$script:NetboxConfig.Timeout = $TimeoutSeconds
$script:NetboxConfig.Timeout
}
}

View file

@ -0,0 +1,19 @@
Function Set-NetboxUntrustedSSL {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessforStateChangingFunctions", "")]
Param( )
# Hack for allowing untrusted SSL certs with https connections
Add-Type -TypeDefinition @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
}

View file

@ -1,14 +1,14 @@
<# <#
.NOTES .NOTES
=========================================================================== ===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.174 Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.174
Created on: 4/28/2020 11:57 Created on: 4/28/2020 11:57
Created by: Claussen Created by: Claussen
Organization: NEOnet Organization: NEOnet
Filename: Get-NetboxAPIDefinition.ps1 Filename: Get-NetboxAPIDefinition.ps1
=========================================================================== ===========================================================================
.DESCRIPTION .DESCRIPTION
A description of the file. A description of the file.
#> #>
@ -16,14 +16,14 @@
function Get-NetboxAPIDefinition { function Get-NetboxAPIDefinition {
[CmdletBinding()] [CmdletBinding()]
param () param ()
#$URI = "https://netbox.neonet.org/api/docs/?format=openapi" #$URI = "https://netbox.neonet.org/api/docs/?format=openapi"
$Segments = [System.Collections.ArrayList]::new(@('docs')) $Segments = [System.Collections.ArrayList]::new(@('docs'))
$URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{'format' = 'openapi'} $URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{'format' = 'openapi' }
$URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck $URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck
InvokeNetboxRequest -URI $URI -Timeout 10 InvokeNetboxRequest -URI $URI
} }

View file

@ -4,17 +4,17 @@
( (
[switch]$Overwrite [switch]$Overwrite
) )
Write-Verbose "Checking for NetboxConfig hashtable" Write-Verbose "Checking for NetboxConfig hashtable"
if ((-not ($script:NetboxConfig)) -or $Overwrite) { if ((-not ($script:NetboxConfig)) -or $Overwrite) {
Write-Verbose "Creating NetboxConfig hashtable" Write-Verbose "Creating NetboxConfig hashtable"
$script:NetboxConfig = @{ $script:NetboxConfig = @{
'Connected' = $false 'Connected' = $false
'Choices' = @{ 'Choices' = @{
} }
'APIDefinition' = $null 'APIDefinition' = $null
} }
} }
Write-Verbose "NetboxConfig hashtable already exists" Write-Verbose "NetboxConfig hashtable already exists"
} }

View file

@ -1,10 +1,10 @@
function VerifyAPIConnectivity { function VerifyAPIConnectivity {
[CmdletBinding()] [CmdletBinding()]
param () param ()
$uriSegments = [System.Collections.ArrayList]::new(@('extras')) $uriSegments = [System.Collections.ArrayList]::new(@('extras'))
$uri = BuildNewURI -Segments $uriSegments -Parameters @{'format' = 'json'} -SkipConnectedCheck $uri = BuildNewURI -Segments $uriSegments -Parameters @{'format' = 'json' } -SkipConnectedCheck
InvokeNetboxRequest -URI $uri InvokeNetboxRequest -URI $uri
} }

View file

@ -3,7 +3,7 @@
# #
# Generated by: Ben Claussen # Generated by: Ben Claussen
# #
# Generated on: 2021-03-31 # Generated on: 2021-07-22
# #
@{ @{
@ -12,7 +12,7 @@
RootModule = 'NetboxPS.psm1' RootModule = 'NetboxPS.psm1'
# Version number of this module. # Version number of this module.
ModuleVersion = '1.3.3' ModuleVersion = '1.4'
# Supported PSEditions # Supported PSEditions
# CompatiblePSEditions = @() # CompatiblePSEditions = @()

View file

@ -108,6 +108,13 @@
<File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxHostScheme_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxHostScheme.ps1</File> <File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxHostScheme_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxHostScheme.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxHostPort_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxHostPort.ps1</File> <File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxHostPort_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxHostPort.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxHostPort_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxHostPort.ps1</File> <File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxHostPort_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxHostPort.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxInvokeParams_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxInvokeParams.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxCipherSSL_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxCipherSSL.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxInvokeParams_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxInvokeParams.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxUnstrustedSSL_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxUnstrustedSSL.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Set-NetboxTimeout_ps1" ExportFunctions="True">Functions\Setup\Set-NetboxTimeout.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxTimeout_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxTimeout.ps1</File>
<File Build="0" Shared="True" ReferenceFunction="Invoke-Get-NetboxVersion_ps1" ExportFunctions="True">Functions\Setup\Get-NetboxVersion.ps1</File>
</Files> </Files>
<StartupScript>R:\Netbox\NetboxPS\Test-Module.ps1</StartupScript> <StartupScript>R:\Netbox\NetboxPS\Test-Module.ps1</StartupScript>
</Project> </Project>

View file

@ -3,7 +3,7 @@
# #
# Generated by: Ben Claussen # Generated by: Ben Claussen
# #
# Generated on: 2021-03-31 # Generated on: 2021-07-22
# #
@{ @{
@ -12,7 +12,7 @@
RootModule = 'NetboxPS.psm1' RootModule = 'NetboxPS.psm1'
# Version number of this module. # Version number of this module.
ModuleVersion = '1.3.3' ModuleVersion = '1.4'
# Supported PSEditions # Supported PSEditions
# CompatiblePSEditions = @() # CompatiblePSEditions = @()

View file

@ -471,56 +471,69 @@ function Connect-NetboxAPI {
<# <#
.SYNOPSIS .SYNOPSIS
Connects to the Netbox API and ensures Credential work properly Connects to the Netbox API and ensures Credential work properly
.DESCRIPTION .DESCRIPTION
Connects to the Netbox API and ensures Credential work properly Connects to the Netbox API and ensures Credential work properly
.PARAMETER Hostname .PARAMETER Hostname
The hostname for the resource such as netbox.domain.com The hostname for the resource such as netbox.domain.com
.PARAMETER Credential .PARAMETER Credential
Credential object containing the API key in the password. Username is not applicable Credential object containing the API key in the password. Username is not applicable
.PARAMETER Scheme .PARAMETER Scheme
Scheme for the URI such as HTTP or HTTPS. Defaults to HTTPS Scheme for the URI such as HTTP or HTTPS. Defaults to HTTPS
.PARAMETER Port .PARAMETER Port
Port for the resource. Value between 1-65535 Port for the resource. Value between 1-65535
.PARAMETER URI .PARAMETER URI
The full URI for the resource such as "https://netbox.domain.com:8443" The full URI for the resource such as "https://netbox.domain.com:8443"
.PARAMETER SkipCertificateCheck
A description of the SkipCertificateCheck parameter.
.PARAMETER TimeoutSeconds
The number of seconds before the HTTP call times out. Defaults to 30 seconds
.EXAMPLE .EXAMPLE
PS C:\> Connect-NetboxAPI -Hostname "netbox.domain.com" PS C:\> Connect-NetboxAPI -Hostname "netbox.domain.com"
This will prompt for Credential, then proceed to attempt a connection to Netbox This will prompt for Credential, then proceed to attempt a connection to Netbox
.NOTES .NOTES
Additional information about the function. Additional information about the function.
#> #>
[CmdletBinding(DefaultParameterSetName = 'Manual')] [CmdletBinding(DefaultParameterSetName = 'Manual')]
param param
( (
[Parameter(ParameterSetName = 'Manual', [Parameter(ParameterSetName = 'Manual',
Mandatory = $true)] Mandatory = $true)]
[string]$Hostname, [string]$Hostname,
[Parameter(Mandatory = $false)] [Parameter(Mandatory = $false)]
[pscredential]$Credential, [pscredential]$Credential,
[Parameter(ParameterSetName = 'Manual')] [Parameter(ParameterSetName = 'Manual')]
[ValidateSet('https', 'http', IgnoreCase = $true)] [ValidateSet('https', 'http', IgnoreCase = $true)]
[string]$Scheme = 'https', [string]$Scheme = 'https',
[Parameter(ParameterSetName = 'Manual')] [Parameter(ParameterSetName = 'Manual')]
[uint16]$Port = 443, [uint16]$Port = 443,
[Parameter(ParameterSetName = 'URI', [Parameter(ParameterSetName = 'URI',
Mandatory = $true)] Mandatory = $true)]
[string]$URI [string]$URI,
[Parameter(Mandatory = $false)]
[switch]$SkipCertificateCheck = $false,
[ValidateNotNullOrEmpty()]
[ValidateRange(1, 65535)]
[uint16]$TimeoutSeconds = 30
) )
if (-not $Credential) { if (-not $Credential) {
try { try {
$Credential = Get-NetboxCredential -ErrorAction Stop $Credential = Get-NetboxCredential -ErrorAction Stop
@ -531,14 +544,29 @@ function Connect-NetboxAPI {
} }
} }
} }
$null = Set-NetboxCredential -Credential $Credential $invokeParams = @{ SkipCertificateCheck = $SkipCertificateCheck; }
if ("Desktop" -eq $PSVersionTable.PsEdition) {
#Remove -SkipCertificateCheck from Invoke Parameter (not supported <= PS 5)
$invokeParams.remove("SkipCertificateCheck")
}
#for PowerShell (<=) 5 (Desktop), Enable TLS 1.1, 1.2 and Disable SSL chain trust
if ("Desktop" -eq $PSVersionTable.PsEdition) {
#Enable TLS 1.1 and 1.2
Set-NetboxCipherSSL
if ($SkipCertificateCheck) {
#Disable SSL chain trust...
Set-NetboxuntrustedSSL
}
}
switch ($PSCmdlet.ParameterSetName) { switch ($PSCmdlet.ParameterSetName) {
'Manual' { 'Manual' {
$uriBuilder = [System.UriBuilder]::new($Scheme, $Hostname, $Port) $uriBuilder = [System.UriBuilder]::new($Scheme, $Hostname, $Port)
} }
'URI' { 'URI' {
$uriBuilder = [System.UriBuilder]::new($URI) $uriBuilder = [System.UriBuilder]::new($URI)
if ([string]::IsNullOrWhiteSpace($uriBuilder.Host)) { if ([string]::IsNullOrWhiteSpace($uriBuilder.Host)) {
@ -546,11 +574,14 @@ function Connect-NetboxAPI {
} }
} }
} }
$null = Set-NetboxHostName -Hostname $uriBuilder.Host $null = Set-NetboxHostName -Hostname $uriBuilder.Host
$null = Set-NetboxCredential -Credential $Credential
$null = Set-NetboxHostScheme -Scheme $uriBuilder.Scheme $null = Set-NetboxHostScheme -Scheme $uriBuilder.Scheme
$null = Set-NetboxHostPort -Port $uriBuilder.Port $null = Set-NetboxHostPort -Port $uriBuilder.Port
$null = Set-NetboxInvokeParams -invokeParams $invokeParams
$null = Set-NetboxTimeout -TimeoutSeconds $TimeoutSeconds
try { try {
Write-Verbose "Verifying API connectivity..." Write-Verbose "Verifying API connectivity..."
$null = VerifyAPIConnectivity $null = VerifyAPIConnectivity
@ -563,18 +594,27 @@ function Connect-NetboxAPI {
throw $_ throw $_
} }
} }
Write-Verbose "Caching API definition" # Write-Verbose "Caching API definition"
$script:NetboxConfig.APIDefinition = Get-NetboxAPIDefinition # $script:NetboxConfig.APIDefinition = Get-NetboxAPIDefinition
#
if ([version]$script:NetboxConfig.APIDefinition.info.version -lt 2.8) { # if ([version]$script:NetboxConfig.APIDefinition.info.version -lt 2.8) {
# $Script:NetboxConfig.Connected = $false
# throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.APIDefinition.info.version)"
# }
Write-Verbose "Checking Netbox version compatibility"
$script:NetboxConfig.NetboxVersion = Get-NetboxVersion
if ([version]$script:NetboxConfig.NetboxVersion.'netbox-version' -lt 2.8) {
$Script:NetboxConfig.Connected = $false $Script:NetboxConfig.Connected = $false
throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.APIDefinition.info.version)" throw "Netbox version is incompatible with this PS module. Requires >=2.8.*, found version $($script:NetboxConfig.NetboxVersion.'netbox-version')"
} else {
Write-Verbose "Found compatible version [$($script:NetboxConfig.NetboxVersion.'netbox-version')]!"
} }
$script:NetboxConfig.Connected = $true $script:NetboxConfig.Connected = $true
Write-Verbose "Successfully connected!" Write-Verbose "Successfully connected!"
#Write-Verbose "Caching static choices" #Write-Verbose "Caching static choices"
#$script:NetboxConfig.Choices.Circuits = Get-NetboxCircuitsChoices #$script:NetboxConfig.Choices.Circuits = Get-NetboxCircuitsChoices
#$script:NetboxConfig.Choices.DCIM = Get-NetboxDCIMChoices # Not completed yet #$script:NetboxConfig.Choices.DCIM = Get-NetboxDCIMChoices # Not completed yet
@ -583,7 +623,7 @@ function Connect-NetboxAPI {
##$script:NetboxConfig.Choices.Secrets = Get-NetboxSecretsChoices # Not completed yet ##$script:NetboxConfig.Choices.Secrets = Get-NetboxSecretsChoices # Not completed yet
##$script:NetboxConfig.Choices.Tenancy = Get-NetboxTenancyChoices ##$script:NetboxConfig.Choices.Tenancy = Get-NetboxTenancyChoices
#$script:NetboxConfig.Choices.Virtualization = Get-NetboxVirtualizationChoices #$script:NetboxConfig.Choices.Virtualization = Get-NetboxVirtualizationChoices
Write-Verbose "Connection process completed" Write-Verbose "Connection process completed"
} }
@ -706,17 +746,17 @@ function Get-ModelDefinition {
#region File Get-NetboxAPIDefinition.ps1 #region File Get-NetboxAPIDefinition.ps1
<# <#
.NOTES .NOTES
=========================================================================== ===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.174 Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.174
Created on: 4/28/2020 11:57 Created on: 4/28/2020 11:57
Created by: Claussen Created by: Claussen
Organization: NEOnet Organization: NEOnet
Filename: Get-NetboxAPIDefinition.ps1 Filename: Get-NetboxAPIDefinition.ps1
=========================================================================== ===========================================================================
.DESCRIPTION .DESCRIPTION
A description of the file. A description of the file.
#> #>
@ -724,16 +764,16 @@ function Get-ModelDefinition {
function Get-NetboxAPIDefinition { function Get-NetboxAPIDefinition {
[CmdletBinding()] [CmdletBinding()]
param () param ()
#$URI = "https://netbox.neonet.org/api/docs/?format=openapi" #$URI = "https://netbox.neonet.org/api/docs/?format=openapi"
$Segments = [System.Collections.ArrayList]::new(@('docs')) $Segments = [System.Collections.ArrayList]::new(@('docs'))
$URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{'format' = 'openapi'} $URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{'format' = 'openapi' }
$URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck $URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck
InvokeNetboxRequest -URI $URI -Timeout 10 InvokeNetboxRequest -URI $URI
} }
#endregion #endregion
@ -1152,11 +1192,11 @@ function Get-NetboxCredential {
[CmdletBinding()] [CmdletBinding()]
[OutputType([pscredential])] [OutputType([pscredential])]
param () param ()
if (-not $script:NetboxConfig.Credential) { if (-not $script:NetboxConfig.Credential) {
throw "Netbox Credentials not set! You may set with Set-NetboxCredential" throw "Netbox Credentials not set! You may set with Set-NetboxCredential"
} }
$script:NetboxConfig.Credential $script:NetboxConfig.Credential
} }
@ -1702,12 +1742,12 @@ function Get-NetboxDCIMSite {
function Get-NetboxHostname { function Get-NetboxHostname {
[CmdletBinding()] [CmdletBinding()]
param () param ()
Write-Verbose "Getting Netbox hostname" Write-Verbose "Getting Netbox hostname"
if ($null -eq $script:NetboxConfig.Hostname) { if ($null -eq $script:NetboxConfig.Hostname) {
throw "Netbox Hostname is not set! You may set it with Set-NetboxHostname -Hostname 'hostname.domain.tld'" throw "Netbox Hostname is not set! You may set it with Set-NetboxHostname -Hostname 'hostname.domain.tld'"
} }
$script:NetboxConfig.Hostname $script:NetboxConfig.Hostname
} }
@ -1745,6 +1785,22 @@ function Get-NetboxHostScheme {
#endregion #endregion
#region File Get-NetboxInvokeParams.ps1
function Get-NetboxInvokeParams {
[CmdletBinding()]
param ()
Write-Verbose "Getting Netbox InvokeParams"
if ($null -eq $script:NetboxConfig.InvokeParams) {
throw "Netbox Invoke Params is not set! You may set it with Set-NetboxInvokeParams -InvokeParams ..."
}
$script:NetboxConfig.InvokeParams
}
#endregion
#region File Get-NetboxIPAMAddress.ps1 #region File Get-NetboxIPAMAddress.ps1
function Get-NetboxIPAMAddress { function Get-NetboxIPAMAddress {
@ -2553,6 +2609,44 @@ function Get-NetboxTenant {
#endregion #endregion
#region File Get-NetboxTimeout.ps1
function Get-NetboxTimeout {
[CmdletBinding()]
[OutputType([uint16])]
param ()
Write-Verbose "Getting Netbox Timeout"
if ($null -eq $script:NetboxConfig.Timeout) {
throw "Netbox Timeout is not set! You may set it with Set-NetboxTimeout -TimeoutSeconds [uint16]"
}
$script:NetboxConfig.Timeout
}
#endregion
#region File Get-NetboxVersion.ps1
function Get-NetboxVersion {
[CmdletBinding()]
param ()
$Segments = [System.Collections.ArrayList]::new(@('status'))
$URIComponents = BuildURIComponents -URISegments $Segments -ParametersDictionary @{
'format' = 'json'
}
$URI = BuildNewURI -Segments $URIComponents.Segments -Parameters $URIComponents.Parameters -SkipConnectedCheck
InvokeNetboxRequest -URI $URI
}
#endregion
#region File Get-NetboxVirtualizationCluster.ps1 #region File Get-NetboxVirtualizationCluster.ps1
<# <#
@ -2969,7 +3063,7 @@ function Get-NetboxVirtualMachineInterface {
#region File InvokeNetboxRequest.ps1 #region File InvokeNetboxRequest.ps1
<# <#
.NOTES .NOTES
=========================================================================== ===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.172 Created with: SAPIEN Technologies, Inc., PowerShell Studio 2020 v5.7.172
@ -2989,44 +3083,46 @@ function InvokeNetboxRequest {
( (
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[System.UriBuilder]$URI, [System.UriBuilder]$URI,
[Hashtable]$Headers = @{ [Hashtable]$Headers = @{
}, },
[pscustomobject]$Body = $null, [pscustomobject]$Body = $null,
[ValidateRange(0, 60)] [ValidateRange(1, 65535)]
[uint16]$Timeout = 5, [uint16]$Timeout = (Get-NetboxTimeout),
[ValidateSet('GET', 'PATCH', 'PUT', 'POST', 'DELETE', 'OPTIONS', IgnoreCase = $true)] [ValidateSet('GET', 'PATCH', 'PUT', 'POST', 'DELETE', 'OPTIONS', IgnoreCase = $true)]
[string]$Method = 'GET', [string]$Method = 'GET',
[switch]$Raw [switch]$Raw
) )
$creds = Get-NetboxCredential $creds = Get-NetboxCredential
$Headers.Authorization = "Token {0}" -f $creds.GetNetworkCredential().Password $Headers.Authorization = "Token {0}" -f $creds.GetNetworkCredential().Password
$splat = @{ $splat = @{
'Method' = $Method 'Method' = $Method
'Uri' = $URI.Uri.AbsoluteUri # This property auto generates the scheme, hostname, path, and query 'Uri' = $URI.Uri.AbsoluteUri # This property auto generates the scheme, hostname, path, and query
'Headers' = $Headers 'Headers' = $Headers
'TimeoutSec' = $Timeout 'TimeoutSec' = $Timeout
'ContentType' = 'application/json' 'ContentType' = 'application/json'
'ErrorAction' = 'Stop' 'ErrorAction' = 'Stop'
'Verbose' = $VerbosePreference 'Verbose' = $VerbosePreference
} }
$splat += Get-NetboxInvokeParams
if ($Body) { if ($Body) {
Write-Verbose "BODY: $($Body | ConvertTo-Json -Compress)" Write-Verbose "BODY: $($Body | ConvertTo-Json -Compress)"
$null = $splat.Add('Body', ($Body | ConvertTo-Json -Compress)) $null = $splat.Add('Body', ($Body | ConvertTo-Json -Compress))
} }
$result = Invoke-RestMethod @splat $result = Invoke-RestMethod @splat
#region TODO: Handle errors a little more gracefully... #region TODO: Handle errors a little more gracefully...
<# <#
try { try {
Write-Verbose "Sending request..." Write-Verbose "Sending request..."
@ -3040,7 +3136,7 @@ function InvokeNetboxRequest {
Write-Verbose "RAW provided...throwing raw exception" Write-Verbose "RAW provided...throwing raw exception"
throw $_ throw $_
} }
Write-Verbose "Converting response to object" Write-Verbose "Converting response to object"
$myError = GetNetboxAPIErrorBody -Response $_.Exception.Response | ConvertFrom-Json $myError = GetNetboxAPIErrorBody -Response $_.Exception.Response | ConvertFrom-Json
} else { } else {
@ -3048,18 +3144,18 @@ function InvokeNetboxRequest {
$myError = $_ $myError = $_
} }
} }
Write-Verbose "MyError is $($myError.GetType().FullName)" Write-Verbose "MyError is $($myError.GetType().FullName)"
if ($myError -is [Exception]) { if ($myError -is [Exception]) {
throw $_ throw $_
} elseif ($myError -is [pscustomobject]) { } elseif ($myError -is [pscustomobject]) {
throw $myError.detail throw $myError.detail
} }
#> #>
#endregion TODO: Handle errors a little more gracefully... #endregion TODO: Handle errors a little more gracefully...
# If the user wants the raw value from the API... otherwise return only the actual result # If the user wants the raw value from the API... otherwise return only the actual result
if ($Raw) { if ($Raw) {
Write-Verbose "Returning raw result by choice" Write-Verbose "Returning raw result by choice"
@ -3936,37 +4032,50 @@ function Remove-NetboxVirtualMachine {
#endregion #endregion
#region File Set-NetboxCipherSSL.ps1
Function Set-NetboxCipherSSL {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessforStateChangingFunctions", "")]
Param( )
# Hack for allowing TLS 1.1 and TLS 1.2 (by default it is only SSL3 and TLS (1.0))
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
}
#endregion
#region File Set-NetboxCredential.ps1 #region File Set-NetboxCredential.ps1
function Set-NetboxCredential { function Set-NetboxCredential {
[CmdletBinding(DefaultParameterSetName = 'CredsObject', [CmdletBinding(DefaultParameterSetName = 'CredsObject',
ConfirmImpact = 'Low', ConfirmImpact = 'Low',
SupportsShouldProcess = $true)] SupportsShouldProcess = $true)]
[OutputType([pscredential])] [OutputType([pscredential])]
param param
( (
[Parameter(ParameterSetName = 'CredsObject', [Parameter(ParameterSetName = 'CredsObject',
Mandatory = $true)] Mandatory = $true)]
[pscredential]$Credential, [pscredential]$Credential,
[Parameter(ParameterSetName = 'UserPass', [Parameter(ParameterSetName = 'UserPass',
Mandatory = $true)] Mandatory = $true)]
[securestring]$Token [securestring]$Token
) )
if ($PSCmdlet.ShouldProcess('Netbox Credentials', 'Set')) { if ($PSCmdlet.ShouldProcess('Netbox Credentials', 'Set')) {
switch ($PsCmdlet.ParameterSetName) { switch ($PsCmdlet.ParameterSetName) {
'CredsObject' { 'CredsObject' {
$script:NetboxConfig.Credential = $Credential $script:NetboxConfig.Credential = $Credential
break break
} }
'UserPass' { 'UserPass' {
$script:NetboxConfig.Credential = [System.Management.Automation.PSCredential]::new('notapplicable', $Token) $script:NetboxConfig.Credential = [System.Management.Automation.PSCredential]::new('notapplicable', $Token)
break break
} }
} }
$script:NetboxConfig.Credential $script:NetboxConfig.Credential
} }
} }
@ -4277,14 +4386,14 @@ function Set-NetboxDCIMInterfaceConnection {
function Set-NetboxHostName { function Set-NetboxHostName {
[CmdletBinding(ConfirmImpact = 'Low', [CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)] SupportsShouldProcess = $true)]
[OutputType([string])] [OutputType([string])]
param param
( (
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[string]$Hostname [string]$Hostname
) )
if ($PSCmdlet.ShouldProcess('Netbox Hostname', 'Set')) { if ($PSCmdlet.ShouldProcess('Netbox Hostname', 'Set')) {
$script:NetboxConfig.Hostname = $Hostname.Trim() $script:NetboxConfig.Hostname = $Hostname.Trim()
$script:NetboxConfig.Hostname $script:NetboxConfig.Hostname
@ -4338,6 +4447,25 @@ function Set-NetboxHostScheme {
#endregion #endregion
#region File Set-NetboxInvokeParams.ps1
function Set-NetboxInvokeParams {
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)]
[OutputType([string])]
param(
[Parameter(Mandatory = $true)]
[array]$InvokeParams
)
if ($PSCmdlet.ShouldProcess('Netbox Invoke Params', 'Set')) {
$script:NetboxConfig.InvokeParams = $InvokeParams
$script:NetboxConfig.InvokeParams
}
}
#endregion
#region File Set-NetboxIPAMAddress.ps1 #region File Set-NetboxIPAMAddress.ps1
<# <#
@ -4534,6 +4662,52 @@ function Set-NetboxIPAMPrefix {
#endregion
#region File Set-NetboxTimeout.ps1
function Set-NetboxTimeout {
[CmdletBinding(ConfirmImpact = 'Low',
SupportsShouldProcess = $true)]
[OutputType([uint16])]
param
(
[Parameter(Mandatory = $false)]
[ValidateRange(1, 65535)]
[uint16]$TimeoutSeconds = 30
)
if ($PSCmdlet.ShouldProcess('Netbox Timeout', 'Set')) {
$script:NetboxConfig.Timeout = $TimeoutSeconds
$script:NetboxConfig.Timeout
}
}
#endregion
#region File Set-NetboxUnstrustedSSL.ps1
Function Set-NetboxUntrustedSSL {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessforStateChangingFunctions", "")]
Param( )
# Hack for allowing untrusted SSL certs with https connections
Add-Type -TypeDefinition @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy
}
#endregion #endregion
#region File Set-NetboxVirtualMachine.ps1 #region File Set-NetboxVirtualMachine.ps1
@ -4691,18 +4865,18 @@ function SetupNetboxConfigVariable {
( (
[switch]$Overwrite [switch]$Overwrite
) )
Write-Verbose "Checking for NetboxConfig hashtable" Write-Verbose "Checking for NetboxConfig hashtable"
if ((-not ($script:NetboxConfig)) -or $Overwrite) { if ((-not ($script:NetboxConfig)) -or $Overwrite) {
Write-Verbose "Creating NetboxConfig hashtable" Write-Verbose "Creating NetboxConfig hashtable"
$script:NetboxConfig = @{ $script:NetboxConfig = @{
'Connected' = $false 'Connected' = $false
'Choices' = @{ 'Choices' = @{
} }
'APIDefinition' = $null 'APIDefinition' = $null
} }
} }
Write-Verbose "NetboxConfig hashtable already exists" Write-Verbose "NetboxConfig hashtable already exists"
} }
@ -4783,11 +4957,11 @@ function ThrowNetboxRESTError {
function VerifyAPIConnectivity { function VerifyAPIConnectivity {
[CmdletBinding()] [CmdletBinding()]
param () param ()
$uriSegments = [System.Collections.ArrayList]::new(@('extras')) $uriSegments = [System.Collections.ArrayList]::new(@('extras'))
$uri = BuildNewURI -Segments $uriSegments -Parameters @{'format' = 'json'} -SkipConnectedCheck $uri = BuildNewURI -Segments $uriSegments -Parameters @{'format' = 'json' } -SkipConnectedCheck
InvokeNetboxRequest -URI $uri InvokeNetboxRequest -URI $uri
} }