How can I filter AWS Instances by IAM role in powershell and get the private ip address of that instance?

大兔子大兔子 提交于 2019-12-13 18:40:43

问题


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


来源:https://stackoverflow.com/questions/35029361/how-can-i-filter-aws-instances-by-iam-role-in-powershell-and-get-the-private-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!