当前位置: 首页>>代码示例>>Python>>正文


Python ConfigDict.save方法代码示例

本文整理汇总了Python中cloudmesh_client.common.ConfigDict.ConfigDict.save方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigDict.save方法的具体用法?Python ConfigDict.save怎么用?Python ConfigDict.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cloudmesh_client.common.ConfigDict.ConfigDict的用法示例。


在下文中一共展示了ConfigDict.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_apikey

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def get_apikey(endpoint):
        config = ConfigDict("cloudmesh.yaml")
        cometConf = config["cloudmesh.comet"]
        defaultUser = cometConf["username"]
        user = input("Comet Nucleus Usename [%s]: " \
                         % defaultUser)
        if not user:
            user = defaultUser
        password = getpass.getpass()
        keyurl = "%s/getkey" % cometConf["endpoints"][endpoint]["nucleus_base_url"]
        headers = {"ACCEPT": "application/json"}
        r = requests.get(keyurl, headers=headers, auth=HTTPBasicAuth(user, password))
        if r.status_code == 200:
            keyobj = r.json()
            api_key = keyobj["key_name"]
            api_secret = keyobj["key"]
            config = ConfigDict("cloudmesh.yaml")
            config.data["cloudmesh"]["comet"]["endpoints"]\
                        [endpoint]["auth_provider"] = 'apikey'
            config.data["cloudmesh"]["comet"]["endpoints"]\
                        [endpoint]["apikey"]["api_key"] = api_key
            config.data["cloudmesh"]["comet"]["endpoints"]\
                        [endpoint]["apikey"]["api_secret"] = api_secret

            config.save()
            Console.ok("api key retrieval and set was successful!")
        else:
            Console.error("Error getting api key. " \
                          "Please check your username/password", traceflag=False)
开发者ID:sohiljain,项目名称:client,代码行数:31,代码来源:comet.py

示例2: entry

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def entry(cls, name):

        banner("Register {}".format(name))

        name = str(name)
        etc_config = ConfigDict("cloudmesh.yaml", etc=True)
        config = ConfigDict("cloudmesh.yaml")

        clouds = config["cloudmesh.clouds"]
        clusters = config["cloudmesh.hpc.clusters"]

        if name in clouds:
            name = "cloudmesh.clouds.{}.credentials".format(name)
        elif name in clusters:
            name = "cloudmesh.hpc.clusters.{}.credentials".format(name)
        elif not name.startswith("cloudmesh."):
            name = "cloudmesh." + name

        try:
            etc = etc_config[name]
            yaml = config[name]

            # walk yaml
            for key in etc:
                if etc[key] == "TBD":
                    result = input("Enter {:} ({:}): ".format(key, yaml[key]))
                    if result != '':
                        yaml[key] = result

            config.save()
        except Exception as e:
            Console.error("Could not find {} in the yaml file".format(name), traceflag=False)
开发者ID:arpiagariu,项目名称:client,代码行数:34,代码来源:register.py

示例3: set_username

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
 def set_username(cls, username):
     """
     Method that sets the username in yaml.
     :param username:
     :return:
     """
     config = ConfigDict("cloudmesh.yaml")
     config['cloudmesh']['profile']['user'] = username
     config.save()
开发者ID:arpiagariu,项目名称:client,代码行数:11,代码来源:register.py

示例4: from_file

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def from_file(cls, filename):
        """
        Replaces the TBD in cloudmesh.yaml with the contents present in FILEPATH's FILE
        :param filename:
        :return:
        """
        if not os.path.isfile(os.path.expanduser(filename)):
            Console.error("{} doesn't exist".format(filename))
            return

        # BUG should use path separator
        path, filename = filename.rsplit("/", 1)
        # Config file to be read from

        from_config_file = ConfigDict(filename, [path])

        config = ConfigDict("cloudmesh.yaml")

        # Merging profile
        profile = config["cloudmesh"]["profile"]
        for profile_key in list(profile.keys()):
            if profile[profile_key] == "TBD":
                profile[profile_key] = \
                    from_config_file["cloudmesh"]["profile"][profile_key]
        config.save()

        # Merging clouds
        clouds = config["cloudmesh"]["clouds"]
        for cloud in list(clouds.keys()):
            cloud_element = clouds[cloud]
            for key in list(cloud_element.keys()):
                if cloud_element[key] == "TBD":
                    cloud_element[key] = \
                        from_config_file["cloudmesh"]["clouds"][cloud][key]
            config["cloudmesh"]["clouds"][cloud] = cloud_element

            credentials = clouds[cloud]["credentials"]
            for key in credentials:
                if credentials[key] == "TBD":
                    credentials[key] = \
                        from_config_file["cloudmesh"]["clouds"][cloud][
                            "credentials"][key]
            config["cloudmesh"]["clouds"][cloud]["credentials"] = credentials

            defaults = clouds[cloud]["default"]
            for key in defaults:
                if defaults[key] == "TBD":
                    defaults[key] = \
                        from_config_file["cloudmesh"]["clouds"][cloud][
                            "default"][
                            key]
            config["cloudmesh"]["clouds"][cloud]["default"] = defaults
        config.save()

        Console.ok(
            "Overwritten the TBD of cloudmesh.yaml with {} contents".format(
                filename))
开发者ID:arpiagariu,项目名称:client,代码行数:59,代码来源:register.py

示例5: ec2

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def ec2(cls, cloud, zipfile):

        def sanitize(name):
            return name.replace(".zip", "").replace("@", "_")

        def find_exports(filename):
            with open(filename, "r") as f:
                content = f.read()
            data = {}
            for line in content.split("\n"):
                if line.startswith("export "):
                    line = line.replace("export ", "")
                    attribute, value = line.split("=", 1)
                    value = value.replace("${NOVA_KEY_DIR}/", "")
                    # remove comments
                    data[attribute] = value.split("#")[0].strip()
            return data

        base = sanitize(os.path.basename(zipfile))
        dest = sanitize(os.path.join(
            path_expand("~"),
            ".cloudmesh",
            "clouds",
            cloud,
            os.path.basename(zipfile)))
        Console.msg("Unzip file {} -> {}".format(zipfile, dest))
        r = Shell.unzip(zipfile, dest)
        rcfile = os.path.join(dest, "ec2rc.sh")
        data = find_exports(rcfile)
        data["DEST"] = dest
        data["CLOUD"] = cloud
        d = {
            "cm_heading": "{CLOUD}, EC2".format(**data),
            "cm_host": None,
            "cm_label": "{CLOUD}_ec2".format(**data),
            "cm_type": "ec2",
            "cm_type_version": "ec2",
            "credentials": {
                "EC2_ACCESS_KEY": "{EC2_ACCESS_KEY}".format(**data),
                "EC2_SECRET_KEY": "{EC2_SECRET_KEY}".format(**data),
                "keyname": "TBD_not_used",
                "userid": "TBD_not_used",
                "EC2_URL": "{EC2_URL}".format(**data),
                "EC2_USER_ID": "{EC2_USER_ID}",
                "EC2_PRIVATE_KEY": "{DEST}/pk.pem".format(**data),
                "EC2_CERT": "{DEST}/cert.pem".format(**data),
                "NOVA_CERT": "{DEST}/cacert.pem".format(**data),
                "EUCALYPTUS_CERT": "{DEST}/cacert.pem".format(**data),
            },
            "default": {
                "flavor": "m1.small",
                "image": "None",
            }
        }
        config = ConfigDict("cloudmesh.yaml")
        config["cloudmesh"]["clouds"][cloud] = d
        config.save()
开发者ID:arpiagariu,项目名称:client,代码行数:59,代码来源:register.py

示例6: test_002_set

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def test_002_set(self):
        """testing to set a value in the dict"""
        HEADING()
        shutil.copy(self.etc_yaml, self.tmp_yaml)
        d = ConfigDict("cloudmesh.yaml", load_order=[self.tmp_dir], verbose=True)
        d["cloudmesh"]["profile"]["firstname"] = "Gregor"
        d.save()

        d = ConfigDict("cloudmesh.yaml", load_order=[self.tmp_dir], verbose=True)
        assert d["cloudmesh"]["profile"]["firstname"] == "Gregor"
开发者ID:rajaramcomputers,项目名称:client,代码行数:12,代码来源:test_configdict.py

示例7: fill_out_form

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def fill_out_form(cls, filename):
        """
        edits profile and clouds from cloudmesh.yaml
        :param filename:
        :type filename: string
        :return:
        """
        Console.ok("Filling out form")
        print(filename)
        config = ConfigDict(filename)
        #
        # edit profile
        #

        profile = config["cloudmesh"]["profile"]
        keys = list(profile.keys())

        # TODO: test this and delete this comment
        # get input that works in python 2 and 3

        # replaced by
        #   from builtins import input
        # input = None
        # try:
        #    input = input
        # except NameError:
        #    pass

        for key in keys:
            if profile[key] == "TBD":
                result = input("Please enter {:}[{:}]:".format(key, profile[key])) or profile[key]
                profile[key] = result

        config["cloudmesh"]["profile"] = profile
        config.save()

        # edit clouds
        clouds = config["cloudmesh"]["clouds"]
        for cloud in list(clouds.keys()):
            print("Editing the credentials for cloud", cloud)
            credentials = clouds[cloud]["credentials"]

            for key in credentials:
                if key not in ["OS_VERSION", "OS_AUTH_URL"] and credentials[key] == "TBD":
                    result = input("Please enter {:}[{:}]:".format(key, credentials[key])) or credentials[key]
                    credentials[key] = result
            config["cloudmesh"]["clouds"][cloud]["credentials"] = credentials
        config.save()
开发者ID:arpiagariu,项目名称:client,代码行数:50,代码来源:register.py

示例8: do_color

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def do_color(self, args, arguments):
        """
        ::

            Usage:
                color FLAG

            Arguments:

                FLAG    color mode flag ON/OFF

            Description:

                Global switch for the console color mode.
                One can switch the color mode on/off with
                    cm color mode ON
                    cm color mode OFF

                By default, the color mode is ON

            Examples:
                color mode ON
                color mode OFF
        """

        # default mode is ON
        color_mode = True

        flag = arguments["FLAG"].lower()
        if flag in ["on", "true"]:
            color_mode = True
            Console.set_theme(color=True)
        elif flag in ["off", "false"]:
            color_mode = False
            Console.set_theme(color=False)
        else:
            Console.error("Invalid Flag")
            return

        # Update the cloudmesh.yaml file
        config = ConfigDict("cloudmesh.yaml")
        config["cloudmesh"]["system"]["console_color"] = color_mode
        config.save()

        Console.color = color_mode
        Console.ok("Color {:}".format(str(color_mode)))

        return ""
开发者ID:atavism,项目名称:client,代码行数:50,代码来源:ColorCommand.py

示例9: get_apikey

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
 def get_apikey():
     user = raw_input("Comet Nucleus Usename: ")
     password = getpass.getpass()
     keyurl = "https://comet-nucleus.sdsc.edu/nucleus/getkey"
     headers = {"ACCEPT": "application/json"}
     r = requests.get(keyurl, headers=headers, auth=HTTPBasicAuth(user, password))
     if r.status_code == 200:
         keyobj = r.json()
         api_key = keyobj["key_name"]
         api_secret = keyobj["key"]
         config = ConfigDict("cloudmesh.yaml")
         config.data["cloudmesh"]["comet"]["auth_provider"] = 'apikey'
         config.data["cloudmesh"]["comet"]["apikey"]["api_key"] = api_key
         config.data["cloudmesh"]["comet"]["apikey"]["api_secret"] = api_secret
         config.save()
         Console.ok("api key retrieval and set was successful!")
     else:
         Console.error("Error getting api key. " \
                       "Please check your username/password", traceflag=False)
开发者ID:alistairking,项目名称:client,代码行数:21,代码来源:comet.py

示例10: read_rc_file

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def read_rc_file(cls, host, openrc, force=False):
        """

        :param host: the host name
        :type host: string
        :param openrc: the file name
        :type openrc: string
        :return:
        """

        openrc = Config.path_expand(openrc)

        # check if file exists
        if not os.path.isfile(openrc):
            Console.error("File not found.")
            return

        with open(openrc, 'r') as f:
            lines = f.read().split("\n")

        config = ConfigDict("cloudmesh.yaml")
        credentials = {}
        for line in lines:
            if line.strip().startswith("export "):
                line = line.replace("export ", "")
                key, value = line.split("=", 1)
                credentials[key] = value

        if host not in config["cloudmesh.clouds"] or force:
            config["cloudmesh"]["clouds"][host] = {
                "credentials": credentials,
                "cm_heading": "TBD",
                "cm_host": "TBD",
                "cm_label": "TBD",
                "cm_type": "TBD",
                "cm_type_version": "TBD"}

        config.save()
        return config["cloudmesh"]["clouds"][host]["credentials"]
开发者ID:arpiagariu,项目名称:client,代码行数:41,代码来源:register.py

示例11: do_comet

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]

#.........这里部分代码省略.........

        elif arguments["stop"]:

            cluster_id = arguments["ID"]
            print("stop", cluster_id)
            Cluster.stop(cluster_id)

        elif arguments["ll"]:

        """
        if arguments["init"]:
            print ("Initializing the comet configuration file...")
            config = ConfigDict("cloudmesh.yaml")
            # for unit testing only.
            cometConf = config["cloudmesh.comet"]
            endpoints = []
            # print (cometConf.keys())
            if "endpoints" in cometConf.keys():
                endpoints = cometConf["endpoints"].keys()
                if len(endpoints) < 1:
                    Console.error("No service endpoints available. "
                                  "Please check the config template",
                                  traceflag=False)
                    return ""
            if "username" in cometConf.keys():
                default_username = cometConf['username']
                # print (default_username)
                if 'TBD' == default_username:
                    set_default_user = \
                        input("Set a default username (RETURN to skip): ")
                    if set_default_user:
                        config.data["cloudmesh"]["comet"]["username"] = \
                            set_default_user
                        config.save()
                        Console.ok("Comet default username set!")
            if "active" in cometConf.keys():
                active_endpoint = cometConf['active']
                set_active_endpoint = \
                    input("Set the active service endpoint to use. "
                          "The availalbe endpoints are - %s [%s]: "
                          % ("/".join(endpoints),
                             active_endpoint)
                          )
                if set_active_endpoint:
                    if set_active_endpoint in endpoints:
                        config.data["cloudmesh"]["comet"]["active"] = \
                            set_active_endpoint
                        config.save()
                        Console.ok("Comet active service endpoint set!")
                    else:
                        Console.error("The provided endpoint does not match "
                                      "any available service endpoints. Try %s"
                                      % "/".join(endpoints),
                                      traceflag=False)

            if cometConf['active'] in endpoints:
                endpoint_url = cometConf["endpoints"] \
                    [cometConf['active']]["nucleus_base_url"]
                api_version = cometConf["endpoints"] \
                    [cometConf['active']]["api_version"]
                set_endpoint_url = \
                    input("Set the base url for the nucleus %s service [%s]: " \
                          % (cometConf['active'],
                             endpoint_url)
                          )
                if set_endpoint_url:
开发者ID:cloudmesh,项目名称:client,代码行数:70,代码来源:CometCommand.py

示例12: do_register

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]

#.........这里部分代码省略.........
                Console.error ("The export may not include all values", traceflag=False)
            return ""

        elif arguments['json']:
            host = arguments['HOST']
            result = CloudRegister.get(host)
            if result:
                print(json.dumps(result, indent=4))
            else:
                print("Cloud {:} is not described in cloudmesh.yaml".format(
                    host))
            return ""

        elif arguments['remote']:

            force = arguments['--force']
            cloud = arguments['CLOUD']

            if cloud is None:
                # clouds =  [ConfigDict(filename="cloudmesh.yaml")["cloudmesh"]["active"][0]]
                clouds = ["kilo"]  # hardcode to kilo for now

            else:
                clouds = [cloud]

            for cloud in clouds:
                CloudRegister.remote(cloud, force)
                export(cloud, "table")

            config = ConfigDict("cloudmesh.yaml")
            if config["cloudmesh.profile.user"] == "TBD":
                name = config["cloudmesh.clouds.kilo.credentials.OS_USERNAME"]
                config["cloudmesh"]["profile"]["user"] = name
                config.save()
            return ""

        elif arguments['ec2']:

            cloud = arguments['CLOUD']
            zipfile = arguments['EC2ZIP']

            if cloud is None:
                clouds = [ConfigDict(filename="cloudmesh.yaml")["cloudmesh"]["active"][0]]
            else:
                clouds = [cloud]

            for cloud in clouds:
                CloudRegister.ec2(cloud, zipfile)
                export(cloud, "table")

            return ""

        elif arguments['env']:
            try:
                CloudRegister.from_environ(arguments['--provider'])
            except Exception as e:
                Error.traceback(e)
            return ""

        elif arguments['cloud']:
            """
            if arguments['--dir']:
                cloud = arguments['--name']
                directory = arguments['--dir']
                Console.ok(directory)
                CloudRegister.directory(cloud, directory)
开发者ID:cloudmesh,项目名称:client,代码行数:70,代码来源:RegisterCommand.py

示例13: from_environ

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def from_environ(cls, provider):
        """
        Reads env OS_* variables and registers a new cloud in yaml, interactively.
        :return:
        """
        yaml_data = ConfigDict("cloudmesh.yaml")
        env_config_data = cls.read_env_config()

        if env_config_data["OS_AUTH_URL"] is None:
            print("ERROR: Cloud credentials not set in environment")
            return

        cloudname_suggest = urlparse(env_config_data["OS_AUTH_URL"]).hostname

        # Command line inputs
        cloudname_to_use = input(
            "Name of the cloud (Default: {:}): ".format(
                cloudname_suggest)) or cloudname_suggest

        cm_label = input(
            "Label for the cloud (Default: {:}): ".format(cloudname_to_use)) or "{:}".format(cloudname_to_use)

        cm_heading = input(
            "Heading for the cloud (Default: {:} Cloud): ".format(cm_label)) or "{:} Cloud".format(cm_label)

        cm_host = input("Cloud host name (Default: {:}): ".format(cloudname_suggest)) or "{:}" \
            .format(cloudname_suggest)

        if provider is None:
            # TODO: Check if the suggestion can be determined dynamically
            cm_type = input("Type of the cloud- openstack/azure/ec2 "
                            "(Default: openstack): ") or "openstack"
        else:
            cm_type = provider

        while cm_type not in ["openstack", "azure", "ec2"]:
            print("\nType of cloud '{:}' is invalid and should be one "
                  "of openstack/ azure/ ec2.\n"
                  .format(cm_type))
            cm_type = input("Type of the cloud- openstack/azure/ec2 "
                            "(Default: openstack): ") or "openstack"

        cm_type_version = input(
            "Version of type {:} (Default: null): ".format(cm_type)) or None

        #  Populate the dict with the data fetched from env
        yaml_data["cloudmesh"]["clouds"][cloudname_to_use] = \
            {"cm_heading": cm_heading,
             "cm_host": cm_host,
             "cm_label": cm_label,
             "cm_type": cm_type,
             "cm_type_version": cm_type_version,
             "credentials": env_config_data
             }

        # Get defaults from user

        default_flavor = input("Default flavor for the cloud instances"
                               "(Default: null): ") or None

        default_image = input("Default image for the cloud instances"
                              " (Default: null): ") or None

        default_location = input(
            "Default location for the cloud instances "
            "(Default: null): ") or None

        yaml_data["cloudmesh"]["clouds"][cloudname_to_use]["default"] = \
            {"flavor": default_flavor,
             "image": default_image,
             "location": default_location
             }

        # Save data in yaml
        yaml_data.save()
        print("New cloud config exported to {:}".format(yaml_data.filename))
开发者ID:arpiagariu,项目名称:client,代码行数:78,代码来源:register.py

示例14: remote

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]
    def remote(cls, host, force=False):
        """

        TODO: there is a bug in the instalation of kilo the openrc file on
        the remote machine is not called openrc.sh but contains username and
        project number.

        :param host: the remote host
        :param force:
        :return:
        """

        config = ConfigDict("cloudmesh.yaml")

        host_spec = config["cloudmesh.clouds." + host]
        host_credentials = host_spec["credentials"]

        if 'cm_openrc' in host_spec:
            Console.ok("looking for openrc")
        else:
            Console.error("no cm_openrc specified in the host")
            return

        hostname = config["cloudmesh.clouds." + host + ".cm_host"]
        Console.ok("fetching information from {:}  ...".format(host))

        openrc = host_spec["cm_openrc"]

        directory = os.path.dirname(openrc)
        base = os.path.basename(openrc)

        _from_dir = "{:}:{:}".format(hostname, directory + "/*").replace("~/", "")
        # _to_dir = os.path.dirname(Config.path_expand(directory))
        # FIX: Issues with path expanding on Windows
        _to_dir = os.path.realpath(
            os.path.expanduser(directory)
        )

        '''
        In Windows, SCP fails with path such as C:\\Users\\...,
            and passes with '~/.cloudmesh/...'
        But on Linux machines, it fails with ~/.cloudmesh/...
            and passes with /home/user/...
        Hence, adding OS check below for SCP copy directory
        '''
        os_type = platform.system().lower()
        if 'windows' not in os_type:
            directory = _to_dir

        # FIX: fix for scp not working on Windows, because scp does not
        # understand
        # paths in format: "C:/Users/<>", rather expects "~/.cloudmesh/<>"
        # openrc_file = Config.path_expand(openrc)
        openrc_file = os.path.realpath(
            os.path.expanduser(openrc)
        )
        print("From:  ", _from_dir)
        print("To:    ", _to_dir)
        print("Openrc:", openrc_file)

        cls.make_dir(_to_dir)
        r = ""
        Console.ok("Reading rc file from {}".format(host))
        try:
            r = Shell.scp('-r', _from_dir, directory)
        except Exception as e:
            print(e)
            return

        #
        # TODO: the permission are not yet right
        #
        os.chmod(_to_dir, 0o700)
        for root, dirs, _ in os.walk(_to_dir):
            for d in dirs:
                os.chmod(os.path.join(root, d), 0o700)
        #
        # END PERMISSION
        #

        with open(openrc_file, 'r') as f:
            lines = f.read().split("\n")

        config = ConfigDict("cloudmesh.yaml")
        for line in lines:
            if line.strip().startswith("export"):
                line = line.replace("export ", "")
                key, value = line.split("=", 1)
                config["cloudmesh"]["clouds"][host]["credentials"][key] = value
        host_spec = config["cloudmesh"]["clouds"][host]
        credentials = host_spec["credentials"]

        if "cm_openrc" in host_spec:
            openrc = host_spec["cm_openrc"]
            for attribute in credentials:
                if attribute in openrc:
                    openrc.replace(attribute, credentials[attribute])
        config.save()
        config = ConfigDict("cloudmesh.yaml")
        return config["cloudmesh"]["clouds"][host]["credentials"]
开发者ID:arpiagariu,项目名称:client,代码行数:102,代码来源:register.py

示例15: do_comet

# 需要导入模块: from cloudmesh_client.common.ConfigDict import ConfigDict [as 别名]
# 或者: from cloudmesh_client.common.ConfigDict.ConfigDict import save [as 别名]

#.........这里部分代码省略.........
            Cluster.start(cluster_id)

        elif arguments["stop"]:

            cluster_id = arguments["ID"]
            print("stop", cluster_id)
            Cluster.stop(cluster_id)

        elif arguments["ll"]:

        """
        if arguments["init"]:
            print ("Initializing the comet configuration file...")
            config = ConfigDict("cloudmesh.yaml")
            # for unit testing only.
            cometConf = config["cloudmesh.comet"]
            endpoints = []
            # print (cometConf.keys())
            if "endpoints" in cometConf.keys():
                endpoints = cometConf["endpoints"].keys()
                if len(endpoints) < 1:
                    Console.error("No service endpoints available."\
                                  " Please check the config template")
                    return ""
            if "username" in cometConf.keys():
                default_username = cometConf['username']
                # print (default_username)
                if 'TBD' == default_username:
                    set_default_user = \
                        input("Set a default username (RETURN to skip): ")
                    if set_default_user:
                        config.data["cloudmesh"]["comet"]["username"] = \
                            set_default_user
                        config.save()
                        Console.ok("Comet default username set!")
            if "active" in cometConf.keys():
                active_endpoint = cometConf['active']
                set_active_endpoint = \
                        input("Set the active service endpoint to use. "\
                                  "The availalbe endpoints are - %s [%s]: "\
                                   % ("/".join(endpoints),
                                     active_endpoint)
                                 )
                if set_active_endpoint:
                    if set_active_endpoint in endpoints:
                        config.data["cloudmesh"]["comet"]["active"] = \
                                        set_active_endpoint
                        config.save()
                        Console.ok("Comet active service endpoint set!")
                    else:
                        Console.error("The provided endpoint does not match any "\
                                      "available service endpoints. Try %s" \
                                      % "/".join(endpoints) )

            if cometConf['active'] in endpoints:
                endpoint_url = cometConf["endpoints"]\
                               [cometConf['active']]["nucleus_base_url"]
                api_version = cometConf["endpoints"]\
                               [cometConf['active']]["api_version"]
                set_endpoint_url = \
                        input("Set the base url for the nucleus %s service [%s]: "\
                                   % (cometConf['active'],
                                      endpoint_url)
                                 )
                if set_endpoint_url:
                    if set_endpoint_url != endpoint_url:
开发者ID:sohiljain,项目名称:client,代码行数:70,代码来源:CometCommand.py


注:本文中的cloudmesh_client.common.ConfigDict.ConfigDict.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。