How can I filter AWS Instances by IAM role in powe

2019-08-08 15:48发布

问题:

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?

回答1:

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