|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Script for assign an instance policy to the current machine. |
| 4 | +""" |
| 5 | + |
| 6 | +import argparse |
| 7 | +import urllib.request |
| 8 | +import logging |
| 9 | +import sys |
| 10 | +import time |
| 11 | + |
| 12 | +import boto3 |
| 13 | +import botocore |
| 14 | + |
| 15 | +LOGGER = logging.getLogger(__name__) |
| 16 | + |
| 17 | +def _get_local_instance_id(): |
| 18 | + return urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode() |
| 19 | + |
| 20 | +def _has_instance_profile(): |
| 21 | + base_url = "http://169.254.169.254/latest/meta-data/iam/security-credentials/" |
| 22 | + try: |
| 23 | + print("Reading: " + base_url) |
| 24 | + iam_role = urllib.request.urlopen(base_url).read().decode() |
| 25 | + except urllib.error.HTTPError as e: |
| 26 | + print(e) |
| 27 | + if e.code == 404: |
| 28 | + return False |
| 29 | + raise e |
| 30 | + |
| 31 | + try: |
| 32 | + url = base_url + iam_role |
| 33 | + print("Reading: " + url) |
| 34 | + req = urllib.request.urlopen(url) |
| 35 | + except urllib.error.HTTPError as e: |
| 36 | + print(e) |
| 37 | + if e.code == 404: |
| 38 | + return False |
| 39 | + raise e |
| 40 | + |
| 41 | + return True |
| 42 | + |
| 43 | +def _wait_instance_profile(): |
| 44 | + retry = 60 |
| 45 | + while not _has_instance_profile() and retry: |
| 46 | + time.sleep(5) |
| 47 | + retry -= 1 |
| 48 | + |
| 49 | + if retry == 0: |
| 50 | + raise ValueError("Timeout on waiting for instance profile") |
| 51 | + |
| 52 | +def _assign_instance_policy(iam_instance_arn): |
| 53 | + |
| 54 | + if _has_instance_profile(): |
| 55 | + print("IMPORTANT: Found machine already has instance profile, skipping the assignment") |
| 56 | + return |
| 57 | + |
| 58 | + instance_id = _get_local_instance_id() |
| 59 | + |
| 60 | + ec2_client = boto3.client("ec2", 'us-east-1') |
| 61 | + |
| 62 | + #https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.associate_iam_instance_profile |
| 63 | + try: |
| 64 | + response = ec2_client.associate_iam_instance_profile( |
| 65 | + IamInstanceProfile={ |
| 66 | + 'Arn' : iam_instance_arn, |
| 67 | + }, |
| 68 | + InstanceId = instance_id) |
| 69 | + |
| 70 | + print(response) |
| 71 | + |
| 72 | + # Wait for the instance profile to be assigned by polling the local instance metadata service |
| 73 | + _wait_instance_profile() |
| 74 | + |
| 75 | + except botocore.exceptions.ClientError as ce: |
| 76 | + if ce.response["Error"]["Code"] == "RequestLimitExceeded": |
| 77 | + print("WARNING: RequestLimitExceeded, exiting with error code 2") |
| 78 | + sys.exit(2) |
| 79 | + raise |
| 80 | + |
| 81 | +def main() -> None: |
| 82 | + """Execute Main entry point.""" |
| 83 | + |
| 84 | + parser = argparse.ArgumentParser(description='IAM Assign Instance frontend.') |
| 85 | + |
| 86 | + parser.add_argument('-v', "--verbose", action='store_true', help="Enable verbose logging") |
| 87 | + parser.add_argument('-d', "--debug", action='store_true', help="Enable debug logging") |
| 88 | + |
| 89 | + parser.add_argument('--instance_profile_arn', type=str, help="Name of instance profile") |
| 90 | + |
| 91 | + args = parser.parse_args() |
| 92 | + |
| 93 | + if args.debug: |
| 94 | + logging.basicConfig(level=logging.DEBUG) |
| 95 | + elif args.verbose: |
| 96 | + logging.basicConfig(level=logging.INFO) |
| 97 | + |
| 98 | + _assign_instance_policy(args.instance_profile_arn) |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == "__main__": |
| 102 | + main() |
0 commit comments