-2

In my code I am testing if a user has AWS access keys:

for response in paginator.paginate(UserName=user_name):
    if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys():
        key1 = response['AccessKeyMetadata'][0]['AccessKeyId']

Later in my code I test if key1 exists:

if key1:
    print("\nAccess Key 1: ", key1)
else:
    print("The user does not have any keys.")

If the user has NO keys at all, the function fails with this error:

  File ".\aws_iam_utils.py", line 1430, in rotate_access_keys
    if key1:
UnboundLocalError: local variable 'key1' referenced before assignment

Am I testing if key1 exists correctly? Why am I getting an unbound local error, when it should just print out the statement in the else clause?

bluethundr
  • 1,005
  • 17
  • 68
  • 141

3 Answers3

2

You just need to initialise key1 before the if condition i.e.

key1 = None  # <- You need this line
for response in paginator.paginate(UserName=user_name):
    if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys():
        key1 = response['AccessKeyMetadata'][0]['AccessKeyId']

It is because if the if condition is not met, key1 will not be created in your original code.

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
1

if key1: does not test if key1 exists; it tests if it contains a "truthy" value, and assumes that it does exist.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

You are experiencing the difference between None and null or undefined. Consider three toilet paper holders. One has plenty, one is down to the inner cardboard tube, and one has not even the tube. Or put another way, one has int papers, one has None papers, and one is null or undefined.

As mentioned in the other answer, initialize key1 as None before your if statement to fix it.

key1 = None

To check if a variable exists:

if 'key1' in globals():
    print(key1) # Or whatever
Charles Landau
  • 4,187
  • 1
  • 8
  • 24