output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Add various variable mapping command line options to the parser
Can you generate the documentation for the following Python 3 function def mapping_args(parser): parser.add_argument('--add-prefix', dest='add_prefix', help='Specify a prefix to use when ' 'generating secret key names') parser.add_argument(...
As a Python code composer, you craft elegant and concise scripts.
Add command line options for the aws_environment operation
Can you generate a brief explanation for the following Python 3 code def aws_env_args(subparsers): env_parser = subparsers.add_parser('aws_environment') env_parser.add_argument('vault_path', help='Full path(s) to the AWS secret') export_arg(env_parser) base_args(env_parser)
As a Python code translator, you convert algorithms and pseudocode into Python.
Add command line options for the environment operation
Here you have a function in Python 3, explain what it does def environment_args(subparsers): env_parser = subparsers.add_parser('environment') env_parser.add_argument('vault_paths', help='Full path(s) to secret', nargs='+') env_parser.add_argument('--p...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add command line options for the template operation
Make a summary of the following Python 3 code def template_args(subparsers): template_parser = subparsers.add_parser('template') template_parser.add_argument('template', help='Template source', nargs='?') template_parser.add_argument('destina...
As a python code expert, you are capable of creating scripts from specifications.
Add Secretfile management command line arguments to parser
Here you have a function in Python 3, explain what it does def secretfile_args(parser): parser.add_argument('--secrets', dest='secrets', help='Path where secrets are stored', default=os.path.join(os.getcwd(), ".secrets")) parser.add_argumen...
You are a Python code architect, reviewing and designing scalable and efficient code
Add the generic command line options
Given the following Python 3 function, write the documentation def base_args(parser): generic_args(parser) parser.add_argument('--monochrome', dest='monochrome', help='Whether or not to use colors', action='store_true') parser.add_argum...
You are a Python code generator, capable of creating scripts from specifications.
def export_args(subparsers): """Add command line options for the export operation""" export_parser = subparsers.add_parser('export') export_parser.add_argument('directory', help='Path where secrets will be exported into') secretfile_args(export_parser) vars_args(export...
Write a Python 3 script for adding command line options for the export operation
You are a Python code generator, capable of creating scripts from specifications.
def render_args(subparsers): """Add command line options for the render operation""" render_parser = subparsers.add_parser('render') render_parser.add_argument('directory', help='Path where Secrefile and accoutrement' ' will be rendered into') ...
Can you implement a function in Python 3 that adds command line options for the render operation
You are a Python code generator, capable of creating scripts from specifications.
def diff_args(subparsers): """Add command line options for the diff operation""" diff_parser = subparsers.add_parser('diff') secretfile_args(diff_parser) vars_args(diff_parser) base_args(diff_parser) thaw_from_args(diff_parser)
Write a Python 3 script to add command line options for the diff operation
You are a Python code analyst, evaluating scripts for potential improvements.
def seed_args(subparsers): """Add command line options for the seed operation""" seed_parser = subparsers.add_parser('seed') secretfile_args(seed_parser) vars_args(seed_parser) seed_parser.add_argument('--mount-only', dest='mount_only', help=...
Create a Python 3 function to add command line options for the seed operation
You are a Python code analyst, evaluating scripts for potential improvements.
Adds command line options for things related to inline thawing of ICE files
How would you explain what the following Python 3 function does def thaw_from_args(parser): parser.add_argument('--thaw-from', dest='thaw_from', help='Thaw an ICE file containing secrets') parser.add_argument('--gpg-password-path', dest='gp...
You are a Python code generator, capable of creating scripts from specifications.
def thaw_args(subparsers): """Add command line options for the thaw operation""" thaw_parser = subparsers.add_parser('thaw') thaw_parser.add_argument('--gpg-password-path', dest='gpg_pass_path', help='Vault path of GPG passphrase location') thaw_...
Write a Python 3 script for adding command line options for the thaw operation
You are a Python code analyst, evaluating scripts for potential improvements.
Add command line options for the freeze operation
Given the following Python 3 function, write the documentation def freeze_args(subparsers): freeze_parser = subparsers.add_parser('freeze') freeze_parser.add_argument('--icefile-prefix', dest='icefile_prefix', help='Prefix of icefilename') secret...
As a Python code analyst, you investigate and solve complex coding mysteries
Add command line options for the set_password operation
How would you explain what the following Python 3 function does def password_args(subparsers): password_parser = subparsers.add_parser('set_password') password_parser.add_argument('vault_path', help='Path which contains password' 'secret to be ud...
As a Python code composer, you craft elegant and concise scripts.
def vars_args(parser): """Add various command line options for external vars""" parser.add_argument('--extra-vars', dest='extra_vars', help='Extra template variables', default=[], type=str, ac...
Implement a Python 3 function for adding various command line options for external vars
As a python code expert, you are capable of creating scripts from specifications.
Return a proper contextual OptionParser
Given the following Python 3 function, write the documentation def parser_factory(fake_args=None): parser = ArgumentParser(description='aomi') subparsers = parser.add_subparsers(dest='operation', help='Specify the data ' ' or extracti...
As a Python code analyst, you investigate and solve complex coding mysteries
def template_runner(client, parser, args): """Executes template related operations""" if args.builtin_list: aomi.template.builtin_list() elif args.builtin_info: aomi.template.builtin_info(args.builtin_info) elif args.template and args.destination and args.vault_paths: aomi.render...
How would you code a function in Python 3 to execute template related operations
As a Python code translator, you convert algorithms and pseudocode into Python.
Handle some human triggers actions
Can you tell what is the following Python 3 function doing def ux_actions(parser, args): # cryptorito uses native logging (as aomi should tbh) normal_fmt = '%(message)s' if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2: logging.basicConfig(level=logging.DEBUG) elif hasattr(args...
As a Python code translator, you convert algorithms and pseudocode into Python.
def do_thaw(client, args): """Execute the thaw operation, pulling in an actual Vault client if neccesary""" vault_client = None if args.gpg_pass_path: vault_client = client.connect(args) aomi.filez.thaw(vault_client, args.icefile, args) sys.exit(0)
Can you implement a function in Python 3 that executes the thaw operation pulling in an actual Vault client if neccesary
You are a Python code analyst, evaluating scripts for potential improvements.
Run appropriate action or throw help
Can you generate a brief explanation for the following Python 3 code def action_runner(parser, args): ux_actions(parser, args) client = aomi.vault.Client(args) if args.operation == 'extract_file': aomi.render.raw_file(client.connect(args), args.vault_path, args.destina...
You are a Python code architect, reviewing and designing scalable and efficient code
def grok_ttl(secret): """Parses the TTL information""" ttl_obj = {} lease_msg = '' if 'lease' in secret: ttl_obj['lease'] = secret['lease'] lease_msg = "lease:%s" % (ttl_obj['lease']) if 'lease_max' in secret: ttl_obj['lease_max'] = secret['lease_max'] elif 'lease' in tt...
Write a Python 3 function for parsing the TTL information from a secret dictionary
You are a Python code generator, capable of creating scripts from specifications.
Return the version of the current package
How would you explain what the following Python 3 function does def my_version(): if os.path.exists(resource_filename(__name__, 'version')): return resource_string(__name__, 'version') return open(os.path.join(os.path.dirname(__file__), "..", "version")).read()
As a python code expert, you are capable of creating scripts from specifications.
def abspath(raw): """Return what is hopefully a OS independent path.""" path_bits = [] if raw.find('/') != -1: path_bits = raw.split('/') elif raw.find('\\') != -1: path_bits = raw.split('\\') else: path_bits = [raw] return os.path.abspath(os.sep.join(path_bits))
Create a Python 3 function to return what is hopefully a OS independent path.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an absolute path to either the relative or absolute file.
Can you generate the documentation for the following Python 3 function def hard_path(path, prefix_dir): relative = abspath("%s/%s" % (prefix_dir, path)) a_path = abspath(path) if os.path.exists(relative): LOG.debug("using relative path %s (%s)", relative, path) return relative LOG.debug...
As a Python code composer, you craft elegant and concise scripts.
Checks if the list of tags is tagged with the list of tags.
Here you have a function in Python 3, explain what it does def is_tagged(required_tags, has_tags): if not required_tags and not has_tags: return True elif not required_tags: return False found_tags = [] for tag in required_tags: if tag in has_tags: found_tags.append(...
You are a Python code generator, capable of creating scripts from specifications.
def cli_hash(list_of_kv): """Parse out a hash from a list of key=value strings""" ev_obj = {} for extra_var in list_of_kv: ev_list = extra_var.split('=') key = ev_list[0] val = '='.join(ev_list[1:]) # b64 and other side effects ev_obj[key] = val return ev_obj
Create a Python 3 function to parse out a hash from a list of key = value strings
As a Python code composer, you craft elegant and concise scripts.
When returning a password from a TTY we assume a user is entering it on a keyboard so we ask for confirmation.
Here you have a function in Python 3, explain what it does def get_tty_password(confirm): LOG.debug("Reading password from TTY") new_password = getpass('Enter Password: ', stream=sys.stderr) if not new_password: raise aomi.exceptions.AomiCommand("Must specify a password") if not confirm: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Will return a two part tuple comprising of the vault path and the key with in the stored object
How would you explain what the following Python 3 function does def path_pieces(vault_path): path_bits = vault_path.split('/') path = '/'.join(path_bits[0:len(path_bits) - 1]) key = path_bits[len(path_bits) - 1] return path, key
You are a Python code generator, capable of creating scripts from specifications.
def mount_for_path(path, client): """Returns the mountpoint for this path""" backend_data = client.list_secret_backends()['data'] backends = [mnt for mnt in backend_data.keys()] path_bits = path.split('/') if len(path_bits) == 1: vault_path = "%s/" % path if vault_path in backends: ...
How would you code a function in Python 3 to return the mountpoint for this path
As a Python code composer, you craft elegant and concise scripts.
Returns the type of backend at the given mountpoint
Can you generate a brief explanation for the following Python 3 code def backend_type(path, client): backends = client.list_secret_backends()['data'] vault_path = "%s/" % path return backends[vault_path]['type']
You are a Python code generator, capable of creating scripts from specifications.
Loads a words file as a list of lines
Here you have a function in Python 3, explain what it does def load_word_file(filename): words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a random entry from a list of things
Make a summary of the following Python 3 code def choose_one(things): choice = SystemRandom().randint(0, len(things) - 1) return things[choice].strip()
You are a Python code analyst, evaluating scripts for potential improvements.
def subdir_path(directory, relative): """Returns a file path relative to another path.""" item_bits = directory.split(os.sep) relative_bits = relative.split(os.sep) for i, _item in enumerate(item_bits): if i == len(relative_bits) - 1: return os.sep.join(item_bits[i:]) else: ...
Can you create a Python 3 function that returns a file path relative to another path.
As a Python code analyst, you investigate and solve complex coding mysteries
Opens something that might be binary but also might be plain text.
Given the following Python 3 function, write the documentation def open_maybe_binary(filename): if sys.version_info >= (3, 0): data = open(filename, 'rb').read() try: return data.decode('utf-8') except UnicodeDecodeError: return data return open(filename, 'r').re...
As a Python code composer, you craft elegant and concise scripts.
def ensure_dir(path): """Ensures a directory exists""" if not (os.path.exists(path) and os.path.isdir(path)): os.mkdir(path)
How would you code a function in Python 3 to ensure a directory exists
You are a Python code generator, capable of creating scripts from specifications.
Called atexit this removes our tmpdir
Can you tell what is the following Python 3 function doing def clean_tmpdir(path): if os.path.exists(path) and \ os.path.isdir(path): rmtree(path)
As a Python code analyst, you investigate and solve complex coding mysteries
Ensure that every string in a dict is properly represented by unicode strings
Explain what the following Python 3 code does def dict_unicodeize(some_dict): # some python 2/3 compat if isinstance(some_dict, ("".__class__, u"".__class__)): if sys.version_info >= (3, 0): return some_dict return some_dict.decode('utf-8') elif isinstance(some_dict, collection...
As a Python code translator, you convert algorithms and pseudocode into Python.
Performs a base type comparison between two dicts
Can you generate the documentation for the following Python 3 function def diff_dict(dict1, dict2, ignore_missing=False): unidict1 = dict_unicodeize(dict1) unidict2 = dict_unicodeize(dict2) if ((not ignore_missing) and (len(unidict1) != len(unidict2))) or \ (ignore_missing and (len(unidict1) >= len(u...
You are a Python code generator, capable of creating scripts from specifications.
def filtered_context(context): """Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.""" ctx = Context(context.opt) for resource in context.resources(): if resource.child:...
Create a Python 3 function to filter a context by only the resources that are actually available for use.
As a Python code translator, you convert algorithms and pseudocode into Python.
Ensure the backend for a resource is properly in context
Can you generate a brief explanation for the following Python 3 code def ensure_backend(resource, backend, backends, opt, managed=True): existing_mount = find_backend(resource.mount, backends) if not existing_mount: new_mount = backend(resource, opt, managed=managed) backends.append(new_mount) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Given a list of mods attempts to find a model that fits one of the models
Make a summary of the following Python 3 code def find_model(config, obj, mods): for mod in mods: if mod[0] != config: continue if len(mod) == 2: return mod[1] if len(mod) == 3 and mod[1] in obj: return mod[2] return None
As a Python code translator, you convert algorithms and pseudocode into Python.
Discovers all aomi Vault resource models. This includes all aomi Vault resource models extending aomi. model. Mount or aomi. model. Resource.
Can you generate a brief explanation for the following Python 3 code def py_resources(): aomi_mods = [m for m, _v in iteritems(sys.modules) if m.startswith('aomi.model')] mod_list = [] mod_map = [] for amod in [sys.modules[m] for m in aomi_mods]: for _mod_bit, m...
As a python code expert, you are capable of creating scripts from specifications.
Loads and returns a full context object based on the Secretfile
Make a summary of the following Python 3 code def load(config, opt): ctx = Context(opt) seed_map = py_resources() seed_keys = sorted(set([m[0] for m in seed_map]), key=resource_sort) for config_key in seed_keys: if config_key not in config: continue ...
You are a Python code generator, capable of creating scripts from specifications.
Will thaw every secret into an appropriate temporary location
Given the following Python 3 function, write the documentation def thaw(self, tmp_dir): for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
You are a Python code architect, reviewing and designing scalable and efficient code
def freeze(self, dest_dir): """Freezes every resource within a context""" for resource in self.resources(): if resource.present: resource.freeze(dest_dir)
Can you write a function in Python 3 where it freezes every resource within a context
You are a Python code analyst, evaluating scripts for potential improvements.
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
Can you write a function in Python 3 where it returns a list of vault resources within context
As a Python code analyst, you investigate and solve complex coding mysteries
def add(self, resource): """Add a resource to the context""" if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBackend, ...
Implement a function in Python 3 to add a resource to the context
You are a Python code architect, reviewing and designing scalable and efficient code
Removes a resource from the context
Can you generate the documentation for the following Python 3 function def remove(self, resource): if isinstance(resource, Resource): self._resources.remove(resource)
As a Python code composer, you craft elegant and concise scripts.
def sync_auth(self, vault_client, resources): """Synchronizes auth mount wrappers. These happen early in the cycle, to ensure that user backends are proper. They may also be used to set mount tuning""" for auth in self.auths(): auth.sync(vault_client) auth_re...
Write a Python 3 function for synchronizing auth mount wrappers.
You are a Python code analyst, evaluating scripts for potential improvements.
Handle the actual mounting of a secret backend.
Given the following Python 3 function, write the documentation def actually_mount(self, vault_client, resource, active_mounts): a_mounts = list(active_mounts) if isinstance(resource, Secret) and resource.mount == 'cubbyhole': return a_mounts active_mount = find_backend(resource.moun...
As a python code expert, you are capable of creating scripts from specifications.
Synchronizes the active mount points. Removes things before adding new.
Given the following Python 3 function, write the documentation def sync_mounts(self, active_mounts, resources, vault_client): # Create a resource set that is only explicit mounts # and sort so removals are first mounts = [x for x in resources if isinstance(x, (Mount, AWS))] ...
You are a Python code architect, reviewing and designing scalable and efficient code
Synchronizes the context to the Vault server.
Can you generate the documentation for the following Python 3 function def sync(self, vault_client, opt): active_mounts = [] for audit_log in self.logs(): audit_log.sync(vault_client) # Handle policies only on the first pass. This allows us # to ensure that ACL's are in plac...
You are a Python code analyst, evaluating scripts for potential improvements.
def fetch(self, vault_client): """Updates the context based on the contents of the Vault server. Note that some resources can not be read after they have been written to and it is up to those classes to handle that case properly.""" backends = [(self.mounts, SecretBackend), ...
Implement a function in Python 3 to update the context based on the contents of the Vault server.
You are a Python code generator, capable of creating scripts from specifications.
Renders a Secret key name appropriately
Explain what the following Python 3 code does def secret_key_name(path, key, opt): value = key if opt.merge_path: norm_path = [x for x in path.split('/') if x] value = "%s_%s" % ('_'.join(norm_path), key) if opt.add_prefix: value = "%s%s" % (opt.add_prefix, value) if opt.add_su...
As a python code expert, you are capable of creating scripts from specifications.
def grok_template_file(src): """Determine the real deal template file""" if not src.startswith('builtin:'): return abspath(src) builtin = src.split(':')[1] builtin = "templates/%s.j2" % builtin return resource_filename(__name__, builtin)
Can you write a function in Python 3 where it determines the real deal template file
You are a Python code architect, reviewing and designing scalable and efficient code
Blends secret and static variables together
Given the following Python 3 function, write the documentation def blend_vars(secrets, opt): base_obj = load_vars(opt) merged = merge_dicts(base_obj, secrets) template_obj = dict((k, v) for k, v in iteritems(merged) if v) # give templates something to iterate over template_obj['aomi_items'] = templa...
As a Python code composer, you craft elegant and concise scripts.
Writes a template using variables from a vault path
Explain what the following Python 3 code does def template(client, src, dest, paths, opt): key_map = cli_hash(opt.key_map) obj = {} for path in paths: response = client.read(path) if not response: raise aomi.exceptions.VaultData("Unable to retrieve %s" % path) if is_aws(r...
As a Python code composer, you craft elegant and concise scripts.
Writes an actual secret out to a file
Here you have a function in Python 3, explain what it does def write_raw_file(secret, dest): secret_file = None secret_filename = abspath(dest) if sys.version_info >= (3, 0): if not isinstance(secret, str): secret_file = open(secret_filename, 'wb') if not secret_file: secret...
You are a Python code generator, capable of creating scripts from specifications.
def raw_file(client, src, dest, opt): """Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded.""" path, key = path_pieces(src) resp = client.read(path) if not resp: client.revoke_self_token() raise aomi.excep...
Create a Python 3 function to write the contents of a vault path to a file.
As a Python code composer, you craft elegant and concise scripts.
def env(client, paths, opt): """Renders a shell snippet based on paths in a Secretfile""" old_prefix = False old_prefix = opt.prefix and not (opt.add_prefix or opt.add_suffix or not opt.merge_path) if old_prefix: LOG.warni...
Can you implement a function in Python 3 that renders a shell snippet based on paths in a Secretfile
You are a Python code analyst, evaluating scripts for potential improvements.
Renders a shell environment snippet with AWS information
Can you generate the documentation for the following Python 3 function def aws(client, path, opt): try: creds = client.read(path) except (hvac.exceptions.InternalServerError) as vault_exception: # this is how old vault behaves if vault_exception.errors[0].find('unsupported path') > 0: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Create the proper generated key value
How would you explain what the following Python 3 function does def generated_key(key): key_name = key['name'] if key['method'] == 'uuid': LOG.debug("Setting %s to a uuid", key_name) return str(uuid4()) elif key['method'] == 'words': LOG.debug("Setting %s to random words", key_name) ...
As a python code expert, you are capable of creating scripts from specifications.
Generates the secret object accordinging existing information and user specified options
Can you tell what is the following Python 3 function doing def generate_obj(self): secret_obj = {} if self.existing: secret_obj = deepcopy(self.existing) for key in self.keys: key_name = key['name'] if self.existing and \ key_name in self.exist...
As a python code expert, you are capable of creating scripts from specifications.
Handle uncaught errors and be polite about it
Here you have a function in Python 3, explain what it does def unhandled(exception, opt): exmod = type(exception).__module__ name = "%s.%s" % (exmod, type(exception).__name__) # this is a Vault error if exmod == 'aomi.exceptions' or exmod == 'cryptorito': # This may be set for Validation or simi...
As a Python code composer, you craft elegant and concise scripts.
def grok_seconds(lease): """Ensures that we are returning just seconds""" if lease.endswith('s'): return int(lease[0:-1]) elif lease.endswith('m'): return int(lease[0:-1]) * 60 elif lease.endswith('h'): return int(lease[0:-1]) * 3600 return None
Implement a function in Python 3 to ensure that we are returning just seconds
You are a Python code generator, capable of creating scripts from specifications.
Renews a secret. This will occur unless the user has specified on the command line that it is not neccesary
Here you have a function in Python 3, explain what it does def renew_secret(client, creds, opt): if opt.reuse_token: return seconds = grok_seconds(opt.lease) if not seconds: raise aomi.exceptions.AomiCommand("invalid lease %s" % opt.lease) renew = None if client.version: v_...
As a Python code composer, you craft elegant and concise scripts.
def approle_token(vault_client, role_id, secret_id): """Returns a vault token based on the role and seret id""" resp = vault_client.auth_approle(role_id, secret_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiC...
Create a Python 3 function to return a vault token based on the role and secret id
As a Python code composer, you craft elegant and concise scripts.
def app_token(vault_client, app_id, user_id): """Returns a vault token based on the app and user id.""" resp = vault_client.auth_app_id(app_id, user_id) if 'auth' in resp and 'client_token' in resp['auth']: return resp['auth']['client_token'] else: raise aomi.exceptions.AomiCredentials('...
Write a Python 3 function that can return a vault token based on the app and user id.
You are a Python code analyst, evaluating scripts for potential improvements.
def token_meta(opt): """Generates metadata for a token""" meta = { 'via': 'aomi', 'operation': opt.operation, 'hostname': socket.gethostname() } if 'USER' in os.environ: meta['unix_user'] = os.environ['USER'] if opt.metadata: meta_bits = opt.metadata.split(',...
Write a Python 3 function for generating metadata for a token
As a Python code analyst, you investigate and solve complex coding mysteries
def get_backend(backend, path, backends): """Returns mountpoint details for a backend""" m_norm = normalize_vault_path(path) for mount_name, values in backends.items(): b_norm = normalize_vault_path(mount_name) if (m_norm == b_norm) and values['type'] == backend: return values ...
Can you implement a function in Python 3 that returns mountpoint details for a backend
You are a Python code generator, capable of creating scripts from specifications.
A decorator that wraps API interactions with Vault API.
Here you have a function in Python 3, explain what it does def wrap_hvac(msg): # pylint: disable=missing-docstring def wrap_call(func): # pylint: disable=missing-docstring def func_wrapper(self, vault_client): try: return func(self, vault_client) except (h...
As a python code expert, you are capable of creating scripts from specifications.
def server_version(self): """Attempts to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.""" health_url = "%s/v1/sys/health" % self.vault_addr resp = self.session.request('get', health_url, **self._kwargs) if re...
Implement a Python 3 function for attempting to determine the version of Vault that a server is running. Some actions will change on older Vault deployments.
You are a Python code architect, reviewing and designing scalable and efficient code
This sets up the tokens we expect to see in a way that hvac also expects.
Given the following Python 3 function, write the documentation def connect(self, opt): if not self._kwargs['verify']: LOG.warning('Skipping SSL Validation!') self.version = self.server_version() self.token = self.init_token() my_token = self.lookup_token() if not my_...
As a Python code analyst, you investigate and solve complex coding mysteries
def init_token(self): """Generate our first token based on workstation configuration""" app_filename = appid_file() token_filename = token_file() approle_filename = approle_file() token = None if 'VAULT_ROLE_ID' in os.environ and \ 'VAULT_SECRET_ID' in os.envi...
Write a Python 3 function for generating our first token based on workstation configuration
As a python code expert, you are capable of creating scripts from specifications.
Return a properly annotated token for our use.
Can you generate a brief explanation for the following Python 3 code def op_token(self, display_name, opt): args = { 'lease': opt.lease, 'display_name': display_name, 'meta': token_meta(opt) } try: token = self.create_token(**args) except (...
As a Python code analyst, you investigate and solve complex coding mysteries
def read(self, path, wrap_ttl=None): """Wrap the hvac read call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).read(path, wrap_ttl) ...
Write a Python 3 script for wrapping the hvac read call using the right token for cubbyhole interactions.
You are a Python code analyst, evaluating scripts for potential improvements.
def write(self, path, wrap_ttl=None, **kwargs): """Wrap the hvac write call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, se...
Can you implement a function in Python 3 that wraps the hvac write call using the right token for cubbyhole interactions.
You are a Python code generator, capable of creating scripts from specifications.
def delete(self, path): """Wrap the hvac delete call, using the right token for cubbyhole interactions.""" path = sanitize_mount(path) val = None if path.startswith('cubbyhole'): self.token = self.initial_token val = super(Client, self).delete(path) ...
Can you write a function in Python 3 where it wraps the hvac delete call using the right token for cubbyhole interactions.
As a Python code translator, you convert algorithms and pseudocode into Python.
Will attempt to retrieve a GPG public key from Keybase if neccesary
Here you have a function in Python 3, explain what it does def from_keybase(username): public_key = key_from_keybase(username) fingerprint = public_key['fingerprint'][-8:].upper().encode('ascii') key = public_key['bundle'].encode('ascii') if not has_gpg_key(fingerprint): LOG.debug("Importing gpg...
As a Python code translator, you convert algorithms and pseudocode into Python.
Will retrieve a GPG key from either Keybase or GPG directly
Given the following Python 3 function, write the documentation def grok_keys(config): key_ids = [] for key in config['pgp_keys']: if key.startswith('keybase:'): key_id = from_keybase(key[8:]) LOG.debug("Encrypting for keybase user %s", key[8:]) else: if not ha...
As a Python code analyst, you investigate and solve complex coding mysteries
def freeze_archive(tmp_dir, dest_prefix): """Generates a ZIP file of secrets""" zip_filename = "%s/aomi-blah.zip" % tmp_dir archive = zipfile.ZipFile(zip_filename, 'w') for root, _dirnames, filenames in os.walk(dest_prefix): for filename in filenames: relative_path = subdir_path(root...
Can you implement a function in Python 3 that generates a ZIP file of secrets
As a python code expert, you are capable of creating scripts from specifications.
def freeze_encrypt(dest_dir, zip_filename, config, opt): """Encrypts the zip file""" pgp_keys = grok_keys(config) icefile_prefix = "aomi-%s" % \ os.path.basename(os.path.dirname(opt.secretfile)) if opt.icefile_prefix: icefile_prefix = opt.icefile_prefix timestamp = time...
Implement a Python 3 function for encrypting the zip file
You are a Python code generator, capable of creating scripts from specifications.
Freeze the secrets in the Secretfile and encrypt it.
Can you tell what is the following Python 3 function doing def freeze(dest_dir, opt): tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Context.load(config, opt) \ .freeze(dest_prefix) zip_filename...
You are a Python code architect, reviewing and designing scalable and efficient code
Decrypts the encrypted ice file
Explain what the following Python 3 code does def thaw_decrypt(vault_client, src_file, tmp_dir, opt): if not os.path.isdir(opt.secrets): LOG.info("Creating secret directory %s", opt.secrets) os.mkdir(opt.secrets) zip_file = "%s/aomi.zip" % tmp_dir if opt.gpg_pass_path: gpg_path_bi...
As a python code expert, you are capable of creating scripts from specifications.
def thaw(vault_client, src_file, opt): """Given the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations""" if not os.path.exists(src_file): raise aomi.exceptions.AomiFile("%s does not exist" % src_file) tmp_dir = ensure_tmpdir() zip_fil...
Can you write a function in Python 3 where it gives the combination of a Secretfile and the output of a freeze operation, will restore secrets to usable locations
You are a Python code generator, capable of creating scripts from specifications.
def diff(self): """Determines if changes are needed for the Vault backend""" if not self.present: if self.existing: return DEL return NOOP is_diff = NOOP if self.present and self.existing: a_obj = self.config.copy() if se...
Create a Python 3 function for determining if changes are needed for the Vault backend
You are a Python code architect, reviewing and designing scalable and efficient code
Synchronizes the local and remote Vault resources. Has the net effect of adding backend if needed.
Given the following Python 3 function, write the documentation def sync(self, vault_client): if self.present: if not self.existing: LOG.info("Mounting %s backend on %s", self.backend, self.path) self.actually_mount(vault_client) el...
You are a Python code generator, capable of creating scripts from specifications.
def sync_tunables(self, vault_client): """Synchtonizes any tunables we have set""" if not self.config: return a_prefix = self.tune_prefix if self.tune_prefix: a_prefix = "%s/" % self.tune_prefix v_path = "sys/mounts/%s%s/tune" % (a_prefix, self.path) ...
Write a Python 3 function that can synchronize any tunables we have set
As a python code expert, you are capable of creating scripts from specifications.
Updates the local resource with context on whether this backend is actually mounted and available
Here you have a function in Python 3, explain what it does def fetch(self, vault_client, backends): if not is_mounted(self.backend, self.path, backends) or \ self.tune_prefix is None: return backend_details = get_backend(self.backend, self.path, backends) self.existing = ...
As a python code expert, you are capable of creating scripts from specifications.
Unmounts a backend within Vault
How would you explain what the following Python 3 function does def unmount(self, client): getattr(client, self.unmount_fun)(mount_point=self.path)
As a python code expert, you are capable of creating scripts from specifications.
Will perform some validation and copy decrypted secret to it s final location
Here you have a function in Python 3, explain what it does def thaw(self, tmp_dir): for sfile in self.secrets(): src_file = "%s/%s" % (tmp_dir, sfile) err_msg = "%s secret missing from icefile" % (self) if not os.path.exists(src_file): if hasattr(self.opt, 'ig...
As a python code expert, you are capable of creating scripts from specifications.
A tunable resource maps against a backend...
Here you have a function in Python 3, explain what it does def tunable(self, obj): self.tune = dict() if 'tune' in obj: for tunable in MOUNT_TUNABLES: tunable_key = tunable[0] map_val(self.tune, obj['tune'], tunable_key) if tunable_key in self....
As a Python code analyst, you investigate and solve complex coding mysteries
def export_handle(self, directory): """Get a filehandle for exporting""" filename = getattr(self, 'filename') dest_file = "%s/%s" % (directory, filename) dest_dir = os.path.dirname(dest_file) if not os.path.isdir(dest_dir): os.mkdir(dest_dir, 0o700) return op...
Can you create a Python 3 function that gets a filehandle for exporting
As a Python code translator, you convert algorithms and pseudocode into Python.
Export the current object to a directory.
Make a summary of the following Python 3 code def export(self, directory): if not self.existing or not hasattr(self, 'filename'): return secret_h = self.export_handle(directory) obj = self.existing if isinstance(obj, str): secret_h.write(obj) elif isinsta...
You are a Python code generator, capable of creating scripts from specifications.
Copies a secret into a particular location
Explain what the following Python 3 code does def freeze(self, tmp_dir): for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % ...
As a Python code composer, you craft elegant and concise scripts.
Determine the desired state of thisCOOKIE based on data present
Make a summary of the following Python 3 code def grok_state(self, obj): if 'state' in obj: my_state = obj['state'].lower() if my_state != 'absent' and my_state != 'present': raise aomi_excep \ .Validation('state must be either "absent" or "present"') ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Base validation method. Will inspect class attributes to dermine just what should be present
Can you generate a brief explanation for the following Python 3 code def validate(self, obj): if 'tags' in obj and not isinstance(obj['tags'], list): raise aomi_excep.Validation('tags must be a list') if self.present: check_obj(self.required_fields, self.name(), obj)
As a Python code analyst, you investigate and solve complex coding mysteries
Determine if something has changed or not
Given the following Python 3 function, write the documentation def diff(self, obj=None): if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff...
As a Python code composer, you craft elegant and concise scripts.
Populate internal representation of remote Vault resource contents
Given the following Python 3 function, write the documentation def fetch(self, vault_client): result = self.read(vault_client) if result: if isinstance(result, dict) and 'data' in result: self.existing = result['data'] else: self.existing = result ...
You are a Python code generator, capable of creating scripts from specifications.
def sync(self, vault_client): """Update remove Vault resource contents if needed""" if self.present and not self.existing: LOG.info("Writing new %s to %s", self.secret_format, self) self.write(vault_client) elif self.present and self.existing: ...
Write a Python 3 script for updating update and remove Vault resource contents if needed
You are a Python code generator, capable of creating scripts from specifications.