我希望得到一个可以根据分配给它的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中执行此操作的等效方法是什么?
答案 0 :(得分:2)
在我弄明白之前,我不得不玩代码。结果我可以使用相同的滤波器参数&像我在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