cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
3128
Views
0
Helpful
4
Comments
dchosnek
Cisco Employee
Cisco Employee

Presentation1.png

PowerShell has been growing in popularity since it became an open-source and cross-platform language in 2016. It's ability to pipe the output of one command into the input of the next command enables developers to get a lot accomplished with a single line of code while maintaining readability with its Verb-Noun cmdlet format (like Get-Help). In this blog, I'll show you how to get started with the PowerShell SDK for Intersight and use some of the PowerShell language constructs with the API.
 
PowerShell is, of course, included in every installation of Microsoft Windows, but I run it on my Mac. I installed PowerShell using Homebrew, and I'm currently running PowerShell Core 7.3.4 and Intersight.PowerShell module version 1.0.11.10371.
 
For all SDKs, you should always consult the Intersight Developer Center for the latest version and repository of examples. The PowerShell SDK is now available on the Microsoft PSGallery, so it is easily installed from a PS prompt using the following command.
 
Install-Module -Name Intersight.PowerShell
 

Basic configuration

 
Authentication is a big benefit of using an Intersight SDK. Every API call is properly formatted with the appropriate authentication headers courtesy of the SDK. You just have to supply an API key and secret and the SDK does the rest. To ensure you never accidentally upload your API key to source control, it is best to set your API key and secret as local environment variables. In PowerShell, that can be done by adding the appropriate lines to your PowerShell $PROFILE or simply executing these commands:
 
$env:INTERSIGHT_API_KEY_ID='5b4f48a96...'
$env:INTERSIGHT_API_PRIVATE_KEY='/path/to/secret/intersight-v3.txt'
 
I truncated the key ID, but you should use single quotes exactly as I've shown above. For PowerShell, you should use an Intersight v3 key. Generating a new key is easy, but the API key secret can only be displayed or downloaded when the key is created. If you misplace the secret, your only option is to delete the key and create a new one.
 
Note that the key you create will have the Intersight role that you have when you create the key. If you create the key while logged in as an Account Administrator, that key will have Account Administrator privileges. But if you create the key while logged in with the Read-Only role, that key will have Read-Only privileges. Be careful about creating a key with more privileges than you actually need.
 
In order for the SDK to properly authenticate on your behalf, you have to configure it with the correct API keys (which again I set as environment variables on my machine) and a pointer to your instance of Intersight. For users of the SaaS platform, your "instance" is simply intersight.com while for users of an appliance, this is the URL of your appliance. The PowerShell SDK examples repository on GitHub contains a simple configuration script, so getting ready to use the SDK involves two steps:
  1. Set local environment variables
  2. Run the api-config.ps1 script
 

Basic navigation

 
My favorite part about using the Intersight PowerShell SDK is that it's PowerShell. I can use all the native constructs, methods, and functions available for any PowerShell script. For example, I can retrieve a list of all PowerShell cmdlets that start with "Write" like this:
 
PS > Get-Command Write-*   

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Write-Debug                                        7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Error                                        7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Host                                         7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Information                                  7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Output                                       7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Progress                                     7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Verbose                                      7.0.0.0    Microsoft.PowerShell.Utility
Cmdlet          Write-Warning                                      7.0.0.0    Microsoft.PowerShell.Utility
 
That extends to the Intersight SDK as well because it's just a PowerShell module.
 
PS > Get-Command Get*organization* -Module Intersight.PowerShell

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Get-IntersightCloudAwsOrganizationalUnit           1.0.11.10… Intersight.PowerShell
Cmdlet          Get-IntersightCloudTfcOrganization                 1.0.11.10… Intersight.PowerShell
Cmdlet          Get-IntersightOrganizationOrganization             1.0.11.10… Intersight.PowerShell
 
If I'm unsure how to use a cmdlet, I can use PowerShell's built-in help cmdlet, Get-Help.
 
PS > Get-Help Get-IntersightOrganizationOrganization
 
Another way to learn about a cmdlet is to use PowerShell's Get-Member cmdlet
 
PS > Get-IntersightOrganizationOrganization | Get-Member
 
Let's not forget tab completion! Typing a cmdlet followed by a dash and hitting TAB twice will show all the parameters available with that cmdlet. This is very helpful!
 
PS > Get-IntersightOrganizationOrganization -                 
Account            Moid              Select        Orderby           Debug                InformationVariable  
AccountMoid        Name              Filter        Apply             ErrorAction          OutVariable          
CreateTime         Parent            Expand        Tag               WarningAction        OutBuffer            
Description        SharedScope       Skip          Json              InformationAction    PipelineVariable     
DomainGroupMoid    Count             Top           WithHttpInfo      ErrorVariable        
ModTime            InlineCount       At            Verbose           WarningVariable
 

Retrieving an organization

Now I would like to put all this exploring to use and retrieve the details of an Intersight organization in my account. The output from my tab completion example shows that "Name" is one of the options available for retrieving an organization. So what happens if I try to retrieve the organization named "default" (which exists in every Intersight account) using the Name parameter?
 
PS > Get-IntersightOrganizationOrganization -Name default | select Moid

Moid
----
5ddf1d456972652d30bc0a10
 
That was easy!
 

PowerShell params versus Intersight params

 
If you read my blog about using the API browser, you'll probably recognize some key words in tab completion exercise above. Skip, Top, Count, Apply, Orderby, Select, and Filter are all query parameters that the Intersight API (and PowerShell SDK) support, but it is much easier for someone familiar with PowerShell to use PowerShell native constructs than to read about how to properly format Intersight API query parameters. Consider these two lines of code that do the same thing... the first command would feel more comfortable (and be more readable) to most PowerShell developers.
 
Get-IntersightOrganizationOrganization -Name default | select Moid
Get-IntersightOrganizationOrganization -Filter 'Name eq default' -Select Moid
 
The main difference between between these two lines is whether the processing occurs in the cloud or on your local machine. For a small payload, it really doesn't matter. You should do whatever is more comfortable for you. The only occasion in which I've found using the Intersight query parameters to be a better approach is when I'm expecting more than 100 entries in the response. The default page size of the API is 100, so if I want to process a huge data source like the Intersight Audit Logs, I'll use the aggregation query parameters built into the Intersight API rather than trying to copy the entire audit log to my local machine for local processing.
 

Creating a policy

 
If I want to create a new NTP policy, I can use a familiar command to search for the right cmdlet:
 
PS > Get-Command *ntp* -Module Intersight.PowerShell
 
The two cmdlets below appear promising. Which one is correct? I used Get-Help, and the description for the first cmdlet states "Initialize cmdlet is used to instantiate the object of complex type in the Powershell session, it does not create the object on the server." Initialize is useful if it will take me a few lines of code to specify the policy, but for something as simple as NTP, I can just use the New cmdlet.
 
Initialize-IntersightNtpPolicy
New-IntersightNtpPolicy
 
Recall that tab completion can display all available options that I might type next. This will come in handy to display all available parameters that I have to define. It will also come in handy to display all available timezones so I can pick the right one without having to consult any documentation.
 
First I'll display all available NTP policy parameters (I pressed TAB twice after the dash):
 
PS > New-IntersightNtpPolicy - 
AdditionalProperties     Moid                   Tags                   Debug                  WarningVariable          
ApplianceAccount         Name                   Timezone               ErrorAction            InformationVariable      
AuthenticatedNtpServers  NtpServers             Json                   WarningAction          OutVariable              
Description              Organization           WithHttpInfo           InformationAction      OutBuffer                
Enabled                  Profiles               Verbose                ErrorVariable          PipelineVariable 
 
Notice that Timezone is one of the parameters that I must specify, but I don't know the format. Should I use America/Chicago or America\Chicago or AmericaChicago? Or should it be Americas\Chicago (with an S)? I'll use tab completion to determine the right format and spelling for the timezone. First I typed what you see below and hit the TAB key.
 
PS > New-IntersightNtpPolicy -Timezone amer
 
After hitting the TAB key, PowerShell autocompleted "amer" to "America" as shown below, but I'm not done yet.
 
PS > New-IntersightNtpPolicy -Timezone America
 
If I hit TAB again, I'll get the full list of every timezone in America, courtesy of PowerShell. I truncated the list to just two rows, but there are actually 15 rows timezones displayed just for the Americas.
 
PS intersight-powershell-utils> New-IntersightNtpPolicy -Timezone America                                                                        AmericaAnchorage      AmericaChicago        AmericaHalifax        AmericaMontevideo         AmericaSantiago
AmericaBelem          AmericaDenver         AmericaLima           AmericaParamaribo         AmericaThule
 
Now that I know how to format the timezone properly, I'll go through the entire sequence of creating an NTP policy. I spaced the parameters on separate lines for readability, but it's obviously not required. I omitted the optional -Description parameter.
 
PS > $org = Get-IntersightOrganizationOrganization -Name default
PS > $ntp = New-IntersightNtpPolicy -Timezone AmericaChicago                   `
                                    -Name blogNtp                              ` 
                                    -Enabled $true                             `
                                    -NtpServers @("172.16.1.90","172.16.1.91") `
                                    -Organization $org
PS > $ntp.Moid
644adc4662757230011dd904
 
Since I saved the newly created NTP policy as a variable, I can easily remove it with a simple command:
 
PS > Remove-IntersightNtpPolicy -Moid $ntp.Moid
 
If I hadn't saved the NTP policy (and it's Moid), I could still locate it by name like I located the default organization and then delete it. Look at the command below and the power of PowerShell piping!
 
PS > Get-IntersightNtpPolicy -Name blogNtp | Remove-IntersightNtpPolicy
 

Conclusion

 
The Intersight PowerShell SDK is the ideal tool for the developer who knows and loves PowerShell. It makes consuming and the Intersight API just as straightforward as using any standard PowerShell module. Make sure to check https://intersight.com/apidocs/downloads/ for the location of a repository of examples that you can leverage. Also, there are more "getting started" level instructions at the project's GitHub repo at https://github.com/CiscoDevNet/intersight-powershell. Happy PowerShell-ing!
 
 
4 Comments
dchosnek
Cisco Employee
Cisco Employee

There is now a YouTube video related to this article: https://www.youtube.com/watch?v=uFdPtV-Mi20

jskizel12
Level 1
Level 1

This is a great article and video! Thank you so much.  

 

I am running into an issue with the parameter...

HttpSigningHeader = @("(request-target)", "Host", "Date", "Digest").

 

Where do I find this information?  The youtube video just had you run the script. I have looked up some details on the HTTP Signing Header and I am not able to find anything that it generated from intersight.com that I would be able to use.


Thanks again!

dchosnek
Cisco Employee
Cisco Employee

@jskizel12 what issue are you having? You can read more about authentication here: https://github.com/CiscoDevNet/intersight-powershell#authentication

Make sure you're setting up the ApiParams as shown below. This snippet is taken from the api_config.ps1 script posted here.

$ApiParams = @{ 
BasePath = $BasePath
ApiKeyId = $ApiKeyId
ApiKeyFilePath = $ApiKeyFilePath
HttpSigningHeader = @("(request-target)", "Host", "Date", "Digest")
}

 

jskizel12
Level 1
Level 1

Hey @dchosnek! I really appreciate you responding to this post. I am able to follow the YouTube video and get everything set up. But when the script runs it errors out at line 39 when it is trying to set the configurations to the parameters that I have set.

The error is "error calling GetOrganizationOrganizationList: Specified value has invalid Control characters. (Parameter 'value').

Does the 'value' have to do with the ApiKeyID/FilePath parameter?  I am going through the api-config script and I cannot find "GetOrganizationOrganizationList" in the code.

Thanks for the help!

Getting Started

Find answers to your questions by entering keywords or phrases in the Search bar above. New here? Use these resources to familiarize yourself with the community: