Reputation: 373
I'm trying to have a script automatically create ECR repos for projects as part of the pipeline. I want to check if it already exists first, however describe-repositories
returns an error instead of "nothing", and it's not caught in a try/catch .
try{
$ErrorActionPreference = "Stop"
aws ecr describe-repositories --repository-names "some-project"
}
catch {
aws ecr create-repository --repository-name "some-project"
}
Output:
An error occurred (RepositoryNotFoundException) when calling the DescribeRepositories operation: The repository with name '...' does not exist in the registry with id '...'
Is there a way to capture the error? Edit: Setting $ErrorActionPreference = "Stop" doesn't change behaviour.
Upvotes: 5
Views: 4101
Reputation: 10019
You should be able to leverage $LastExitCode
to tell that an error has occurred (Some minimal AWS CLI documentation on this)
aws ecr describe-repositories --repository-names "some-project"
if ($LastExitCode) {
aws ecr create-repository --repository-name "some-project"
}
If you want the actual error message, you should be able to leverage redirection as described in How to capture error messages thrown by a command?
Really though I think there are two other improvements you can do here:
$repositories = (aws ecr describe-repositories) | ConvertFrom-Json
if ("some-project" -notin $repositories.repositories.repositoryName) {
aws ecr create-repository --repository-name "some-project"
}
$ErrorActionPreference
work.Upvotes: 4