简体   繁体   English

适用于 AWS EC2 多账户的 Powershell 脚本

[英]Powershell Scripts for AWS EC2 Multiaccounts

I have been looking for an example powershell script which would iterate through multiple accounts in AWS and just print EC2 instance info from every account.我一直在寻找一个示例 powershell 脚本,它可以遍历 AWS 中的多个帐户,并且只从每个帐户打印 EC2 实例信息。 I have been using Python/Boto3 to accomplish the same task , but want to learn Powershell way of doing this.我一直在使用 Python/Boto3 来完成同样的任务,但想学习 Powershell 的方法。 I have searched but couldn't find any example of multi account especially as how to get sts token for every account and assume role etc. If anyone could please point me to any such example script if available, that would be great.我已经搜索过但找不到任何多帐户的示例,尤其是如何为每个帐户获取 sts 令牌并承担角色等。如果有人可以指出任何此类示例脚本(如果可用),那就太好了。

Thanks and regards.感谢致敬。

I am assuuming that you would need different credentials for each account.我假设您需要为每个帐户提供不同的凭据。 For each account, you would need to create an AWS credential.对于每个账户,您需要创建一个 AWS 凭证。 For an example of how to do this see:https://timharkin.com/managing-aws-credentials-with-powershell/有关如何执行此操作的示例,请参阅:https ://timharkin.com/managing-aws-credentials-with-powershell/

Once you have the credentials saved, you can use three nested loops to get the info you are looking for.保存凭据后,您可以使用三个嵌套循环来获取您要查找的信息。 Those loops would be Credential->Region-->EC2 Instance.这些循环将是 Credential->Region-->EC2 Instance。 The code for this would be:代码如下:

$AccountCreds = "Credential1","Credential2"
$Regions="ap-northeast-1","ap-northeast-2","ap-south-1","ap-southeast-1","ap-southeast-2","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"

foreach ($credential in $AccountCreds){
    Set-AWSCredential -ProfileName $credential

    foreach($region in $Regions){

        Set-DefaultAWSRegion $region
        try {

            (Get-EC2Instance  ).Instances |Format-Table  -AutoSize | Out-String  -Width 512

        }
        catch {

        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM