def delete_chef_node(self, nodeId): try: pychef.Node(nodeId, api=self.chef_api).delete(api=self.chef_api) pychef.Client(nodeId, api=self.chef_api).delete(api=self.chef_api) return True except Exception as e: return e
def handle(event, _context): """Lambda Handler""" log_event(event) # If you're using a self signed certificate change # the ssl_verify argument to False with chef.ChefAPI(CHEF_SERVER_URL, get_pem(), USERNAME, ssl_verify=VERIFY_SSL): instance_id = get_instance_id(event) try: search = chef.Search('node', 'ec2_instance_id:' + instance_id) except ChefServerNotFoundError as err: LOGGER.error(err) return False if len(search) != 0: for instance in search: node = chef.Node(instance.object.name) client = chef.Client(instance.object.name) try: node.delete() LOGGER.info('===Node Delete: SUCCESS===') client.delete() LOGGER.info('===Client Delete: SUCCESS===') return True except ChefServerNotFoundError as err: LOGGER.error(err) return False else: LOGGER.info( '=Instance does not appear to be Chef Server managed.=') return True
def _clean_host_attributes(self, config, target_system): """clean node attributes about target system.""" import chef node_name = self._get_node_name(config['fullname']) client_name = self._get_client_name(config['fullname']) node = chef.Node(node_name, api=self.api_) roles_per_target_system = node.get('roles_per_target_system', {}) if target_system in roles_per_target_system: del roles_per_target_system[target_system] node['roles_per_target_system'] = roles_per_target_system if not roles_per_target_system: try: node.delete() client = chef.Client(client_name, api=self.api_) client.delete() logging.debug('delete %s for host %s ', target_system, node_name) except Exception as error: logging.debug('failed to delete %s for host %s: %s', target_system, node_name, error) else: node.run_list = [] for _, roles in roles_per_target_system.items(): for role in roles: node.run_list.append('role[%s]' % role) node.save() logging.debug('node %s is updated for %s', node_name, target_system)
def delete_node(hostname): with chef.ChefAPI(CHEF_SERVER_URL, PEM_KEY, USERNAME): try: # remove client from chef server client = chef.Client(hostname) client.delete() logger.info('Successfully deleted client %s', hostname) # remove node from chef server node = chef.Node(hostname) node.delete() logger.info('Successfully deleted node %s', hostname) except ChefServerNotFoundError as err: logger.error(err)
def lambda_handler(event, context): print("Event received: " + json.dumps(event)) for record in event['Records']: if 'Sns' in record: message = json.loads(record['Sns']['Message']) if message['Event'] == 'autoscaling:EC2_INSTANCE_TERMINATE': instance_id = message['EC2InstanceId'] print("instance_id = " + instance_id) try: chef_api = chef.autoconfigure() except: raise Exception('Could not configure Chef!') try: rows = chef.Search('node', 'ec2_instance_id:' + instance_id) except: raise Exception( 'Could not search for nodes with ec2_instance_id: ' + instance_id) for row in rows: try: n = chef.Node(row['name']) except: raise Exception('Could not fetch node object for ' + row['name']) print("node: " + str(n)) try: c = chef.Client(row['name']) except: raise Exception('Could not fetch client object for ' + row['name']) print("client: " + str(c)) try: n.delete() except: raise Exception('Could not delete node ' + str(n)) try: c.delete() except: raise Exception('Could not delete client ' + str(n)) else: raise Exception('Could not process SNS message')
def handle(event, _context): """Lambda Handler""" log_event(event) #Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6 requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # If you're using a self signed certificate change # the ssl_verify argument to False with chef.ChefAPI(CHEF_SERVER_URL, get_pem(), USERNAME, ssl_verify=VERIFY_SSL): instance_id = get_instance_id(event) try: search = chef.Search('node', 'ec2_instance_id:' + instance_id) except ChefServerNotFoundError as err: LOGGER.error(err) return False if len(search) != 0: for instance in search: node = chef.Node(instance.object.name) client = chef.Client(instance.object.name) try: LOGGER.info('About to delete the node named - ' + node.name) LOGGER.info('About to delete the client named - ' + client.name) if not DEBUG: node.delete() LOGGER.info('===Node Delete: SUCCESS===') client.delete() LOGGER.info('===Client Delete: SUCCESS===') else: LOGGER.info('Would have deleted the node named - ' + node.name + ' here, but we are in DEBUG mode') LOGGER.info('Would have deleted the client named - ' + client.name + ' here, but we are in DEBUG mode') return True except ChefServerNotFoundError as err: LOGGER.error(err) return False else: LOGGER.info( '=Instance does not appear to be Chef Server managed.=') return True
def bake(self): if self.CHEF_RUNLIST: chef_path = os.path.expanduser(self.chef_path) self.chef_api = chef.autoconfigure(chef_path) with self.chef_api: try: node = chef.Node(self.name) node.delete() self.log.info('Removed previous chef node "{node}"'.format( node=self.name)) except chef.exceptions.ChefServerNotFoundError: pass except chef.exceptions.ChefServerError as e: # This gets thrown on chef12 when the client/node does not # exist. if str(e) == 'Forbidden': pass else: self.log.error(str(e)) raise e except Exception as e: self.log.error(str(e)) raise e try: client = chef.Client(self.name) client = client.delete() self.log.info( 'Removed previous chef client "{client}"'.format( client=self.name)) except chef.exceptions.ChefServerNotFoundError: pass except chef.exceptions.ChefServerError as e: # This gets thrown on chef12 when the client/node does not # exist. if str(e) == 'Forbidden': pass else: self.log.error(str(e)) raise e except Exception as e: self.log.error(str(e)) raise e
def clean(self): try: for node_name in chef.Node.list(api=self.api): node = chef.Node(node_name, api=self.api) node.delete() logging.info('delete node %s', node_name) except Exception as error: logging.error('failed to delete some nodes') logging.exception(error) try: for client_name in chef.Client.list(api=self.api): if client_name in ['chef-webui', 'chef-validator']: continue client = chef.Client(client_name, api=self.api) client.delete() logging.info('delete client %s', client_name) except Exception as error: logging.error('failed to delete some clients') logging.exception(error) try: for env_name in chef.Environment.list(api=self.api): if env_name == '_default': continue env = chef.Environment(env_name, api=self.api) env.delete() logging.info('delete env %s', env_name) except Exception as error: logging.error('failed to delete some envs') logging.exception(error) try: for databag_name in chef.DataBag.list(api=self.api): databag = chef.DataBag(databag_name, api=self.api) for item_name, item in databag.items(): item.delete() logging.info( 'delete item %s from databag %s', item_name, databag_name ) except Exception as error: logging.error('failed to delete some databag items') logging.exception(error)
def _delete_node(self, node): """clean node attributes about target system.""" import chef if node is None: raise Exception("Node is None, cannot delete a none node.") node_name = node.name client_name = node_name # Clean log for this node first log_dir_prefix = compass_setting.INSTALLATION_LOGDIR[NAME] self._clean_log(log_dir_prefix, node_name) # Delete node and its client on chef server try: node.delete() client = chef.Client(client_name, api=self.chef_api) client.delete() logging.debug('delete node %s', node_name) except Exception as error: logging.debug('failed to delete node %s, error: %s', node_name, error)