Find iam.amazonaws.com/permitted namespace annotations without ARN

Audun Nes
1 min readMay 10, 2021

--

I wrote a small Python script that can take the output from kubectl and parse its JSON output and loop through namespace annotations for iam.amazonaws.com/permitted that does not contain a full ARN.

#!/user/bin/env python3
import json
import os
import subprocess
from io import TextIOWrapper


def find_namespace_annotations_without_full_arn() -> None:
os.environ.get('KUBECONFIG')
command: str = 'kubectl get ns -o json'
command_list: list = command.split(' ')
out_file: TextIOWrapper = open("output.json", "w")
subprocess.run(command_list, stdout=out_file)

with open('output.json') as json_file:
data: dict = json.load(json_file)
items = data.get('items')
counter: int = 0
for item in items:
hinted_item: dict = item
metadata: dict = hinted_item.get('metadata')
name: str = metadata.get('name')

if metadata:
annotations: dict = metadata.get('annotations')
try:
permissions: str = annotations.get('iam.amazonaws.com/permitted')
try:
iam_id: str = permissions.split(':')[4]
owner_account_id: str = f'arn:aws:iam::{iam_id}:role/'
regex_account_id: str = 'arn:aws:iam::\\d{12}:role'
except IndexError:
None
if owner_account_id not in permissions or regex_account_id in permissions:
counter += 1
print(f'{name} has annotation iam.amazonaws.com/permitted: {permissions}')
except AttributeError:
None

print(f'Found: {counter} occurrences.')


def main():
find_namespace_annotations_without_full_arn()


if __name__ == '__main__':
main()

I hope you can use it as inspiration for similar tasks.

--

--

Audun Nes

Lead Cloud Engineer/Site Reliability Engineer from Copenhagen, Denmark. GitHub: https://github.com/avnes