Exemplo n.º 1
0
def resolve_policy_document(policy_name):
  policy_filename = "{}{}.json".format(CONTEXT.policy_template_path, policy_name)
  print_if_verbose("Load policy: {} from file: {}".format(policy_name, policy_filename))
  # retrieve policy template
  try:
    policy_file = file(policy_filename, 'r')
    policy_template = policy_file.read()
    policy_file.close()
  except:
    fail("error opening policy file: {}".format(policy_filename))
  print_if_verbose("pre-resolution policy template:\n{}".format(policy_template))
  # If running in EC2, do not set profile and set target_other=True
  if CONTEXT.whereami == "ec2":
    resolver = EFTemplateResolver(target_other=True, env=CONTEXT.env, region=EFConfig.DEFAULT_REGION,
                                  service=CONTEXT.service, verbose=CONTEXT.verbose)
  else:
    resolver = EFTemplateResolver(profile=CONTEXT.account_alias, env=CONTEXT.env, region=EFConfig.DEFAULT_REGION,
                                service=CONTEXT.service, verbose=CONTEXT.verbose)
  resolver.load(policy_template)
  policy_document = resolver.render()
  print_if_verbose("resolved policy document:\n{}".format(policy_document))
  if not resolver.resolved_ok():
    fail("policy template {} has unresolved symbols or extra {{ or }}: {}".format(
      policy_filename, resolver.unresolved_symbols()))
  return policy_document
Exemplo n.º 2
0
def merge_files(context):
    """
  Given a context containing path to template, env, and service:
  merge config into template and output the result to stdout
  Args:
    context: a populated context object
  """
    resolver = EFTemplateResolver(profile=context.profile,
                                  region=context.region,
                                  env=context.env,
                                  service=context.service)

    try:
        with open(context.template_path, 'r') as f:
            template_body = f.read()
            f.close()
    except IOError as error:
        raise IOError("Error loading template file: {} {}".format(
            context.template_path, repr(error)))

    try:
        with open(context.param_path, 'r') as f:
            param_body = f.read()
            f.close()
    except IOError as error:
        raise IOError("Error loading param file: {} {}".format(
            context.param_path, repr(error)))

    dest = json.loads(param_body)["dest"]

    # if 'dest' for the current object contains an 'environments' list, check it
    if dest.has_key("environments"):
        if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
            print("Environment: {} not enabled for {}".format(
                resolver.resolved["ENV_SHORT"], context.template_path))
            return

    # Process the template_body - apply context + parameters
    resolver.load(template_body, param_body)
    rendered_body = resolver.render()

    if not resolver.resolved_ok():
        raise RuntimeError(
            "Couldn't resolve all symbols; template has leftover {{ or }}: {}".
            format(resolver.unresolved_symbols()))

    if context.verbose:
        print(context)
        dir_path = normpath(dirname(dest["path"]))
        print("make directories: {} {}".format(dir_path, dest["dir_perm"]))
        print("chmod file to: " + dest["file_perm"])
        user, group = dest["user_group"].split(":")
        print("chown last directory in path to user: {}, group: {}".format(
            user, group))
        print("chown file to user: {}, group: {}\n".format(user, group))

        print("template body:\n{}\nrendered body:\n{}\n".format(
            template_body, rendered_body))
    else:
        print(rendered_body)
Exemplo n.º 3
0
def merge_files(service, skip_on_user_group_error=False):
    """
  Given a prefix, find all templates below; merge with parameters; write to "dest"
  Args:
    service: "<service>", "all", or "ssh"
    skip_on_user_group_error: True or False

  For S3, full path becomes:
    s3://ellation-cx-global-configs/<service>/templates/<filename>
    s3://ellation-cx-global-configs/<service>/parameters/<filename>.parameters.<yaml|yml|json>
  For filesystem, full path becomes:
    /vagrant/configs/<service>/templates/<filename>
    /vagrant/configs/<service>/parameters/<filename>.parameters.<yaml|yml|json>
  """
    if WHERE == "ec2":
        config_reader = EFInstanceinitConfigReader("s3", service, log_info,
                                                   RESOURCES["s3"])
        resolver = EFTemplateResolver()
    elif WHERE == "virtualbox-kvm":
        config_path = "{}/{}".format(VIRTUALBOX_CONFIG_ROOT, service)
        config_reader = EFInstanceinitConfigReader("file", config_path,
                                                   log_info)
        environment = EFConfig.VAGRANT_ENV
        resolver = EFTemplateResolver(env=environment,
                                      profile=get_account_alias(environment),
                                      region=EFConfig.DEFAULT_REGION,
                                      service=service)

    while config_reader.next():
        log_info("checking: {}".format(config_reader.current_key))

        # if 'dest' for the current object contains an 'environments' list, check it
        dest = config_reader.dest
        if "environments" in dest:
            if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
                log_info("Environment: {} not enabled for {}".format(
                    resolver.resolved["ENV_SHORT"], config_reader.current_key))
                continue

        # If 'dest' for the current object contains a user_group that hasn't been created in the environment yet and the
        # flag is set to True to skip, log the error and move onto the next config file without blowing up.
        if skip_on_user_group_error:
            user, group = get_user_group(dest)
            try:
                getpwnam(user).pw_uid
            except KeyError:
                log_info(
                    "File specifies user {} that doesn't exist in environment. Skipping config file."
                    .format(user))
                continue
            try:
                getgrnam(group).gr_gid
            except KeyError:
                log_info(
                    "File specifies group {} that doesn't exist in environment. Skipping config file."
                    .format(group))
                continue

        # Process the template_body - apply context + parameters
        log_info("Resolving template")
        resolver.load(config_reader.template, config_reader.parameters)
        rendered_body = resolver.render()
        if not resolver.resolved_ok():
            critical(
                "Couldn't resolve all symbols; template has leftover {{ or }}: {}"
                .format(resolver.unresolved_symbols()))

        # Write the rendered file
        dir_path = normpath(dirname(dest["path"]))
        # Resolved OK. try to write the template
        log_info("make directories: {} {}".format(dir_path, dest["dir_perm"]))
        try:
            makedirs(dir_path, int(dest["dir_perm"], 8))
        except OSError as error:
            if error.errno != 17:
                critical("Error making directories {}".format(repr(error)))
        log_info("open: " + dest["path"] + ",w+")
        try:
            outfile = open(dest["path"], 'w+')
            log_info("write")
            outfile.write(rendered_body)
            log_info("close")
            outfile.close()
            log_info("chmod file to: " + dest["file_perm"])
            chmod(dest["path"], int(dest["file_perm"], 8))
            user, group = get_user_group(dest)
            uid = getpwnam(user).pw_uid
            gid = getgrnam(group).gr_gid
            log_info("chown last directory in path to: " + dest["user_group"])
            chown(dir_path, uid, gid)
            log_info("chown file to: " + dest["user_group"])
            chown(dest["path"], uid, gid)
        except Exception as error:
            critical("Error writing file: " + dest["path"] + ": " +
                     repr(error))
Exemplo n.º 4
0
def merge_files(context):
    """
  Given a context containing path to template, env, and service:
  merge config into template and output the result to stdout
  Args:
    context: a populated context object
  """
    resolver = EFTemplateResolver(profile=context.profile,
                                  region=context.region,
                                  env=context.env,
                                  service=context.service)

    try:
        with open(context.template_path, 'r') as f:
            template_body = f.read()
            f.close()
    except IOError as error:
        raise IOError("Error loading template file: {} {}".format(
            context.template_path, repr(error)))

    if context.no_params is False:
        try:
            with open(context.param_path, 'r') as f:
                param_body = f.read()
                f.close()
        except IOError as error:
            raise IOError("Error loading param file: {} {}".format(
                context.param_path, repr(error)))

        dest = yaml.safe_load(param_body)["dest"]

        # if 'dest' for the current object contains an 'environments' list, check it
        if "environments" in dest:
            if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
                print("Environment: {} not enabled for {}".format(
                    resolver.resolved["ENV_SHORT"], context.template_path))
                return

        # Process the template_body - apply context + parameters
        resolver.load(template_body, param_body)
    else:
        resolver.load(template_body)
    rendered_body = resolver.render()

    if not resolver.resolved_ok():
        raise RuntimeError(
            "Couldn't resolve all symbols; template has leftover {{ or }}: {}".
            format(resolver.unresolved_symbols()))

    if context.lint:
        if context.template_path.endswith(".json"):
            try:
                json.loads(rendered_body, strict=False)
                print("JSON passed linting process.")
            except ValueError as e:
                fail("JSON failed linting process.", e)
        elif context.template_path.endswith((".yml", ".yaml")):
            conf = yamllint_config.YamlLintConfig(content='extends: relaxed')
            lint_output = yamllinter.run(rendered_body, conf)
            lint_level = 'error'
            lint_errors = [
                issue for issue in lint_output if issue.level == lint_level
            ]
            if lint_errors:
                split_body = rendered_body.splitlines()
                for error in lint_errors:
                    print(error)
                    # printing line - 1 because lists start at 0, but files at 1
                    print("\t", split_body[error.line - 1])
                fail("YAML failed linting process.")

    if context.verbose:
        print(context)
        if context.no_params:
            print('no_params flag set to true!')
            print(
                'Inline template resolution based on external symbol lookup only and no destination for file write.\n'
            )
        else:
            dir_path = normpath(dirname(dest["path"]))
            print("make directories: {} {}".format(dir_path, dest["dir_perm"]))
            print("chmod file to: " + dest["file_perm"])
            user, group = dest["user_group"].split(":")
            print("chown last directory in path to user: {}, group: {}".format(
                user, group))
            print("chown file to user: {}, group: {}\n".format(user, group))

        print("template body:\n{}\nrendered body:\n{}\n".format(
            template_body, rendered_body))
    elif context.silent:
        print("Config template rendered successfully.")
    else:
        print(rendered_body)
Exemplo n.º 5
0
def merge_files(service):
    """
  Given a prefix, find all templates below; merge with parameters; write to "dest"
  Args:
    service: "<service>" or "all"

  For S3, full path becomes:
    s3://ellation-cx-global-configs/<service>/templates/<filename>
    s3://ellation-cx-global-configs/<service>/parameters/<filename>.parameters.json
  For filesystem, full path becomes:
    /vagrant/configs/<service>/templates/<filename>
    /vagrant/configs/<service>/parameters/<filename>.parameters.json
  """
    if WHERE == "ec2":
        config_reader = EFInstanceinitConfigReader("s3", service, log_info,
                                                   RESOURCES["s3"])
    elif WHERE == "virtualbox-kvm":
        config_path = "{}/{}".format(VIRTUALBOX_CONFIG_ROOT, service)
        config_reader = EFInstanceinitConfigReader("file", config_path,
                                                   log_info)

    while config_reader.next():
        # Make a new TemplateResolver for every file::parameters pair, so cached keys don't carry over
        if WHERE == "ec2":
            resolver = EFTemplateResolver()
        elif WHERE == "virtualbox-kvm":
            resolver = EFTemplateResolver(env="localvm", service=service)

        log_info("checking: {}".format(config_reader.current_key))

        # if 'dest' for the current object contains an 'environments' list, check it
        dest = config_reader.dest
        if dest.has_key("environments"):
            if not resolver.resolved["ENV_SHORT"] in dest["environments"]:
                log_info("Environment: {} not enabled for {}".format(
                    resolver.resolved["ENV_SHORT"], config_reader.current_key))
                continue

        # Process the template_body - apply context + parameters
        log_info("Resolving template")
        resolver.load(config_reader.template, config_reader.parameters)
        rendered_body = resolver.render()
        if not resolver.resolved_ok():
            critical(
                "Couldn't resolve all symbols; template has leftover {{ or }}: {}"
                .format(resolver.unresolved_symbols()))

        # Write the rendered file
        dir_path = normpath(dirname(dest["path"]))
        # Resolved OK. try to write the template
        log_info("make directories: {} {}".format(dir_path, dest["dir_perm"]))
        try:
            makedirs(dir_path, int(dest["dir_perm"], 8))
        except OSError as error:
            if error.errno != 17:
                critical("Error making directories {}".format(repr(error)))
        log_info("open: " + dest["path"] + ",w+")
        try:
            outfile = open(dest["path"], 'w+')
            log_info("write")
            outfile.write(rendered_body)
            log_info("close")
            outfile.close()
            log_info("chmod file to: " + dest["file_perm"])
            chmod(dest["path"], int(dest["file_perm"], 8))
            user, group = dest["user_group"].split(":")
            uid = getpwnam(user).pw_uid
            gid = getgrnam(group).gr_gid
            log_info("chown last directory in path to: " + dest["user_group"])
            chown(dir_path, uid, gid)
            log_info("chown file to: " + dest["user_group"])
            chown(dest["path"], uid, gid)
        except Exception as error:
            critical("Error writing file: " + dest["path"] + ": " +
                     repr(error))