【问题标题】:Try/Catch aws cli errors in powershell script在 powershell 脚本中尝试/捕获 aws cli 错误
【发布时间】:2021-02-02 14:11:13
【问题描述】:

我正在尝试让脚本自动为项目创建 ECR 存储库,作为管道的一部分。我想先检查它是否已经存在,但是 describe-repositories 返回一个错误而不是“nothing”,并且它没有被 try/catch 捕获。

try{
    $ErrorActionPreference = "Stop"
    aws ecr describe-repositories --repository-names "some-project"
}
catch {
    aws ecr create-repository --repository-name "some-project"    
}

输出:

An error occurred (RepositoryNotFoundException) when calling the DescribeRepositories operation: The repository with name '...' does not exist in the registry with id '...'

有没有办法捕获错误? 编辑:设置 $ErrorActionPreference = "Stop" 不会改变行为。

【问题讨论】:

  • 您没有显示它,所以我们不知道您是否已将 ErrorAction 设置为 Stop,这是 Try/Catch 工作所必需的。如果支持,请设置首选项或添加到 Try 命令。
  • try/catch 只有终止错误。如果您的错误未终止执行,则它是非终止错误。正如@RetiredGeek 指出的那样,这些会发生什么由$ErrorActionPreference 设置。见about_try_catch_finally
  • 我尝试在第一个 aws 命令之前设置 $ErrorActionPreference = "Stop",但它也没有触发 catch。
  • if($(aws ecr describe-...) -match 'RepositoryNotFoundException'){ aws ecr create-... }
  • throw 错误进入 catch 块

标签: powershell aws-cli


【解决方案1】:

您应该能够利用$LastExitCode 来判断发生了错误(一些minimal AWS CLI documentation 对此)

aws ecr describe-repositories --repository-names "some-project"

if ($LastExitCode) {
    aws ecr create-repository --repository-name "some-project"
}

如果您想要实际的错误消息,您应该能够利用 How to capture error messages thrown by a command? 中所述的重定向


虽然我认为您还可以在此处进行其他两项改进:

  • 不要描述特定的存储库,list them 并查看您想要的存储库是否存在:
$repositories = (aws ecr describe-repositories) | ConvertFrom-Json

if ("some-project" -notin $repositories.repositories.repositoryName) {
    aws ecr create-repository --repository-name "some-project"
}

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多