【问题标题】:How can I filter AWS Instances by IAM role in powershell and get the private ip address of that instance?如何在 Powershell 中按 IAM 角色过滤 AWS 实例并获取该实例的私有 IP 地址?
【发布时间】:2016-01-28 08:10:50
【问题描述】:

我正在寻找一个脚本,该脚本可以根据分配给它的 IAM 角色过滤 AWS 实例,然后 获取它的私有 IP 地址。 我最近问了一个类似的问题:filtering ec2 instances by associated IAM role with boto 答案非常有效。 现在,我想在 Windows PowerShell 上做同样的事情。

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

我已经设置了一个配置文件以在所有会话上运行。

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

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

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 中执行此操作的等效方法是什么?

【问题讨论】:

    标签: powershell amazon-web-services amazon-ec2 aws-powershell


    【解决方案1】:

    在弄明白之前,我不得不玩弄代码。事实证明,我可以使用与我在 boto 代码中使用的过滤器参数和值相同的过滤器参数和值。!
    这是我的代码和输出:

    代码:

    $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
    

    【讨论】:

    • 干得好!为了将来参考,您可以在此处找到兼容过滤器的完整列表:docs.aws.amazon.com/powershell/latest/reference/items/…
    • @AnthonyNeace 谢谢!当我早些时候尝试解决此问题时,我在您在评论中发布的链接上 - 我找不到 iam 角色iam-instance-profile.arn(我使用过的那个)的过滤器,所以我认为可能有更多过滤器可以使用的没有全部列出的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    相关资源
    最近更新 更多