我希望有一个脚本可以工作,该脚本可以根据分配给它的 IAM 角色筛选 AWS 实例,然后获取它的私有 IP 地址。我最近问了一个类似的问题:按与 boto 关联的 IAM 角色过滤 ec2 实例,答案效果很好。现在,我想做同样的事情,除了在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中这样做的等效方法是什么?
我想通之前,我必须玩弄代码。事实证明,我可以使用与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