1

I am looking to get a script working that can filter AWS instances according to the IAM role assigned to it and then get the private ip address of it. I had asked a similar question recently: filtering ec2 instances by associated IAM role with boto where the answer has worked wonderfully. Now, I would like to do the same thing except on Windows PowerShell.

I understand that PowerShell does not provide nice features as boto does however I know that there is a AWS Tools Kit for PowerShell which you can use to get information on instances.

I have already setup a profile to run on all sessions.

PS > Set-AWSCredentials -AccessKey AKIAIOSFODNN7EXAMPLE -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY -StoreAs TestUser1
PS > Initialize-AWSDefaults -ProfileName TestUser1 -Region ap-southeast-2

This is roughly what my code looks like on boto where it filters instances by IAM role and then stores its private ip addresses in a list.

instancelist = conn.get_only_instances(filters={"iam-instance-profile.arn": "arn:aws:iam::123456789012:instance-profile/TestRole"})

aList = list()

for instance in instancelist:
    output1 = instance.private_ip_address
    aList.append(output1)  

What would be the equivalent way to do so in PowerShell?

Community
  • 1
  • 1
carol Alex
  • 353
  • 1
  • 3
  • 15

1 Answers1

2

I had to play around with the code before I figured it out. Turns out I could use the same filter parameters & values as I did in my boto code.!
Here is my code and the output:

Code:

$filter = New-Object Amazon.EC2.Model.Filter -Property @{Name = "iam-instance-profile.arn"; Value = "arn:aws:iam::123456789012:instance-profile/TestRole"} 
$ec2 = @(Get-EC2Instance -Filter $filter)
$ec2instances = $ec2.instances  #returns instances with its attributes
$ec2instances.privateipaddress  #returns private ip addresses of the filtered instances

Output:

PS > & "pathtocode.ps1"
10.200.1.11
10.200.1.45
10.200.1.132
carol Alex
  • 353
  • 1
  • 3
  • 15
  • Good work! For future reference, you can find a full list of compatible filters here: http://docs.aws.amazon.com/powershell/latest/reference/items/Get-EC2Instance.html – Anthony Neace Jan 28 '16 at 00:13
  • @AnthonyNeace Thanks! I was on the link you posted on your comment when I was trying to solve this issue earlier - I couldn't find a filter for the iam role `iam-instance-profile.arn` (the one i've used) so I reckon there might be more filters that could be used that isn't all listed there :) – carol Alex Jan 28 '16 at 02:42