aws / aws-tools-for-powershell

The AWS Tools for PowerShell lets developers and administrators manage their AWS services from the PowerShell scripting environment.
Apache License 2.0
239 stars 79 forks source link

Get-IamPolicy is throwing an error when ErrorAction is SlientlyContinue #178

Closed russellaa closed 2 years ago

russellaa commented 3 years ago

Description

Get-IamPolicy is throwing an error when ErrorAction is SlientlyContinue

I am trying to ensure a policy exists. The first time it is run and the policy won't exist and the cmdlet should throw an error message. To get around this I should be able to use ErrorAction SilentlyContinue to not error out. It's still throwing an error message.

Reproduction Steps

try {
    $get = $false
    $getSplat = @{
        PolicyArn   = "arn:aws:iam::${accountID}:policy/$policyName"
        ProfileName = $profileName
        Verbose     = $true
        ErrorAction = 'SilentlyContinue'
    }
    $get = Get-IAMPolicy @getSplat
    if ($get -eq $false) {
        $splat = @{
            PolicyName     = $policyName
            PolicyDocument = $json 
            Description    = "Read-Write Access"
            ProfileName    = $profileName
            Verbose        = $true
        }
        New-IAMPolicy @splat
    }
}
catch {
    $ErrorMessage = $_.Exception
    Write-Error $ErrorMessage
}

Logs

PS C:> Get-Error

Exception : Type : System.InvalidOperationException TargetSite : Name : ThrowTerminatingError DeclaringType : System.Management.Automation.MshCommandRuntime, System.Management.Automation, Version=7.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 MemberType : Method Module : System.Management.Automation.dll StackTrace : at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord) Message : Policy arn:aws:iam::099850854730:policy/S3-Bucket-Policy-automationtest-2020-10072 was not found. InnerException : LoggedAt : 10/07/2020 14:31:24 Type : Amazon.IdentityManagement.Model.NoSuchEntityException ErrorCode : NoSuchEntity RequestId : de992788-63c9-4250-a949-49d1b45f5454 StatusCode : NotFound TargetSite : Name : HandleException DeclaringType : Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler MemberType : Method Module : AWSSDK.Core.dll StackTrace : at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) at Amazon.Runtime.Internal.ExceptionHandler1.Handle(IExecutionContext executionContext, Exception exception) at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception) at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext) at Amazon.PowerShell.Cmdlets.IAM.GetIAMPolicyCmdlet.CallAWSServiceOperation(IAmazonIdentityManagementService client, GetPolicyRequest request) at Amazon.PowerShell.Cmdlets.IAM.GetIAMPolicyCmdlet.Execute(ExecutorContext context) Message : Policy arn:aws:iam::099850854730:policy/S3-Bucket-Policy-automationtest-2020-10072 was not found. InnerException : Type : Amazon.Runtime.Internal.HttpErrorResponseException Response : Amazon.Runtime.Internal.Transform.HttpClientResponseData TargetSite : Name : MoveNext DeclaringType : Amazon.Runtime.HttpWebRequestMessage+<GetResponseAsync>d__20, AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=885c28607f98e604 MemberType : Method Module : AWSSDK.Core.dll StackTrace : at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) at Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext) at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext) Message : Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown. Source : AWSSDK.Core HResult : -2146233088 Source : AWSSDK.Core HResult : -2146233088 Source : System.Management.Automation HResult : -2146233079 TargetObject : Amazon.PowerShell.Cmdlets.IAM.GetIAMPolicyCmdlet CategoryInfo : InvalidOperation: (Amazon.PowerShell.C….GetIAMPolicyCmdlet:GetIAMPolicyCmdlet) [Get-IAMPolicy], InvalidOperationException FullyQualifiedErrorId : Amazon.IdentityManagement.Model.NoSuchEntityException,Amazon.PowerShell.Cmdlets.IAM.GetIAMPolicyCmdlet InvocationInfo : MyCommand : Get-IAMPolicy ScriptLineNumber : 1 OffsetInLine : 8 HistoryId : 121 Line : $get = Get-IAMPolicy @getSplat -ErrorAction SilentlyContinue PositionMessage : At line:1 char:8

Environment

Resolution


This is a :bug: bug-report

yobyot commented 3 years ago

Hello,

Is this going to be fixed soon? -ErrorAction SilentlyContinue is incredibly useful when checking the presence/absence of some resource that is required for a script. It eliminates the need to test for $null and makes it less burdensome to parse resources.

For example, in this snippet I want to make sure a valid KMS CMK ARN has been supplied as a parameter to the script. If Get-KmsKey didn't terminate my script (that is, it respected -ErrorAction) on not found conditions, the script would know a) that a valid ARN had been specified and b) that ARN is available in the region the script is running it. That's a lot of work I don't have to do.

Thanks!

if ($cmkArn)
{
    "Specified SSE-KMS"
    # Check to see if the ARN of the CMK is valid.
    # The ARN MUST BE in this format: arn:aws:kms:region:acct-id:key/key-id"
    If (Get-KMSKey -KeyId $cmkArn -ErrorAction SilentlyContinue)
    {
        # Update hashtable with encryption defaults
        $encryptionConfig.ServerSideEncryptionByDefault.Add("ServerSideEncryptionAlgorithm", "aws:kms")
        $encryptionConfig.ServerSideEncryptionByDefault.Add("ServerSideEncryptionKeyManagementServiceKeyId", $cmkArn)
        "Creating S3 bucket with encryption using CMK $cmkArn"
        CreateS3Bucket $bucketName
        DisablePublicAccess $newS3Bucket
        EnableServerSideEncryption $newS3Bucket
    }
    else
    {
        Write-Host "CMK ARN is invalid or key not found. Is it in this region? Exiting" -ForegroundColor Red
    }
}   
else 
{
    Write-Host "No CMK specified but SSE-KMS requested. Exiting" -ForegroundColor Red
    Exit
}
github-actions[bot] commented 2 years ago

We have noticed this issue has not received attention in 1 year. We will close this issue for now. If you think this is in error, please feel free to comment and reopen the issue.