Create roles/dockerfile-to-ansible path and role structure.
        :return: None
337501
def create_role_from_template(self):
        '''
        
        '''
        description = u"Imported Dockerfile for {}".format(self.project_name)

        create_role_from_templates(role_name=os.path.basename(self.import_from),
                                   role_path=self.role_path,
                                   project_name=self.project_name,
                                   description=description)
583660
def _connect_docker(spec):
    
    return {
        'method': 'docker',
        'kwargs': {
            'username': spec.remote_user(),
            'container': spec.remote_addr(),
            'python_path': spec.python_path(),
            'connect_timeout': spec.ansible_ssh_timeout() or spec.timeout(),
            'remote_name': get_remote_name(spec),
        }
    }
682863
def _make_tmp_path(self, conn):
        '''  '''

        basefile = 'ansible-%s-%s' % (time.time(), random.randint(0, 2**48))
        basetmp = os.path.join(C.DEFAULT_REMOTE_TMP, basefile)
        if self.sudo and self.sudo_user != 'root':
            basetmp = os.path.join('/tmp', basefile)

        cmd = 'mkdir -p %s' % basetmp
        if self.remote_user != 'root':
            cmd += ' && chmod a+rx %s' % basetmp
        cmd += ' && echo %s' % basetmp

        result = self._low_level_exec_command(conn, cmd, None, sudoable=False)
        rc = utils.last_non_blank_line(result['stdout']).strip() + '/'
        return rc
28240
def execute(self):
        

        role_name = self._command_args['role_name']
        role_directory = os.getcwd()
        msg = 'Initializing new role {}...'.format(role_name)
        LOG.info(msg)

        if os.path.isdir(role_name):
            msg = ('The directory {} exists. '
                   'Cannot create new role.').format(role_name)
            util.sysexit_with_message(msg)

        template_directory = ''
        if 'template' in self._command_args.keys():
            template_directory = self._command_args['template']
        else:
            template_directory = 'role'
        self._process_templates(template_directory, self._command_args,
                                role_directory)
        scenario_base_directory = os.path.join(role_directory, role_name)
        templates = [
            'scenario/driver/{driver_name}'.format(**self._command_args),
            'scenario/verifier/{verifier_name}'.format(**self._command_args),
        ]
        for template in templates:
            self._process_templates(template, self._command_args,
                                    scenario_base_directory)
        self._process_templates('molecule', self._command_args, role_directory)

        role_directory = os.path.join(role_directory, role_name)
        msg = 'Initialized role in {} successfully.'.format(role_directory)
        LOG.success(msg)
1166949
def _remote_chmod(self, paths, mode, sudoable=False):
        
        LOG.debug('_remote_chmod(%r, mode=%r, sudoable=%r)',
                  paths, mode, sudoable)
        return self.fake_shell(lambda: mitogen.select.Select.all(
            self._connection.get_chain().call_async(
                ansible_mitogen.target.set_file_mode, path, mode
            )
            for path in paths
        ))
832165
def create_dependencies task
      project_name = "minke#{SecureRandom.urlsafe_base64(12)}".downcase.gsub(/[^0-9a-z ]/i, '')
      network_name = ENV['DOCKER_NETWORK'] ||= "#{project_name}_default"
      ENV['DOCKER_PROJECT'] = project_name
      ENV['DOCKER_NETWORK'] = network_name

      logger = Minke::Logging.create_logger(STDOUT, self.verbose)
      shell = Minke::Helpers::Shell.new(logger)

      task_runner = Minke::Tasks::TaskRunner.new ({
        :ruby_helper       => Minke::Helpers::Ruby.new,
        :copy_helper       => Minke::Helpers::Copy.new,
        :service_discovery => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name),
        :logger_helper     => logger
      })

      consul = Minke::Docker::Consul.new(
        {
          :health_check => Minke::Docker::HealthCheck.new(logger),
          :service_discovery => Minke::Docker::ServiceDiscovery.new( project_name, Minke::Docker::DockerRunner.new(logger, network_name), network_name),
          :consul_loader => ConsulLoader::Loader.new(ConsulLoader::ConfigParser.new),
          :docker_runner => Minke::Docker::DockerRunner.new(logger, network_name),
          :network => network_name,
          :project_name => project_name,
          :logger_helper => logger
        }
      )

      network = Minke::Docker::Network.new(
        network_name,
        shell
      )

      return {
        :config                 => @config,
        :task_name              => task,
        :docker_runner          => Minke::Docker::DockerRunner.new(logger, network_name, project_name),
        :task_runner            => task_runner,
        :shell_helper           => shell,
        :logger_helper          => logger,
        :generator_config       => generator_config,
        :docker_compose_factory => Minke::Docker::DockerComposeFactory.new(shell, project_name, network_name),
        :consul                 => consul,
        :docker_network         => network,
        :health_check           => Minke::Docker::HealthCheck.new(logger),
        :service_discovery      => Minke::Docker::ServiceDiscovery.new(project_name, Minke::Docker::DockerRunner.new(logger), network_name)
      } 
    end
684926
def run(self):
        
        path = self.path or CONTAINER_BUILD_JSON_PATH
        try:
            with open(path, 'r') as build_cfg_fd:
                build_cfg_json = json.load(build_cfg_fd)
        except ValueError:
            self.log.error("couldn't decode json from file '%s'", path)
            return None
        except IOError:
            self.log.error("couldn't read json from file '%s'", path)
            return None
        else:
            return self.substitute_configuration(build_cfg_json)
562887
def write_path(path, s, owner=None, group=None, mode=None,
               utimes=None, sync=False):
    
    path = os.path.abspath(path)
    fd, tmp_path = tempfile.mkstemp(suffix='.tmp',
                                    prefix='.ansible_mitogen_transfer-',
                                    dir=os.path.dirname(path))
    fp = os.fdopen(fd, 'wb', mitogen.core.CHUNK_SIZE)
    LOG.debug('write_path(path=%r) temporary file: %s', path, tmp_path)

    try:
        try:
            if mode:
                set_file_mode(tmp_path, mode, fd=fp.fileno())
            if owner or group:
                set_file_owner(tmp_path, owner, group, fd=fp.fileno())
            fp.write(s)
        finally:
            fp.close()

        if sync:
            os.fsync(fp.fileno())
        os.rename(tmp_path, path)
    except BaseException:
        os.unlink(tmp_path)
        raise

    if utimes:
        os.utime(path, utimes)
1319854
def build_tmp_dir
      base_directory = tmp_path/"etc"/"chef"
      roles_dir = "#{base_directory}/roles"
      FileUtils.rm_rf base_directory # cleanup old chef temp directory
      puts "Copying the chef-repo into the base directory from #{repo}"
      
      FileUtils.mkdir_p base_directory
      FileUtils.mkdir_p roles_dir # Why do we need this??!?
      if File.directory?(repo)
        if File.exist?(base_directory)
          # First remove the directory
          FileUtils.remove_entry base_directory, :force => true
        end
        cookbook_path = "#{base_directory}/cookbooks"
        FileUtils.mkdir_p cookbook_path
        FileUtils.cp_r "#{repo}/.", cookbook_path
      else
        raise "#{repo} chef repo directory does not exist"
      end
      puts "Creating the dna.json"
      attributes.to_dna [], base_directory/"dna.json", {:run_list => ["role[#{cloud.name}]"]}
      write_solo_dot_rb
      # Make sure the roles directory exists
      FileUtils.mkdir_p roles_dir
      write_chef_role_json "#{roles_dir}/#{cloud.name}.json"
    end
235088
def __get_docker_file_path(path):
    '''
    
    '''
    if os.path.isfile(path):
        return path
    for dc_filename in DEFAULT_DC_FILENAMES:
        file_path = os.path.join(path, dc_filename)
        if os.path.isfile(file_path):
            return file_path
585806
def _check_yaml_and_paths(ymlfilepath, yamldefs):
        
        relpath = os.path.relpath(ymlfilepath)
        if '/' not in relpath:
            relpath = './%s' % relpath
        pathroot = os.path.abspath(os.path.dirname(ymlfilepath))

        for imagename, defn in iteritems(yamldefs):
            if imagename == '_SOURCES_':
                yamldefs['_SOURCES_'] = [os.path.relpath(_get_abspath(pathroot, p))
                                         for p in yamldefs['_SOURCES_']]
                continue
            elif imagename in SPECIAL_FIELDS:
                continue

            for key in ('build_directory', 'FROM_DOCKERFILE', 'ignorefile'):
                if key in defn:
                    defn[key] = _get_abspath(pathroot, defn[key])

            if 'copy_from' in defn:
                if not isinstance(defn['copy_from'], dict):
                    raise errors.ParsingFailure((
                            'Syntax error in file "%s": \n' +
                            'The "copy_from" field in image definition "%s" is not \n' 
                            'a key:value list.') % (ymlfilepath, imagename))
                for otherimg, value in defn.get('copy_from', {}).items():
                    if not isinstance(value, dict):
                        raise errors.ParsingFailure((
                            'Syntax error in field:\n'
                            '     %s . copy_from . %s\nin file "%s". \n'
                            'All entries must be of the form "sourcepath: destpath"')%
                                 (imagename, otherimg, ymlfilepath))

            # save the file path for logging
            defn['_sourcefile'] = relpath

            if 'ignore' in defn and 'ignorefile' in defn:
                raise errors.MultipleIgnoreError(
                        'Image "%s" has both "ignore" AND "ignorefile" fields.' % imagename +
                        ' At most ONE of these should be defined')

            if 'secret_files' in defn and not defn.get('squash', True):
                raise errors.ParsingFailure(
                        "Step '%s' defines secret_files, so 'squash' cannot be set to 'false'"
                        % imagename)

            if defn.get('secret_files', None) and defn.get('copy_from', False):
                raise errors.ParsingFailure(
                        '`secret_files` currently is not implmemented to handle `copy_from`'
                        ' (step %s)' % imagename)

            for key in defn:
                if key not in RECOGNIZED_KEYS:
                    raise errors.UnrecognizedKeyError(
                            'Field "%s" in image "%s" in file "%s" not recognized' %
                            (key, imagename, relpath))
774965
def build(self):
        
        docker_build = docker.from_env().api.build
        build_actions = []
        for a in docker_build(
            str(settings.project_customization.path), tag=settings.tag
        ):
            build_actions.append(a)
702623
function createRole (commandOptions, { roleName, permissionsList }) {
  return command(
    commandOptions,
    txHelper.addCommand(
      txHelper.emptyTransaction(),
      'createRole',
      {
        roleName,
        permissionsList
      }
    )
  )
}
14780
def load(self):
        
        if self.exists():
            with open(self.dot_file, 'r') as handle:
                self.update(json.load(handle))
        if self.options['context'] is not None:
            self['context'] = self.options['context']
        else:
            self.options['context'] = self['context']
        if self.options['defaults'] is not None:
            self['defaults'] = self.options['defaults']
        else:
            self.options['defaults'] = self['defaults']
        if self.options['output'] is not None:
            self['output'] = self.options['output']

        if self.options.get('inclusive', False):
            self['inclusive'] = True

        if self.options.get('exclude', []):
            self['exclude'].extend(self.options['exclude'])

        if self['output'] is None:
            self['output'] = os.path.join(os.getcwd(), 'dockerstache-output')
        self['output_path'] = self.abs_output_dir()
        self['input_path'] = self.abs_input_dir()
        if self['context'] is not None:
            self['context_path'] = absolute_path(self['context'])
        if self['defaults'] is not None:
            self['defaults_path'] = absolute_path(self['defaults'])
976393
def dump_artifacts(kwargs):
    '''
    
    '''
    private_data_dir = kwargs.get('private_data_dir')
    if not private_data_dir:
        private_data_dir = tempfile.mkdtemp()
        kwargs['private_data_dir'] = private_data_dir

    if not os.path.exists(private_data_dir):
        raise ValueError('private_data_dir path is either invalid or does not exist')

    if 'role' in kwargs:
        role = {'name': kwargs.pop('role')}
        if 'role_vars' in kwargs:
            role['vars'] = kwargs.pop('role_vars')

        play = [{'hosts': kwargs.pop('hosts', 'all'), 'roles': [role]}]

        if kwargs.pop('role_skip_facts', False):
            play[0]['gather_facts'] = False

        kwargs['playbook'] = play

        if 'envvars' not in kwargs:
            kwargs['envvars'] = {}

        roles_path = kwargs.pop('roles_path', None)
        if not roles_path:
            roles_path = os.path.join(private_data_dir, 'roles')
        else:
            roles_path += ':{}'.format(os.path.join(private_data_dir, 'roles'))

        kwargs['envvars']['ANSIBLE_ROLES_PATH'] = roles_path

    obj = kwargs.get('playbook')
    if obj and isplaybook(obj):
        path = os.path.join(private_data_dir, 'project')
        kwargs['playbook'] = dump_artifact(json.dumps(obj), path, 'main.json')

    obj = kwargs.get('inventory')
    if obj and isinventory(obj):
        path = os.path.join(private_data_dir, 'inventory')
        if isinstance(obj, Mapping):
            kwargs['inventory'] = dump_artifact(json.dumps(obj), path, 'hosts.json')
        elif isinstance(obj, string_types):
            if not os.path.exists(obj):
                kwargs['inventory'] = dump_artifact(obj, path, 'hosts')

    for key in ('envvars', 'extravars', 'passwords', 'settings'):
        obj = kwargs.get(key)
        if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
            path = os.path.join(private_data_dir, 'env')
            dump_artifact(json.dumps(obj), path, key)
            kwargs.pop(key)

    for key in ('ssh_key', 'cmdline'):
        obj = kwargs.get(key)
        if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
            path = os.path.join(private_data_dir, 'env')
            dump_artifact(str(kwargs[key]), path, key)
            kwargs.pop(key)
440511
def build_docker_build_command(configuration):
    
    parts = configuration.pop('docker', 'docker').split()
    parts.append('build')

    build = configuration.pop('build')

    build['path'] = os.path.join(configuration['workspace'], build['path'])
    build['file'] = os.path.join(build['path'], build['file'])

    parts.extend(build_parameter_parts(
        build, 'tag', 'file', 'no-cache', 'quiet', 'cpu-shares', 'memory'))

    parts.extend(build_dict_parameter_parts(build, 'build-arg'))
    parts.append(build.pop('path'))

    return parts
798920
def create_role(self, role_name, role_type, host_id):
    
    return roles.create_role(self._get_resource_root(), self.name, role_type,
        role_name, host_id, self._get_cluster_name())