How to use the pyinfra.api.exceptions.PyinfraError function in pyinfra

To help you get started, we’ve selected a few pyinfra examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Fizzadar / pyinfra / pyinfra / __main__.py View on Github external
serial=arguments['serial'],
            no_wait=arguments['no_wait']
        )

        # Run the after_deploy hook if provided
        run_hook(state, 'after_deploy', hook_data)

        print('--> Results:')
        print_results(state, inventory)

# Hook errors
except hook.Error as e:
    _exception('hook error', e)

# Internal exceptions
except PyinfraError as e:
    _exception('pyinfra error', e)

# IO errors
except IOError as e:
    _exception('local IO error', e)

# Unexpected exceptions/everything else
except Exception as e:
    _exception('unknown error', e, always_dump=True)


_exit()
github Fizzadar / pyinfra / pyinfra / api / operation.py View on Github external
# If we're in CLI mode, there's no state/host passed down, we need to
        # use the global "pseudo" modules.
        if len(args) < 2 or not (
            isinstance(args[0], (State, PseudoModule))
            and isinstance(args[1], (Host, PseudoModule))
        ):
            state = pseudo_state._module
            host = pseudo_host._module

            if state.in_op:
                raise PyinfraError((
                    'Nested operation called without state/host: {0} ({1})'
                ).format(op_name, _get_call_location()))

            if state.in_deploy:
                raise PyinfraError((
                    'Nested deploy operation called without state/host: {0} ({1})'
                ).format(op_name, _get_call_location()))

        # Otherwise (API mode) we just trim off the commands
        else:
            args_copy = list(args)
            state, host = args[0], args[1]
            args = args_copy[2:]

        # In API mode we have the kwarg - if a nested operation call we have
        # current_frameinfo.
        frameinfo = kwargs.pop('frameinfo', get_caller_frameinfo())

        # Configure operation
        #
github Fizzadar / pyinfra / pyinfra / api / state.py View on Github external
activated_count = activated_count or len(self.activated_hosts)

        logger.debug('Failing hosts: {0}'.format(', '.join(
            (host.name for host in hosts_to_fail),
        )))

        # Remove the failed hosts from the inventory
        self.active_hosts -= hosts_to_fail

        # Check we're not above the fail percent
        active_hosts = self.active_hosts

        # No hosts left!
        if not active_hosts:
            raise PyinfraError('No hosts remaining!')

        if self.config.FAIL_PERCENT is not None:
            percent_failed = (
                1 - len(active_hosts) / activated_count
            ) * 100

            if percent_failed > self.config.FAIL_PERCENT:
                raise PyinfraError('Over {0}% of hosts failed ({1}%)'.format(
                    self.config.FAIL_PERCENT,
                    int(round(percent_failed)),
                ))
github Fizzadar / pyinfra / pyinfra / api / exceptions.py View on Github external
class OperationError(PyinfraError):
    '''
    Exception raised during fact gathering staging if an operation is unable to
    generate output/change state.
    '''


class DeployError(PyinfraError):
    '''
    User exception for raising in deploys or sub deploys.
    '''


class InventoryError(PyinfraError):
    '''
    Exception raised for inventory related errors.
    '''


class NoConnectorError(PyinfraError, TypeError):
    '''
    Raised when a requested connector is missing.
    '''


class NoHostError(PyinfraError, TypeError):
    '''
    Raised when an inventory is missing a host.
    '''
github Fizzadar / pyinfra / pyinfra / local.py View on Github external
if key in [
                'SUDO', 'SUDO_USER', 'SU_USER',
                'PRESERVE_SUDO_ENV', 'IGNORE_ERRORS',
            ]
        }
        with pseudo_state.deploy(
            filename, kwargs, None, frameinfo.lineno,
            in_deploy=False,
        ):
            exec_file(filename)

        # One potential solution to the above is to add local as an actual
        # module, ie `pyinfra.modules.local`.

    except IOError as e:
        raise PyinfraError(
            'Could not include local file: {0}\n{1}'.format(filename, e),
        )
github Fizzadar / pyinfra / pyinfra / api / exceptions.py View on Github external
class PyinfraError(Exception):
    '''
    Generic pyinfra exception.
    '''


class OperationError(PyinfraError):
    '''
    Exception raised during fact gathering staging if an operation is unable to
    generate output/change state.
    '''


class DeployError(PyinfraError):
    '''
    User exception for raising in deploys or sub deploys.
    '''


class InventoryError(PyinfraError):
    '''
    Exception raised for inventory related errors.
    '''
github Fizzadar / pyinfra / pyinfra / api / connectors / ssh.py View on Github external
else:
                    raise PyinfraError(
                        'Private key file ({0}) is encrypted, set ssh_key_password to '
                        'use this key'.format(key_filename),
                    )

            # Now, try opening the key with the password
            try:
                key = RSAKey.from_private_key_file(
                    filename=filename,
                    password=key_password,
                )
                break

            except SSHException:
                raise PyinfraError(
                    'Incorrect password for private key: {0}'.format(
                        key_filename,
                    ),
                )

    # No break, so no key found
    else:
        raise IOError('No such private key file: {0}'.format(key_filename))

    state.private_keys[key_filename] = key
    return key
github Fizzadar / pyinfra / pyinfra / hook.py View on Github external
from click import ClickException

from pyinfra.api.exceptions import PyinfraError

from . import pseudo_state

HOOKS = {
    'before_connect': [],
    'before_facts': [],
    'before_deploy': [],
    'after_deploy': [],
}


class Error(PyinfraError, ClickException):
    '''
    Exception raised when encounting errors in deploy hooks.
    '''


def _make_hook_wrapper(hook_name):
    def hook_func(func):
        # Only add hooks when the state is not initialised
        if pseudo_state.initialised:
            return

        HOOKS[hook_name].append(func)

        @wraps(func)
        def decorated(*args, **kwargs):
            return func(*args, **kwargs)
github Fizzadar / pyinfra / pyinfra / api / connectors / ssh.py View on Github external
# Key is encrypted!
        except PasswordRequiredException:
            # If password is not provided, but we're in CLI mode, ask for it. I'm not a
            # huge fan of having CLI specific code in here, but it doesn't really fit
            # anywhere else without duplicating lots of key related code into cli.py.
            if not key_password:
                if pyinfra.is_cli:
                    key_password = getpass(
                        'Enter password for private key: {0}: '.format(
                            key_filename,
                        ),
                    )

            # API mode and no password? We can't continue!
                else:
                    raise PyinfraError(
                        'Private key file ({0}) is encrypted, set ssh_key_password to '
                        'use this key'.format(key_filename),
                    )

            # Now, try opening the key with the password
            try:
                key = RSAKey.from_private_key_file(
                    filename=filename,
                    password=key_password,
                )
                break

            except SSHException:
                raise PyinfraError(
                    'Incorrect password for private key: {0}'.format(
                        key_filename,
github Fizzadar / pyinfra / pyinfra / api / operations.py View on Github external
def _run_serial_ops(state):
    '''
    Run all ops for all servers, one server at a time.
    '''

    for host in list(state.inventory):
        host_operations = product([host], state.get_op_order())
        with progress_spinner(host_operations) as progress:
            try:
                _run_server_ops(
                    state, host,
                    progress=progress,
                )
            except PyinfraError:
                state.fail_hosts({host})