ONTAP Rest API Discussions

credentials with powershell


Hello all,

I want to script REST API using powershell. How do I get the credentials (token) and pass it to the commands?

something similar to this:

[the below doesn't work, but I think I am close]

$user = Read-Host “Enter username”
$pass = Read-Host -assecurestring “Enter password” | ConvertTo-SecureString -asPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential($user,$pass)
$token = Invoke-WebRequest -Credential $credential -Method Post -Uri ""

Invoke-RestMethod -method GET -uri '"*&return_records=true&return_timeout=15" ' -header @{"accept" = "application/json"; "authorization" = "Basic $token"}


any input would be appreciated


Re: credentials with powershell


It's "quirky" that's for sure - but I've generally handled it this way and seems to work across PowerShell versions.


...this example is with the ONTAP Select Deploy Utility but should work with ONTAP I would think...

Function ConvertTo-PlainText( [security.securestring]$secure ) 
	$marshal = [Runtime.InteropServices.Marshal] 
	$marshal::PtrToStringAuto( $marshal::SecureStringToBSTR($secure) ) 
Write-Host " Enter Deploy Password: " -NoNewline
$pwd = Read-Host -AsSecureString
$deploy_password = ConvertTo-PlainText $pwd
$pw = ConvertTo-SecureString -String "$deploy_password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $pw
$url = "https://{ip}/api/v3/clusters?name=cluster1"
Invoke-RestMethod -Method 'GET' -Uri $url -Credential $cred -SkipCertificateCheck


I get inconsistent behavior if I try to send the secure password directly to the New-Object call - you'd think they would be the same but perhaps not (?!?).  


The "-SkipCertificateCheck" switch is awesome btw - too bad it's only in PowerShell version 6/7 😁

Re: credentials with powershell


After some testing I realized this actually didn't work correctly in PowerShell Core 7.0 (oops!)


Here's the new code (note the previous "marshal" function is not used and the change to the Read-Host cmdlet):

$pwd = Read-Host " Enter Deploy Password" -AsSecureString
$deploy_password = ConvertFrom-SecureString $pwd -AsPlainText
$pw = ConvertTo-SecureString -String "$deploy_password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $pw
$url = "https://{ip}/api/v3/clusters?name=cluster1"
$result = Invoke-RestMethod -Method 'GET' -Uri $url -Credential $cred -SkipCertificateCheck


I still couldn't pass the secure password directly (?!?)

Re: credentials with powershell




You can pass a [System.Management.Automation.PSCredential] object to your script or function. IE prompt for credentials, then within your code use the credential object to create the header for authentication.  Here is a very basic example based on your code to query a volume on a cluster using a credential object.


  [Parameter(Mandatory = $True, HelpMessage = "The Cluster Name or IP Address")]
  [Parameter(Mandatory = $True, HelpMessage = "The Cluster Name or IP Address")]
  [Parameter(Mandatory = $True, HelpMessage = "The Credential to authenticate to AIQUM")]
#'Set the authentication header.
$auth    = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName + ':' + $Credential.GetNetworkCredential().Password))
$headers = @{"Authorization" = "Basic $auth"}
#'Enumerate the Volume.
[String]$uri = "https://$Cluster/api/storage/volumes?name=$VolumeName&fields=*&return_records=true&return_timeout=15"
  $response = Invoke-RestMethod -method GET -uri $uri -header $headers -ErrorAction Stop
  Write-Host "Enumerated volume ""$VolumeName"" on cluster ""$Cluster"" using URI ""$uri"""
  Write-Warning -Message $("Failed enumerating volume ""$VolumeName"" on cluster ""$Cluster"" using URI ""$uri"". Error " + $_.Exception.Message + ". Status Code " + $_.Exception.Response.StatusCode.value__)


EG if you save that as "GetVolume.ps1" then prompt for a credential object using:


PS C:\> $credential = Get-Credential


Then run the script as follows (IE you can pass the cluster name, volume and credential object as input parameters to your script (or function in library). This way you can avoid having to hard code usernames or passwords in code.


PS C:\Scripts\PowerShell\Projects\ONTAP> .\GetVolume.ps1 -Cluster cluster2.demo.netapp.com -VolumeName volume_001 -Credential $credential
Enumerated volume "volume_001" on cluster "cluster2.demo.netapp.com" using URI "https://cluster2.demo.netapp.com/api/storage/volumes?name=volume_001&fields=*&return_records=true&return_timeout=15"

uuid            : 9838bd47-ab86-11ea-85a7-005056b01307
comment         :
create_time     : 2020-06-11T01:55:15+00:00
language        : c.utf_8
name            : volume_001
size            : 1161850880
state           : online
style           : flexvol
tiering         : @{policy=none}
type            : rw
aggregates      : {@{name=aggr1_cluster2_01; uuid=e329b91b-0633-4186-8c8d-aa4c7191da16}}
clone           : @{is_flexclone=False}
nas             : @{export_policy=}
snapshot_policy : @{name=default}
svm             : @{name=svm21; uuid=503ac2b8-acfe-11e9-8271-005056b03109; _links=}
space           : @{size=1161850880; available=21479424; used=1082281984}
snapmirror      : @{is_protected=False}
metric          : @{timestamp=2020-06-15T04:26:15Z; duration=PT15S; status=ok; latency=; iops=; throughput=}
_links          : @{self=}


If you don't want to be prompted for credentials you could make the credential parameter non-mandatory and checking for cached credentials using the PSTK (Get-NcCredential) so you don't have to pass the credential parameter if they have already been cached.


Loads of examples of using the $Credential parameter as an input into a function in the module libraries i've uploaded to github for AIQUM and VSC 


Hope that helps. Let me know if you have any questions






If this post resolved your issue, help others by selecting ACCEPT AS SOLUTION or adding a KUDO.
Earn Rewards for Your Review!
GPI Review Banner
All Community Forums