Exemplo n.º 1
0
        def set_credentials():
            if info["done"]:
                return
            info["done"] = True

            environment = configuration["bespin"].environment
            if not environment:
                raise BadOption("Please specify an environment",
                                available=list(
                                    configuration["environments"].keys()))
            if environment not in configuration["environments"]:
                raise BadOption("Please specify a defined environment",
                                available=list(
                                    configuration["environments"].keys()))
            region = configuration["environments"][environment].region

            no_assume_role = configuration["bespin"].no_assume_role
            if self.options and "no_assume_role" in self.options:
                no_assume_role = self.options["no_assume_role"]
            assume_role = NotSpecified if no_assume_role else configuration[
                "bespin"].assume_role

            credentials = Credentials(
                region, configuration["environments"][environment].account_id,
                assume_role)
            bespin.credentials = credentials
Exemplo n.º 2
0
    def find_missing_env(self, key="env"):
        """Find any missing environment variables"""
        missing = [e.env_name for e in getattr(self, key) if e.missing]
        if missing:
            raise BadOption("Some environment variables aren't in the current environment", missing=missing)

        if key == "env" and self.newrelic is not NotSpecified:
            missing = [e.env_name for e in self.newrelic.env if e.missing]
            if missing:
                raise BadOption("Some newrelic environment variables aren't in the current environment", missing=missing)
Exemplo n.º 3
0
    def find_stack(self, stack, configuration):
        """Complain if we don't have an stack"""
        stacks = configuration["stacks"]
        available = list(stacks.keys())

        if not stack:
            info = {}
            if available:
                info["available"] = available
            raise BadOption("Please use --stack to specify a stack to use",
                            **info)

        if stack not in stacks:
            raise BadOption("No such stack", wanted=stack, available=available)

        return stacks
Exemplo n.º 4
0
    def confirm(self, stack, environment, start=None):
        instances = []
        if self.auto_scaling_group_name is not NotSpecified:
            instances = self.instances(stack)

            if len(instances) is 0:
                if self.zero_instances_is_ok:
                    log.info(
                        "No instances to check, but config says that's ok!")
                    return
                else:
                    raise BadDeployment(
                        "No instances are InService in the auto scaling group!",
                        stack=stack.name,
                        auto_scaling_group_name=self.auto_scaling_group_name)
        else:
            if any(item is not NotSpecified
                   for item in (self.sns_confirmation, self.url_checker)):
                raise BadOption(
                    "Auto_scaling_group_name must be specified if sns_confirmation or url_checker are specified"
                )

        for checker in (self.check_sns, self.check_url,
                        self.check_deployed_s3_paths):
            checker(stack, instances, environment, start)
Exemplo n.º 5
0
def become(collector, stack, artifact, **kwargs):
    """Print export statements for assuming an amazon iam role"""
    configuration = collector.configuration
    bespin = configuration['bespin']
    environment = bespin.environment
    region = configuration['environments'][environment].region

    if not environment:
        raise BadOption("Please specify an environment")

    if all(thing in ("", None, NotSpecified) for thing in (stack, artifact)):
        raise BespinError("Please specify your desired role as an artifact")

    if artifact:
        role = artifact
    else:
        role = stack

    credentials = Credentials(region, configuration["environments"][environment].account_id, role)
    credentials.verify_creds()

    print("export AWS_ACCESS_KEY_ID={0}".format(os.environ['AWS_ACCESS_KEY_ID']))
    print("export AWS_SECRET_ACCESS_KEY={0}".format(os.environ['AWS_SECRET_ACCESS_KEY']))
    print("export AWS_SECURITY_TOKEN={0}".format(os.environ['AWS_SECURITY_TOKEN']))
    print("export AWS_SESSION_TOKEN={0}".format(os.environ['AWS_SESSION_TOKEN']))
Exemplo n.º 6
0
 def note_deployment(self):
     """Note a deployment"""
     missing = [e.env_name for e in self.env if e.missing]
     if missing:
         raise BadOption("Some environment variables aren't in the current environment", missing=missing)
     provided_env = dict(e.pair for e in self.env)
     version = self.deployed_version.format(**provided_env)
     self.client.notify_deployment(application_id=self.application_id, description="Deployed {0}".format(version), revision=version)
Exemplo n.º 7
0
 def decrypt(self):
     """Decrypt the crypto text"""
     log.info("Decrypting %s password", self.name)
     try:
         crypto_text = base64.b64decode(self.crypto_text)
     except binascii.Error as error:
         raise BadOption("Failed to base64 decode crypto_text", crypto_text=self.crypto_text, error=error)
     return self.bespin.credentials.kms.decrypt(crypto_text, self.encryption_context, self.grant_tokens)["Plaintext"].decode("utf-8")
Exemplo n.º 8
0
    def get_variable(self, artifact):
        try:
            val = self.configuration.root()
            env_objs = []
            for part in artifact.split(','):
                val = val[part]
                if callable(val):
                    val = val()
                if hasattr(val, "env"):
                    env_objs.append(val.env)
                if hasattr(val, "build_env"):
                    env_objs.append(val.build_env)

            if isinstance(val, stack_objs.StaticVariable):
                val = val.resolve()
            elif isinstance(val, stack_objs.DynamicVariable):
                self.set_credentials()
                val = val.resolve()
            if isinstance(val, MergedOptions):
                val = val.as_dict()

            if env_objs and isinstance(val, six.string_types):
                envs = dict(
                    chain.from_iterable([(env.env_name, env)
                                         for env in env_obj]
                                        for env_obj in env_objs))
                wanted = []

                class Formatter(string.Formatter):
                    def get_field(self, key, args, kwargs, format_spec=None):
                        if key not in envs:
                            raise BadOptionFormat(
                                "Couldn't find an environment specification",
                                wanted=key,
                                available=list(envs.keys()))
                        wanted.append(envs[key])

                        if envs[key].missing:
                            return '', key
                        else:
                            return envs[key].pair[1], key

                val = Formatter().format(val)
                missing = [env.env_name for env in wanted if env.missing]
                if any(missing):
                    raise BadOption(
                        "Some environment variables aren't in the current environment",
                        missing=missing)

            return val
        except KeyError:
            raise MissingVariable(wanted=artifact)
Exemplo n.º 9
0
    def find_stacks(kls, configuration, stacks, plan):
        if plan in (None, NotSpecified):
            raise BadOption("Please specify a plan",
                            available=list(configuration["plans"].keys()))

        if plan not in configuration["plans"]:
            raise MissingPlan(wanted=plan,
                              available=configuration["plans"].keys())

        missing = []

        for stack in configuration["plans"][plan]:
            if stack not in stacks:
                missing.append(stack)

        if missing:
            raise BadOption("Some stacks in the plan don't exist",
                            missing=missing,
                            available=list(stacks.keys()))

        for stack in configuration["plans"][plan]:
            yield stack
Exemplo n.º 10
0
def instances(collector, stack, artifact, **kwargs):
    """Find and ssh into instances"""
    if artifact is None:
        instance_ids = stack.ssh.find_instance_ids(stack)
        stack.ec2.display_instances(instance_ids, address=stack.ssh.address)
    else:
        # Have to convert instance ids into ip addresses
        if artifact.startswith("i-"):
            instance_ids = stack.ssh.find_instance_ids(stack)
            if artifact not in instance_ids:
                raise BadOption("Please specify either an IP Address or instance id that exists", instance_ids = instance_ids, got = artifact) 

            artifact = stack.ec2.ip_for_instance_id(artifact)

        # Artifact should be an ip address now !
        stack.ssh.ssh_into(artifact, collector.configuration["$@"])
Exemplo n.º 11
0
    def run(self, collector, stack, available_actions, tasks, **extras):
        """Run this task"""
        task_action = available_actions[self.action]
        self.set_description(available_actions)
        configuration = collector.configuration.wrapped()

        if self.options:
            if stack:
                configuration.update({"stacks": {stack: self.options}})
            else:
                configuration.update(self.options)

        configuration.update(configuration["args_dict"].as_dict(),
                             source="<cli>")

        if self.overrides:
            overrides = {}
            for key, val in self.overrides.items():
                overrides[key] = val
                if isinstance(val, MergedOptions):
                    overrides[key] = dict(val.items())
            configuration.update(overrides)

        if task_action.needs_stack:
            environment = configuration["bespin"].environment
            if not environment:
                raise BadOption("Please specify an environment",
                                available=list(
                                    configuration.get("environments",
                                                      {}).keys()))
            if configuration["environments"].get(environment) is None:
                raise BadOption(
                    "No configuration found for specified environment",
                    environment=environment,
                    available=list(configuration["environments"].keys()))

            self.find_stack(stack, configuration)
            stack = configuration["stacks"][stack]

        bespin = configuration["bespin"]
        info = {"done": False}

        def set_credentials():
            if info["done"]:
                return
            info["done"] = True

            environment = configuration["bespin"].environment
            if not environment:
                raise BadOption("Please specify an environment",
                                available=list(
                                    configuration["environments"].keys()))
            if environment not in configuration["environments"]:
                raise BadOption("Please specify a defined environment",
                                available=list(
                                    configuration["environments"].keys()))
            region = configuration["environments"][environment].region

            no_assume_role = configuration["bespin"].no_assume_role
            if self.options and "no_assume_role" in self.options:
                no_assume_role = self.options["no_assume_role"]
            assume_role = NotSpecified if no_assume_role else configuration[
                "bespin"].assume_role

            credentials = Credentials(
                region, configuration["environments"][environment].account_id,
                assume_role)
            bespin.credentials = credentials

        bespin.set_credentials = set_credentials
        if task_action.needs_credentials:
            bespin.set_credentials()

        artifact = configuration["bespin"].chosen_artifact or None
        if task_action.needs_artifact and not artifact:
            raise BadOption("Please specify an artifact")

        from bespin.collector import Collector
        new_collector = Collector()
        new_collector.configuration = configuration
        new_collector.configuration_file = collector.configuration_file
        return task_action(collector,
                           stack=stack,
                           artifact=artifact,
                           tasks=tasks,
                           **extras)