Beispiel #1
0
def main(*args):
    parser = SaltKeyOptionParser()
    parser.parse_args()
    opts = parser.config
    key = Key(opts)
    my_opts = opts['destroy_vm_reminder']
    key_list = key.name_match(my_opts['key_glob'])

    vms = {}
    rxp = re.compile(my_opts['key_regexp'])
    for status, keys in key_list.items():
        for key in keys:
            m = rxp.match(key)
            if m:
                user = m.group("user")
                if user not in vms:
                    vms[user] = []
                vms[user].append(key)

    smtp = SMTP(**my_opts['email']['smtp'])
    template = Template(my_opts['email']['message_template'])

    for user, keys in vms.items():

        res = requests.get(
            ("{prefix}/securityRealm/user/{user}/api/json").format(
                prefix=my_opts['jenkins']['prefix'], user=user),
            auth=(my_opts['jenkins']['username'],
                  my_opts['jenkins']['api_token']))
        data = json.loads(res.content)
        name = data['fullName']
        email = ''
        for property in data['property']:
            if 'address' in property:
                email = property['address']
                break

        message = template.render(
            name=name,
            vms=keys,
            url="{prefix}/job/{job_name}/build?delay=0sec".format(
                prefix=my_opts['jenkins']['prefix'],
                job_name=my_opts['destroy_job']))

        envelope = Envelope(
            from_addr=my_opts['email']['from'],
            to_addr=(email, name),
            subject=my_opts['email']['subject'],
            text_body=message,
        )
        smtp.send(envelope)
Beispiel #2
0
def main(*args):
    parser = SaltKeyOptionParser()
    parser.parse_args()
    opts = parser.config
    key = Key(opts)
    my_opts = opts['destroy_vm_reminder']
    key_list = key.name_match(my_opts['key_glob'])

    vms = {}
    rxp = re.compile(my_opts['key_regexp'])
    for status, keys in key_list.items():
        for key in keys:
            m = rxp.match(key)
            if m:
                user = m.group("user")
                if user not in vms:
                    vms[user] = []
                vms[user].append(key)

    smtp = SMTP(**my_opts['email']['smtp'])
    template = Template(my_opts['email']['message_template'])

    for user, keys in vms.items():

        res = requests.get(("{prefix}/securityRealm/user/{user}/api/json").format(
            prefix=my_opts['jenkins']['prefix'], user=user),
                           auth=(my_opts['jenkins']['username'],
                                 my_opts['jenkins']['api_token']))
        data = json.loads(res.content)
        name = data['fullName']
        email = ''
        for property in data['property']:
            if 'address' in property:
                email = property['address']
                break

        message = template.render(
            name=name, vms=keys,
            url="{prefix}/job/{job_name}/build?delay=0sec".format(
                prefix=my_opts['jenkins']['prefix'],
                job_name=my_opts['destroy_job']))

        envelope = Envelope(
            from_addr=my_opts['email']['from'],
            to_addr=(email, name),
            subject=my_opts['email']['subject'],
            text_body = message,
        )
        smtp.send(envelope)
Beispiel #3
0
class KeyManager:
    def __init__(self):
        self.opts = salt.config.master_config('/etc/salt/master')
        self.mykeymgr = Key(self.opts)

    def get_minion_keys(self, status=None):
        '''Return a list of minion keys matching status type'''
        #  Key.list_status(status)  where status type = accepted, pre, rejected, all
        #  or, use Key.list_keys(self)  --> dict of minions_rejected, minions_pre, minions
        if status not in ['pre', 'accepted', 'rejected']:
            result = None
        else:
            try:
                r_dict = self.mykeymgr.list_status(status)
                k = r_dict.keys()
                result = r_dict.get(k[0], None)
            except Exception, e:
                raise
        return result
Beispiel #4
0
class KeyManager:
    def __init__(self):
        self.opts = salt.config.master_config("/etc/salt/master")
        self.mykeymgr = Key(self.opts)

    def get_minion_keys(self, status=None):
        """Return a list of minion keys matching status type"""
        #  Key.list_status(status)  where status type = accepted, pre, rejected, all
        #  or, use Key.list_keys(self)  --> dict of minions_rejected, minions_pre, minions
        if status not in ["pre", "accepted", "rejected"]:
            result = None
        else:
            try:
                r_dict = self.mykeymgr.list_status(status)
                k = r_dict.keys()
                result = r_dict.get(k[0], None)
            except Exception, e:
                raise
        return result
Beispiel #5
0
 def execute(self, cmd, args):
     hostname = yield db.get(self.context, 'hostname')
     remote_salt_key_cmd = get_config().getstring('salt',
                                                  'remote_key_command',
                                                  None)
     if remote_salt_key_cmd:
         try:
             output = subprocess.check_output([
                 remote_salt_key_cmd, self._remote_option, hostname,
                 '--no-color', '--out=raw'
             ])
             log.msg('Salt output: %s' % output, system='action-accept')
         except subprocess.CalledProcessError as e:
             cmd.write("%s\n" % format_error(e))
     else:
         try:
             import salt.config
             from salt.key import Key
             c_path = get_config().getstring('salt', 'master_config_path',
                                             '/etc/salt/master')
             opts = salt.config.client_config(c_path)
             yield getattr(Key(opts), self._action)(hostname)
         except Exception as e:
             cmd.write("%s\n" % format_error(e))
Beispiel #6
0
def accept_key(minion_id):
    mymanager = Key(opts)
    mymanager.accept(match=minion_id)
    return
Beispiel #7
0
#!/usr/bin/env python
import sys
import salt
import yaml
import salt.client
from salt.key import Key

opts = salt.config.master_config('/etc/salt/master')
mymanager = Key(opts)
#aws_minion_file = "/etc/salt/ha/aws-autoscaling-info/aws_minion_info.yaml"
aws_minion_file = "/etc/salt/ha/aws-autoscaling-info/aws_minions.yaml"
'''  Reference of yaml on aws_minion_file - a list of dictionaries
 -  { 'minion_id': 'ip-10-0-10-137.ec2.internal', 'instance_id': 'i-4e087261'}
 -  { 'minion_id': 'ip-10-0-10-137.ec2.internal', 'instance_id': 'i-4e087261'}
'''


def load_minion_info(file_path=aws_minion_file):
    mydict = [
    ]  # useful if sns/sqs have not provided any info = no minion file yet
    mystr = "no data"
    try:
        #mydict = yaml.load(open(file_path, "r").read())
        minions = yaml.load(open(file_path, "r").read())
        #minions = mydict.get('minions', [])
    except Exception, e:
        print "Unable to open file, or convert to dict, giving an empty dict"
        print "Exception: %s" % e
        print "mystr = %s" % mystr
        print "mydict %s" % mydict
        raise
Beispiel #8
0
 def __init__(self):
     self.options = DummyOptions()
     keys_config = master_config(self.get_config_file_path('master'))
     Key.__init__(self, keys_config)
Beispiel #9
0
 def _salt_key(self):
     return Key(
         salt.config.master_config(config.get('cthulhu',
                                              'salt_config_path')))
Beispiel #10
0
 def __init__(self):
     self.options = DummyOptions()
     keys_config = master_config(self.get_config_file_path('master'))
     Key.__init__(self, keys_config)
Beispiel #11
0
def accept_key(minion_id):
  mymanager = Key(opts)
  mymanager.accept(match=minion_id)
  return
#!/usr/bin/env python

import os
import warnings
warnings.filterwarnings("ignore")

import salt.client
from salt.key import Key

master_opts = salt.config.master_config(
    os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))

salt_key = Key(master_opts)
local = salt.client.LocalClient()

minions = salt_key.list_keys()["minions"]

ping_result = local.cmd('*', 'test.ping', timeout=30)

for minion in minions:
    if not ping_result.get(minion):
        salt_key.delete_key(minion)

Beispiel #13
0
 def __init__(self):
     self.opts = salt.config.master_config('/etc/salt/master')
     self.mykeymgr = Key(self.opts)
                print 'FAIL:', minion, cmd
    elif cmd not in ["saltutil.sync_modules"]:
        if len(result) == 0:
            raise Exception("Command %s failed on %s: %s" % (cmd, target, result))

    print 'target=' + target, cmd, result

    return result

old_hostname = sys.argv[1]
new_hostname = sys.argv[2].lower()

master_opts = salt.config.master_config(
    os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))

salt_key = Key(master_opts)
local = salt.client.LocalClient()

salt_cmd('saltutil.sync_modules', name=old_hostname, timeout=30)

salt_cmd('miscutils.set_hostname', [ new_hostname ],
    name=old_hostname, timeout=30)

for i in xrange(60):
    minions = salt_key.list_keys().get("minions_pre")
    if len(minions) > 0 and new_hostname in minions:
        salt_key.accept(new_hostname)
        salt_key.delete_key(old_hostname)
        break
    sleep(2)
Beispiel #15
0
def delete_key(minion_id):
    mymanager = Key(opts)
    mymanager.delete_key(minion_id)
    return
Beispiel #16
0
 def __init__(self):
     self.opts = salt.config.master_config("/etc/salt/master")
     self.mykeymgr = Key(self.opts)
Beispiel #17
0
def delete_key(minion_id):
  mymanager = Key(opts)
  mymanager.delete_key(minion_id)
  return