def tag_resources_with_retry()

in TerraformScripts/sc_terraform_wrapper/terraform_tag.py [0:0]


def tag_resources_with_retry(client, arns, tags, nth_try):
    print('Tagging try #{}. Attempt to tag ARNs: {}'.format(nth_try, arns))

    failed_arns = []
    ignored_arns = []

    for arn in arns:
        error_code = None
        try:
            response = client.tag_resources(
                ResourceARNList=[arn],
                Tags=tags
            )
            if response.get('FailedResourcesMap'):
                error_code = next(iter(response['FailedResourcesMap'].values()))['ErrorCode']
        except ClientError as e:
            error_code = e.response['Error']['Code']

        if error_code:
            if error_code == 'InvalidParameterException':
                ignored_arns.append(arn)
            else:
                failed_arns.append(arn)

    if ignored_arns:
        print('Some ARNs are invalid for tagging. Ignoring: ' + ''.join(ignored_arns))

    # retry failed resources with backoff
    if failed_arns:
        if nth_try <= TAG_RETRY_TIMES:
            # Exponential backoff with full jitter. Reference:
            # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
            temp = min(RETRY_DELAY_CAP, RETRY_DELAY_BASE * 2 ** nth_try)
            delay = temp / 2 + random.uniform(0, temp / 2)
            time.sleep(delay)
            print('Retry tagging #{}'.format(nth_try))
            return tag_resources_with_retry(client, failed_arns, tags, nth_try + 1)
        else:
            print('Tagging failed on {}'.format(failed_arns))