# Buggy code
def process(self, resources, event):
    if event is None:
        return
    event = event["detail"]
    utype = event["userIdentity"]["type"]
    if utype not in self.data.get(
        "user-type", ["AssumedRole", "IAMUser", "FederatedUser"]
    ):
        return

    user = None
    if utype == "IAMUser":
        user = event["userIdentity"]["userName"]
        principal_id_value = event["userIdentity"].get("principalId", "")
    elif utype == "AssumedRole" or utype == "FederatedUser":
        user = event["userIdentity"]["arn"]
        prefix, user = user.rsplit("/", 1)
        principal_id_value = event["userIdentity"].get("principalId", "").split(":")[0]
        # instance role
        if user.startswith("i-"):
            return
        # lambda function (old style)
        elif user.startswith("awslambda"):
            return
    if user is None:
        return
    # if the auto-tag-user policy set update to False (or it's unset) then we
    # will skip writing their UserName tag and not overwrite pre-existing values
    if not self.data.get("update", False):
        untagged_resources = []
        # iterating over all the resources the user spun up in this event
        for resource in resources:
            tag_already_set = False
            for tag in resource.get("Tags", ()):
                if tag["Key"] == self.data["tag"]:
                    tag_already_set = True
                    break
            if not tag_already_set:
                untagged_resources.append(resource)
    # if update is set to True, we will overwrite the userName tag even if
    # the user already set a value
    else:
        untagged_resources = resources

    tag_action = self.manager.action_registry.get("tag")
    new_tags = {self.data["tag"]: user}
    # if principal_id_key is set (and value), we'll set the principalId tag.
    principal_id_key = self.data.get("principal_id_tag", None)
    if principal_id_key and principal_id_value:
        new_tags[principal_id_key] = principal_id_value
    for key, value in new_tags.items():
        tag_action({"key": key, "value": value}, self.manager).process(
            untagged_resources
        )
    return new_tags


# Traceback (UnboundLocalError)
[ERROR]    2020-10-27T18:30:32.480Z    ec614241-19ef-4d44-b3a0-400229378905    error during policy execution
Traceback (most recent call last):
File "/var/task/c7n/handler.py", line 166, in dispatch_event
p.push(event, context)
File "/var/task/c7n/policy.py", line 1138, in push
return mode.run(event, lambda_ctx)
File "/var/task/c7n/policy.py", line 526, in run
return PullMode.run(self)
File "/var/task/c7n/policy.py", line 317, in run
results = a.process(resources)
File "/var/task/c7n/resources/asg.py", line 1212, in process
instance_count = sum(list(w.map(self.process_asg, asgs)))
File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 611, in result_iterator
yield fs.pop().result()
File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 439, in result
return self.__get_result()
File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result
raise self._exception
File "/var/lang/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/var/task/c7n/resources/asg.py", line 1230, in process_asg
if not self.manager.config.dryrun and instances:
UnboundLocalError: local variable 'instances' referenced before assignment
[ERROR] 2020-10-27T18:30:32.480Z ec614241-19ef-4d44-b3a0-400229378905 error during policy execution Traceback (most recent call last): File "/var/task/c7n/handler.py", line 166, in dispatch_event p.push(event, context) File "/var/task/c7n/policy.py", line 1138, in push return mode.run(event, lambda_ctx) File "/var/task/c7n/policy.py", line 526, in run return PullMode.run(self) File "/var/task/c7n/policy.py", line 317, in run results = a.process(resources) File "/var/task/c7n/resources/asg.py", line 1212, in process instance_count = sum(list(w.map(self.process_asg, asgs))) File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 611, in result_iterator yield fs.pop().result() File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 439, in result return self.__get_result() File "/var/lang/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result raise self._exception File "/var/lang/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/var/task/c7n/resources/asg.py", line 1230, in process_asg if not self.manager.config.dryrun and instances: UnboundLocalError: local variable 'instances' referenced before assignment

# Fixed code
def process(self, resources, event):
    if event is None:
        return

    user_info = self.get_tag_value(event)

    # will skip writing their UserName tag and not overwrite pre-existing values
    if not self.data.get("update", False):
        untagged_resources = []
        # iterating over all the resources the user spun up in this event
        for resource in resources:
            tag_already_set = False
            for tag in resource.get("Tags", ()):
                if tag["Key"] == self.data["tag"]:
                    tag_already_set = True
                    break
            if not tag_already_set:
                untagged_resources.append(resource)
    # if update is set to True, we will overwrite the userName tag even if
    # the user already set a value
    else:
        untagged_resources = resources

    new_tags = {}
    if user_info["user"]:
        new_tags[self.data["tag"]] = user_info["user"]

    # if principal_id_key is set (and value), we'll set the principalId tag.
    principal_id_key = self.data.get("principal_id_tag", None)
    if principal_id_key and user_info["id"]:
        new_tags[principal_id_key] = user_info["id"]

    if new_tags:
        self.set_resource_tags(new_tags, untagged_resources)
    return new_tags