如何通过Powershell中的IAM角色过滤AWS实例并获取该实例的私有IP地址? [英] How can I filter AWS Instances by IAM role in powershell and get the private ip address of that instance?

查看:146
本文介绍了如何通过Powershell中的IAM角色过滤AWS实例并获取该实例的私有IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个脚本,该脚本可以根据分配给其的IAM角色过滤AWS实例,然后获取其私有IP地址. 我最近问过类似的问题:通过关联的IAM过滤ec2实例在boto中扮演的角色,答案非常有效. 现在,除了Windows PowerShell,我想做同样的事情.

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.

我知道PowerShell不能像boto那样提供出色的功能,但是我知道有一个适用于PowerShell的AWS工具套件,您可以使用它来获取有关实例的信息.

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

这大致就是我的代码在boto上的样子,它通过IAM角色过滤实例,然后将其私有IP地址存储在列表中.

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)  

在PowerShell中这样做的等效方法是什么?

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

推荐答案

在弄清楚代码之前,我不得不尝试一下代码.事实证明,我可以使用相同的过滤器参数&值,就像我在boto代码中所做的一样!!
这是我的代码和输出:

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:

代码:

$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

输出:

PS > & "pathtocode.ps1"
10.200.1.11
10.200.1.45
10.200.1.132

这篇关于如何通过Powershell中的IAM角色过滤AWS实例并获取该实例的私有IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆