def handle_security_credentials(role_name): """ Assumes an IAM role and returns the security credentials. Caches results in application context until expiration. :param role_name: the IAM role to assume """ with app.app_context(): credentials = getattr(current_app, '_security_credentials', None) expiration = getattr(current_app, '_security_credentials_expiration', None) if not credentials or datetime.now(pytz.utc) > expiration: role = iam.connect_to_region(REGION).get_role(role_name) session = sts.connect_to_region(REGION).assume_role(role.arn, "Local") credentials = jsonify({ "Code": "Success", "LastUpdated": datetime.now(pytz.utc).strftime(DATE_FORMAT), "Type": "AWS-HMAC", "AccessKeyId": session.credentials.access_key, "SecretAccessKey": session.credentials.secret_key, "Token": session.credentials.session_token, "Expiration": session.credentials.expiration }) current_app._security_credentials = credentials current_app._security_credentials_expiration = datetime.strptime(session.credentials.expiration, DATE_FORMAT).replace(tzinfo=pytz.utc) return credentials
def __init__(self, environment, deployment, region, zone, template=template): # Create connections to AWS components self.cfn_connection = cfn.connect_to_region(region) self.sns_connection = sns.connect_to_region(region) self.vpc_connection = vpc.connect_to_region(region) self.iam_connection = iam.connect_to_region("universal") # Temporary python class -> directory name hack self.lab_dir = self.__class__.__name__.lower() self.stack_name = "-".join( [self.lab_dir, environment, deployment, region, zone]) if environment != '': self.notification_arns = self.get_sns_topic( "cloudformation-notifications-" + environment) self.parameters = [] # Prepare the CFN template self.template_url = "/".join([ os.path.dirname(os.path.realpath(__file__)), self.lab_dir, vpc_provider, template ]) self.template_body = self.read_file(self.template_url, max_template_size) self.validate_template()
def get_username(): iam_connection = iam.connect_to_region( "universal", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) return iam_connection.get_user( )["get_user_response"]["get_user_result"]["user"]["user_name"]
def validate_iam_key(): print "-------------------------------------------------------------" print "Access Keys Created Date" + "\t\t" + "Username" print "-------------------------------------------------------------" conn = iam.connect_to_region('eu-west-1') users = conn.get_all_users() exception_user_list = ["navjot"] for user in users.list_users_response.users: user_name = user['user_name'] if user_name in exception_user_list: continue accessKeys=conn.get_all_access_keys(user_name=user_name) print accessKeys for keysCreatedDate in accessKeys.list_access_keys_response.list_access_keys_result.access_key_metadata: user_name = user['user_name'] create_date = keysCreatedDate['create_date'] access_key_id = keysCreatedDate['access_key_id'] date_delta = datetime.datetime.today() - datetime.datetime.strptime(create_date, '%Y-%m-%dT%H:%M:%SZ') age = date_delta.days if age >= warning_time_limit and age <=disable_time_limit: send_deactivate_email(user_name, age, access_key_id) elif age >= disable_time_limit:
def main(options): sts_connection = STSConnection() # conn = dynamodb.connect_to_region(options.region) assumedRoleObject = sts_connection.assume_role() conn = dynamodb.layer2.Layer2(region=options.region, aws_access_key_id=assumedRoleObject.credentials.access_key, aws_secret_access_key=assumedRoleObject.credentials.secret_key, security_token=assumedRoleObject.credentials.session_token) def create_table(name): table_schema = conn.create_schema( hash_key_name='Key', hash_key_proto_value=str ) table = conn.create_table( name=name, schema=table_schema, read_units=2, write_units=1 ) return table try: create_table(CONFIGURATION_TABLE_NAME) time.sleep(5) except: pass table = conn.get_table(CONFIGURATION_TABLE_NAME) availability_zones = ",".join([zone.name for zone in ec2.connect_to_region(options.region).get_all_zones()]) account_id = iam.connect_to_region(options.region).get_user().arn.split(':')[4] items = { 'account_name': options.account_name, 'account_environment': options.account_environment, 'availability_zones': availability_zones, 'account_id': account_id, 'output_path': options.output_path, 'output_path': options.output_path } if options.accounts: items['accounts'] = options.accounts if options.okta_credential: okta_config = json.load(open(options.okta_credential)) items['okta_credential'] = json.dumps(okta_config) for key, value in items.iteritems(): print key attrs = {'Key': key, 'Value': value} time.sleep(1) my_item = table.new_item(attrs=attrs) print my_item.put()
def get_iam_connection(aws_access_key_id, aws_secret_access_key, region_name): conn = iam.connect_to_region(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) if conn is None: raise Exception("Could not get iam connection to region {}, invalid credentials.".format(region_name)) return conn
def get(name, platform, env): connection = iam.connect_to_region('universal') iam_role_name = "iam-%s-%s-%s" % (name, platform, env) try: instance_profile = connection.get_instance_profile(iam_role_name) except BotoServerError: instance_profile = connection.get_instance_profile('default-iam-role') return instance_profile['get_instance_profile_response']['get_instance_profile_result']['instance_profile']['instance_profile_name']
def get_iam_connection(aws_access_key_id, aws_secret_access_key, region_name): conn = iam.connect_to_region(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) if conn is None: raise Exception( "Could not get iam connection to region {}, invalid credentials.". format(region_name)) return conn
def get(name, platform, env): connection = iam.connect_to_region('universal') iam_role_name = "iam-%s-%s-%s" % (name, platform, env) try: instance_profile = connection.get_instance_profile(iam_role_name) except BotoServerError: instance_profile = connection.get_instance_profile('default-iam-role') return instance_profile['get_instance_profile_response'][ 'get_instance_profile_result']['instance_profile'][ 'instance_profile_name']
def getrole(short, group, platform, environment): iamconn = iam.connect_to_region('universal') if all([short, group, platform, environment]): try: instance_profile = iamconn.get_instance_profile(short+group+"-"+platform+"-"+environment+"-role") return instance_profile['get_instance_profile_response']['get_instance_profile_result']['instance_profile']['instance_profile_name'] except BotoServerError: instance_profile = iamconn.get_instance_profile('default-iam-role') return instance_profile['get_instance_profile_response']['get_instance_profile_result']['instance_profile']['instance_profile_name'] return None
def _put_certificates_into_listener(self): iam_connection = iam.connect_to_region('universal') certificates = iam_connection.get_all_server_certs()['list_server_certificates_response']['list_server_certificates_result']['server_certificate_metadata_list'] for certificate in certificates: if certificate['server_certificate_name'] == self.domain: listener = self.listeners['443'] listener_ssl = listener[1] listener_ssl = listener_ssl + (certificate['arn'],) listener.pop() listener.append(listener_ssl) self.listener = listener return True return False
def _put_certificates_into_listener(self): iam_connection = iam.connect_to_region('universal') certificates = iam_connection.get_all_server_certs( )['list_server_certificates_response'][ 'list_server_certificates_result'][ 'server_certificate_metadata_list'] for certificate in certificates: if certificate['server_certificate_name'] == self.domain: listener = self.listeners['443'] listener_ssl = listener[1] listener_ssl = listener_ssl + (certificate['arn'], ) listener.pop() listener.append(listener_ssl) self.listener = listener return True return False
def connect_to_region(): aws_connection = ec2.connect_to_region( region_name=app.region_name, aws_access_key_id=session['username'], aws_secret_access_key=session['password'], is_secure=True, validate_certs=False ) iam_connection = iam.connect_to_region( region_name=app.region_name, aws_access_key_id=session['username'], aws_secret_access_key=session['password'], is_secure=True, validate_certs=False ) user_data = iam_connection.get_user()['get_user_response']['get_user_result']['user'] session.update(user_data) return aws_connection
def getrole(short, group, platform, environment): iamconn = iam.connect_to_region('universal') if all([short, group, platform, environment]): try: instance_profile = iamconn.get_instance_profile(short + group + "-" + platform + "-" + environment + "-role") return instance_profile['get_instance_profile_response'][ 'get_instance_profile_result']['instance_profile'][ 'instance_profile_name'] except BotoServerError: instance_profile = iamconn.get_instance_profile('default-iam-role') return instance_profile['get_instance_profile_response'][ 'get_instance_profile_result']['instance_profile'][ 'instance_profile_name'] return None
def __init__(self, environment, deployment, region, zone, template=template): # Create connections to AWS components self.cfn_connection = cfn.connect_to_region(region) self.sns_connection = sns.connect_to_region(region) self.vpc_connection = vpc.connect_to_region(region) self.iam_connection = iam.connect_to_region("universal") # Temporary python class -> directory name hack self.lab_dir = self.__class__.__name__.lower() self.stack_name = "-".join([self.lab_dir, environment, deployment, region, zone]) if environment != '': self.notification_arns = self.get_sns_topic("cloudformation-notifications-" + environment) self.parameters = [] # Prepare the CFN template self.template_url = "/".join([os.path.dirname(os.path.realpath(__file__)), self.lab_dir, vpc_provider, template]) self.template_body = self.read_file(self.template_url, max_template_size) self.validate_template()
def refresh_users(): iam_connection = iam.connect_to_region( region_name=app.region_name, aws_access_key_id=session['username'], aws_secret_access_key=session['password'], is_secure=True, validate_certs=False ) add_users = 0 all_users = iam_connection.get_all_users() for user in all_users['list_users_response']['list_users_result']['users']: u = User(username=user['user_name']) try: db.session.add(u) db.session.commit() except Exception: continue add_users += 1 flash("Added %d users from AWS" % add_users) return redirect("/admin/user/")
def create_ecs_service_role(region, namespace, mappings, parameters, **kwargs): """Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role """ conn = connect_to_region(region) policy = Policy(Statement=[ Statement(Effect=Allow, Resource=["*"], Action=[ ecs.CreateCluster, ecs.DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Poll, ecs.ECSAction("Submit*") ]) ]) conn.put_role_policy("ecsServiceRole", "AmazonEC2ContainerServiceRole", policy.to_json()) return True
def __init__(self, module, env, cluster, zone, template_name='template.json', **optionals): # debug and/or dry-run mode self.debug = optionals['debug'] self.dry_run = optionals['dry_run'] self.enable_debug() self.env = env.strip().lower() self.cluster = snake_case_with_dashes(cluster.strip()) self.zone = zone self.template_name = template_name # for stack names & resources names in template, use only non-default names self.non_default_cluster = self.cluster if self.cluster not in [default_cluster_name] else None # stack name self.module_name = snake_case_with_dashes(module.strip()) self.stack_name = "-".join(filter(None, [self.module_name, self.env, self.non_default_cluster, self.zone])) # params self.parameters = [] # stack tags self.stack_tags = { '{0}:minion:env'.format(org_name): self.env, '{0}:minion:cluster'.format(org_name): self.cluster, '{0}:minion:module'.format(org_name): self.module_name } # Create connections to AWS components aws_access_key_id = get_env_variable('MINION_ACCESS_KEY_ID') aws_secret_access_key = get_env_variable('MINION_SECRET_ACCESS_KEY') self.cfn_connection = cfn.connect_to_region(aws_region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) self.vpc_connection = vpc.connect_to_region(aws_region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) self.iam_connection = iam.connect_to_region("universal", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
def create_ecs_service_role(region, namespace, mappings, parameters, **kwargs): """Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role """ conn = connect_to_region(region) policy = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ecs.CreateCluster, ecs.DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Poll, ecs.ECSAction("Submit*")] ) ]) conn.put_role_policy("ecsServiceRole", "AmazonEC2ContainerServiceRole", policy.to_json()) return True
def _initialise_aws_connections(): _log.info('Initialising AWS Connections') _validate_environment() # Even though the Boto lib can use the environment variables we'll import one # for easier re-use in this script _log.info('Loading credentials from Environment') aws_region = os.getenv('AWS_DEFAULT_REGION') _log.info('Initializing Boto resources') resources = { 'vpc': vpc.connect_to_region(aws_region), 'ec2': ec2.connect_to_region(aws_region), 'elb': elb.connect_to_region(aws_region), 'iam': iam.connect_to_region(aws_region), 'route53': Route53Connection(), 'cloudwatch': cloudwatch.connect_to_region(aws_region), 'region': aws_region } return resources
def handle_security_credentials(role_name): """ Assumes an IAM role and returns the security credentials. Caches results in application context until expiration. :param role_name: the IAM role to assume """ with app.app_context(): credentials = getattr(current_app, '_security_credentials', None) expiration = getattr(current_app, '_security_credentials_expiration', None) if not credentials or datetime.now(pytz.utc) > expiration: role = iam.connect_to_region(REGION).get_role(role_name) session = sts.connect_to_region(REGION).assume_role( role.arn, "Local") credentials = jsonify({ "Code": "Success", "LastUpdated": datetime.now(pytz.utc).strftime(DATE_FORMAT), "Type": "AWS-HMAC", "AccessKeyId": session.credentials.access_key, "SecretAccessKey": session.credentials.secret_key, "Token": session.credentials.session_token, "Expiration": session.credentials.expiration }) current_app._security_credentials = credentials current_app._security_credentials_expiration = datetime.strptime( session.credentials.expiration, DATE_FORMAT).replace(tzinfo=pytz.utc) return credentials
def createIAMCertificate(domain, certificate, key): """ Create a new IAM certificate from ACME and private key. It also fetched the chain certificate from ACME if provided """ # First we fetch the chain certificate chain = requests.get(certificate.cert_chain_uri) chain_certificate = None if chain.status_code == 200: chain_certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, chain.content) iam_connection = iam.connect_to_region(exec_region) res = iam_connection.upload_server_cert( domain['name'] + "-" + datetime.utcnow().strftime("%Y-%m-%dT%H-%M"), crypto.dump_certificate(crypto.FILETYPE_PEM, certificate.body.wrapped).decode("ascii"), crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode("ascii"), crypto.dump_certificate(crypto.FILETYPE_PEM, chain_certificate).decode("ascii"), "/") sleep(10) return res
def __init__(self, yamlFile): self.logger = logging.getLogger(__name__) # load the yaml file and turn it into a dict thefile = open(yamlFile, 'r') rendered_file = pystache.render(thefile.read(), dict(os.environ)) self.stackDict = yaml.safe_load(rendered_file) # Make sure there is only one top level element in the yaml file if len(self.stackDict.keys()) != 1: error_message = ("Need one and only one mega stack name at the" + " top level, found %s") self.logger.critical(error_message % len(self.stackDict.keys())) exit(1) # Now we know we only have one top element, # that must be the mega stack name self.name = self.stackDict.keys()[0] # Find and set the mega stacks region. Exit if we can't find it if 'region' in self.stackDict[self.name]: self.region = self.stackDict[self.name]['region'] else: self.logger.critical("No region specified for mega stack," + " don't know where to build it.") exit(1) if 'account_id' in self.stackDict[self.name]: # Get the account ID for the current AWS credentials iamconn = iam.connect_to_region(self.region) user_response = iamconn.get_user()['get_user_response'] user_result = user_response['get_user_result'] account_id = user_result['user']['arn'].split(':')[4] # Check if the current account ID matches the stack's account ID if account_id != str(self.stackDict[self.name]['account_id']): self.logger.critical("Account ID of stack does not match the" + " account ID of your AWS credentials.") exit(1) self.sns_topic_arn = self.stackDict[self.name].get('sns-topic-arn', []) if isinstance(self.sns_topic_arn, str): self.sns_topic_arn = [self.sns_topic_arn] for topic in self.sns_topic_arn: if topic.split(':')[3] != self.region: self.logger.critical("SNS Topic %s is not in the %s region." % (topic, self.region)) exit(1) self.global_tags = self.stackDict[self.name].get('tags', {}) # Array for holding CFStack objects once we create them self.stack_objs = [] # Get the names of the sub stacks from the yaml file and sort in array self.cf_stacks = self.stackDict[self.name]['stacks'].keys() # Megastack holds the connection to CloudFormation and list of stacks # currently in our region stops us making lots of calls to # CloudFormation API for each stack try: self.cfconn = cloudformation.connect_to_region(self.region) self.cf_desc_stacks = self._describe_all_stacks() except boto.exception.NoAuthHandlerFound as exception: self.logger.critical( "No credentials found for connecting to CloudFormation: %s" % exception) exit(1) # iterate through the stacks in the yaml file and create CFstack # objects for them for stack_name in self.cf_stacks: the_stack = self.stackDict[self.name]['stacks'][stack_name] if type(the_stack) is dict: if the_stack.get('disable', False): warn_message = ("Stack %s is disabled by configuration" + " directive. Skipping") self.logger.warning(warn_message % stack_name) continue local_sns_arn = the_stack.get('sns-topic-arn', self.sns_topic_arn) if isinstance(local_sns_arn, str): local_sns_arn = [local_sns_arn] for topic in local_sns_arn: if topic.split(':')[3] != self.region: error_message = "SNS Topic %s is not in the %s region." self.logger.critical(error_message % (topic, self.region)) exit(1) local_tags = the_stack.get('tags', {}) merged_tags = dict(self.global_tags.items() + local_tags.items()) # Add static cumulus-stack tag merged_tags['cumulus-stack'] = self.name if 'cf_template' in the_stack: self.stack_objs.append( CFStack( mega_stack_name=self.name, name=stack_name, params=the_stack.get('params'), template_name=the_stack['cf_template'], region=self.region, sns_topic_arn=local_sns_arn, depends_on=the_stack.get('depends'), tags=merged_tags ) )
def _connect_iam(region, profile): try: boto_conn = iam.connect_to_region(region, profile_name=profile) except Exception, e: log("ERROR", "Failed to connect to profile %s %s" % (profile, e)) raise
def ensure_server_cert_exists(region, namespace, mappings, parameters, **kwargs): conn = connect_to_region(region) cert_name = kwargs['cert_name'] try: response = conn.get_server_certificate(cert_name) cert_arn = _get_cert_arn_from_response( 'get_server_certificate', response, ) logger.info('certificate exists: %s (%s)', cert_name, cert_arn) except BotoServerError: upload = raw_input( 'Certificate "%s" wasn\'t found. Upload it now? (yes/no) ' % ( cert_name, ) ) if upload != 'yes': return False paths = { 'certificate': kwargs.get('path_to_certificate'), 'private_key': kwargs.get('path_to_private_key'), 'chain': kwargs.get('path_to_chain'), } for key, value in paths.iteritems(): if value is not None: continue path = raw_input('Path to %s (skip): ' % (key,)) if path == 'skip' or not path.strip(): continue full_path = utils.full_path(path) if not os.path.exists(full_path): logger.error('%s path "%s" does not exist', key, full_path) return False paths[key] = full_path parameters = { 'cert_name': cert_name, } for key, path in paths.iteritems(): if not path: continue with open(path) as read_file: contents = read_file.read() if key == 'certificate': parameters['cert_body'] = contents elif key == 'private_key': parameters['private_key'] = contents elif key == 'chain': parameters['cert_chain'] = contents response = conn.upload_server_cert(**parameters) cert_arn = _get_cert_arn_from_response( 'upload_server_certificate', response, ) logger.info( 'uploaded certificate: %s (%s)', cert_name, cert_arn, ) return True
clean_env() self.conf = '%s/%s/%s.ini' % (os.getenv('AWS_CRED_DIR'), acct_name, acct_name) try: boto.config.load_credential_file(self.conf) except IOError, msg: print >> sys.stderr, 'ERROR: %s' % msg return False if service == 's3': self.conn = s3.connect_to_region(region) if service == 'ec2': self.conn = ec2.connect_to_region(region) if service == 'rds': self.conn = rds.connect_to_region(region) if service == 'rds2': self.conn = rds2.connect_to_region(region) if service == 'elb': self.conn = elb.connect_to_region(region) if service == 'sqs': self.conn = sqs.connect_to_region(region) if service == 'emr': self.conn = emr.connect_to_region(region) if service == 'route53': self.conn = route53.connect_to_region(region) if service == 'iam': self.conn = iam.connect_to_region('universal') if not self.conn: print >> sys.stderr, 'ERROR: Unknown service' return False return self.conn
#!/bin/python from boto import iam from datetime import datetime import sys # color codings used in the html report hcol = "#95A5A5" dcol = "#F5B7B1" wcol = "#FFFFFF" # connecting to a region conn=iam.connect_to_region('eu-west-1') # fetching all the users user_list=conn.get_all_users() list1=user_list['list_users_response']['list_users_result']['users'] # construct the html body and table header to show the results html = "<html><table border='1' frames='border' rules='all' cellpadding='4px'>" html = html + "<tr bgcolor='#95A5A5'><th colspan='9'>AWS ACCESS KEY REPORT</th></tr>" html = html + "<tr bgcolor='#95A5A5'><th>Sno</th><th>AWS USER</th><th>ACCESS KEY</th><th>STATUS</th><th>CREATION DATE</th><th>REMARKS</th>" count=0 for i in list1: user=i['user_name'] # fetching all the IAM access keys access=conn.get_all_access_keys(user) if len(access['list_access_keys_response']['list_access_keys_result']['access_key_metadata']) != 0 and len(user) == 4: for j in range(0,len(access['list_access_keys_response']['list_access_keys_result']['access_key_metadata'])):
def get_username(): iam_connection = iam.connect_to_region("universal", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) return iam_connection.get_user()["get_user_response"]["get_user_result"]["user"]["user_name"]
print("Opening port 22 and other stuff in the secgroup ") secgroup.authorize(ip_protocol='tcp', from_port=22, to_port=22, cidr_ip='0.0.0.0/0') secgroup.authorize(ip_protocol='tcp', from_port=0, to_port=65535, cidr_ip='10.0.0.0/16') secgroup.authorize(ip_protocol='icmp', from_port=-1, to_port=-1, cidr_ip='10.0.0.0/16') secgroup.add_tag("Project", PROJECT) iam_con = iam.connect_to_region(REGION) print("Creating instance profile") my_instance_profile = iam_con.create_instance_profile(PROJECT) print("Creating role") my_role = iam_con.create_role('describe_instances') print("Adding role to instance profile") iam_con.add_role_to_instance_profile(PROJECT, 'describe_instances') print("Adding policy to role") ec2ro_policy = """{ "Statement":[{ "Action":["ec2:Describe*"], "Effect":"Allow", "Resource":"*" }] } """
import datetime import dateutil from dateutil import parser import boto environment = ['prod', 'dev'] for env in environment: from boto import iam conn = iam.connect_to_region('ap-southeast-1', profile_name=env) users = conn.get_all_users() timeLimit = datetime.datetime.now() - datetime.timedelta(days=90) print "----------------------------------------------------------" print "Users Having 90 days old IAM keys in " + env + " AWS account:" print "----------------------------------------------------------" print "\n" for user in users.list_users_response.users: accessKeys = conn.get_all_access_keys(user_name=user['user_name']) for keysCreatedDate in accessKeys.list_access_keys_response.list_access_keys_result.access_key_metadata: if (keysCreatedDate['status'] == 'Active'): if parser.parse(keysCreatedDate['create_date']).date( ) <= timeLimit.date(): print " " + user['user_name'] print "\n"
print("Creating route table") route_table = vpc_con.create_route_table(my_vpc.id) route_table.add_tag("Project",PROJECT) print("Associating route table to subnet") vpc_con.associate_route_table(route_table.id, subnetdmz.id) print("Create route to the internet") route = vpc_con.create_route(route_table.id, '0.0.0.0/0', gateway.id) print("Creating Security group") secgroup = vpc_con.create_security_group(PROJECT+'_group','A security_group for Kafka', my_vpc.id) print("Opening port 22 and other stuff in the secgroup ") secgroup.authorize(ip_protocol='tcp', from_port=22, to_port=22, cidr_ip='0.0.0.0/0') secgroup.authorize(ip_protocol='tcp', from_port=0, to_port=65535, cidr_ip='10.0.0.0/16') secgroup.authorize(ip_protocol='icmp', from_port=-1, to_port=-1, cidr_ip='10.0.0.0/16') secgroup.add_tag("Project",PROJECT) iam_con = iam.connect_to_region(REGION) print("Creating instance profile") my_instance_profile = iam_con.create_instance_profile(PROJECT) print("Creating role") my_role = iam_con.create_role('describe_instances') print("Adding role to instance profile") iam_con.add_role_to_instance_profile(PROJECT, 'describe_instances') print("Adding policy to role") ec2ro_policy = """{ "Statement":[{ "Action":["ec2:Describe*"], "Effect":"Allow", "Resource":"*" }] } """
def ensure_server_cert_exists(region, namespace, mappings, parameters, **kwargs): conn = connect_to_region(region) cert_name = kwargs["cert_name"] try: response = conn.get_server_certificate(cert_name) cert_arn = _get_cert_arn_from_response( "get_server_certificate", response, ) logger.info("certificate exists: %s (%s)", cert_name, cert_arn) except BotoServerError: upload = raw_input( "Certificate '%s' wasn't found. Upload it now? (yes/no) " % (cert_name, )) if upload != "yes": return False paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.iteritems(): if value is not None: continue path = raw_input("Path to %s (skip): " % (key, )) if path == "skip" or not path.strip(): continue full_path = utils.full_path(path) if not os.path.exists(full_path): logger.error("%s path '%s' does not exist", key, full_path) return False paths[key] = full_path parameters = { "cert_name": cert_name, } for key, path in paths.iteritems(): if not path: continue with open(path) as read_file: contents = read_file.read() if key == "certificate": parameters["cert_body"] = contents elif key == "private_key": parameters["private_key"] = contents elif key == "chain": parameters["cert_chain"] = contents response = conn.upload_server_cert(**parameters) cert_arn = _get_cert_arn_from_response( "upload_server_certificate", response, ) logger.info( "uploaded certificate: %s (%s)", cert_name, cert_arn, ) return True
def ensure_server_cert_exists(region, namespace, mappings, parameters, **kwargs): conn = connect_to_region(region) cert_name = kwargs["cert_name"] try: response = conn.get_server_certificate(cert_name) cert_arn = _get_cert_arn_from_response( "get_server_certificate", response, ) logger.info("certificate exists: %s (%s)", cert_name, cert_arn) except BotoServerError: upload = raw_input( "Certificate '%s' wasn't found. Upload it now? (yes/no) " % ( cert_name, ) ) if upload != "yes": return False paths = { "certificate": kwargs.get("path_to_certificate"), "private_key": kwargs.get("path_to_private_key"), "chain": kwargs.get("path_to_chain"), } for key, value in paths.iteritems(): if value is not None: continue path = raw_input("Path to %s (skip): " % (key,)) if path == "skip" or not path.strip(): continue full_path = utils.full_path(path) if not os.path.exists(full_path): logger.error("%s path '%s' does not exist", key, full_path) return False paths[key] = full_path parameters = { "cert_name": cert_name, } for key, path in paths.iteritems(): if not path: continue with open(path) as read_file: contents = read_file.read() if key == "certificate": parameters["cert_body"] = contents elif key == "private_key": parameters["private_key"] = contents elif key == "chain": parameters["cert_chain"] = contents response = conn.upload_server_cert(**parameters) cert_arn = _get_cert_arn_from_response( "upload_server_certificate", response, ) logger.info( "uploaded certificate: %s (%s)", cert_name, cert_arn, ) return True
# This script will result all the AWS IAM Users whose access keys are 90 days old import datetime import dateutil from dateutil import parser import boto from boto import iam conn=iam.connect_to_region('ap-southeast-1') users=conn.get_all_users() timeLimit=datetime.datetime.now() - datetime.timedelta(days=90) print "---------------------------------------------" print "Access Keys Date" + "\t\t" + "Username" print "---------------------------------------------" for user in users.list_users_response.users: accessKeys=conn.get_all_access_keys(user_name=user['user_name']) for keysCreatedDate in accessKeys.list_access_keys_response.list_access_keys_result.access_key_metadata: if parser.parse(keysCreatedDate['create_date']).date() <= timeLimit.date(): print(keysCreatedDate['create_date']) + "\t\t" + user['user_name']
def ensure_server_cert_exists(region, namespace, mappings, parameters, **kwargs): conn = connect_to_region(region) cert_name = kwargs['cert_name'] try: response = conn.get_server_certificate(cert_name) cert_arn = _get_cert_arn_from_response( 'get_server_certificate', response, ) logger.info('certificate exists: %s (%s)', cert_name, cert_arn) except BotoServerError: upload = raw_input( 'Certificate "%s" wasn\'t found. Upload it now? (yes/no) ' % (cert_name, )) if upload != 'yes': return False paths = { 'certificate': kwargs.get('path_to_certificate'), 'private_key': kwargs.get('path_to_private_key'), 'chain': kwargs.get('path_to_chain'), } for key, value in paths.iteritems(): if value is not None: continue path = raw_input('Path to %s (skip): ' % (key, )) if path == 'skip' or not path.strip(): continue full_path = utils.full_path(path) if not os.path.exists(full_path): logger.error('%s path "%s" does not exist', key, full_path) return False paths[key] = full_path parameters = { 'cert_name': cert_name, } for key, path in paths.iteritems(): if not path: continue with open(path) as read_file: contents = read_file.read() if key == 'certificate': parameters['cert_body'] = contents elif key == 'private_key': parameters['private_key'] = contents elif key == 'chain': parameters['cert_chain'] = contents response = conn.upload_server_cert(**parameters) cert_arn = _get_cert_arn_from_response( 'upload_server_certificate', response, ) logger.info( 'uploaded certificate: %s (%s)', cert_name, cert_arn, ) return True