Saturday, April 15, 2017

AWS Powershell Tools Snippets: Powershell Pipes

I'm on another AWS Powershell tools rant. Hopefully after reading this blog post you'll share my appreciation for how useful they are.

Powershell takes the idea of piping commands together (sending that output of one command directly to the input of another) to a whole new level of useful. If you aren't familiar with the concept, it's a great way to make your commands dynamic and intricate. Let's walk through an example.

Let's say you want to list all of your Opsworks instances in an AWS account. You'd probably start by going to the AWS Powershell Tools commandlet reference and find the Get-OPSInstances commandlet. But running it alone will give you the not-so-helpful output below


Looking a little more closely at the documentation you'll find a "StackId" parameter that will give you instances for that stack. Obviously you could go to the console, find a stack, copy the ID, and paste it into the shell, but that feels like a lot of steps.

Instead you could use two commands, connected by a pipe to link they're results together. For example "Get-OpsStacks" piped into 
"Get-OpsInstances". In the command below I'm using the "count" property of powershell lists to find the number of instances returned, which is more than the zero by my first command.


Pretty cool! I was able to pull back instances without going to the console to look up a Stack ID.

This is a pretty basic example, but once you're comfortable with the concept the possibilities are endless. Let's say we wanted to find only Opsworks Stacks that contain the number "901" (we use the "900" range for test instances at my company). You could pipe "Get-OpsStacks" into the "Where" commandlet to filter the Opsworks stacks before you get the instances.

In the example below, I've also used "foreach" commandlet to only print the hostname to keep the output a little smaller.


It's pretty clear that we've got instances from multiple stacks here, so we can make our where filter a little more sophisticated. Let's find instances that are only part of the NodeJS webserver stack.


You can repeat this pattern of piping commands together as many times as you need to get the results you're looking for. Eventually these commands can get long and complicated enough it's better to put them into a file for some formatting and white space, but for quick and dirty work they're pretty useful.