Beispiel #1
0
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory_args = dict(
            refresh=args.refresh,
            config_files=config_files,
            private=args.private,
            cloud=args.cloud,
        )
        if hasattr(shade.inventory.OpenStackInventory, 'extra_config'):
            inventory_args.update(
                dict(config_key='ansible',
                     config_defaults={
                         'use_hostnames': False,
                         'expand_hostvars': True,
                         'fail_on_errors': True,
                     }))

        inventory = shade.inventory.OpenStackInventory(**inventory_args)

        if args.list:
            output = get_host_groups(inventory,
                                     refresh=args.refresh,
                                     cloud=args.cloud)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Beispiel #2
0
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory_args = dict(refresh=args.refresh, config_files=config_files, private=args.private)
        if hasattr(shade.inventory.OpenStackInventory, "extra_config"):
            inventory_args.update(
                dict(config_key="ansible", config_defaults={"use_hostnames": False, "expand_hostvars": True})
            )
        # shade.inventory ignores OS_CLOUD
        # http://git.openstack.org/cgit/openstack-infra/shade/tree/shade/inventory.py?h=1.12.1#n38
        cloud = os.getenv("OS_CLOUD")
        if cloud:
            inventory_args["cloud"] = cloud

        inventory = shade.inventory.OpenStackInventory(**inventory_args)

        if args.list:
            output = get_host_groups(inventory, refresh=args.refresh)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write("%s\n" % e.message)
        sys.exit(1)
    sys.exit(0)
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory_args = dict(
            refresh=args.refresh,
            config_files=config_files,
            private=args.private,
        )
        if hasattr(shade.inventory.OpenStackInventory, 'extra_config'):
            inventory_args.update(dict(
                config_key='ansible',
                config_defaults={
                    'use_hostnames': False,
                    'expand_hostvars': True,
                }
            ))

        inventory = shade.inventory.OpenStackInventory(**inventory_args)

        if args.list:
            output = get_host_groups(inventory, refresh=args.refresh)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory_args = dict(
            refresh=args.refresh,
            config_files=config_files,
            private=True,
        )
        if hasattr(shade.inventory.OpenStackInventory, 'extra_config'):
            inventory_args.update(
                dict(config_key='ansible',
                     config_defaults={
                         'use_hostnames': False,
                         'expand_hostvars': True,
                         'fail_on_errors': True,
                     }))
        # shade.inventory ignores OS_CLOUD
        # http://git.openstack.org/cgit/openstack-infra/shade/tree/shade/inventory.py?h=1.12.1#n38
        cloud = os.getenv('OS_CLOUD')
        if cloud:
            inventory_args['cloud'] = cloud

        inventory = shade.inventory.OpenStackInventory(**inventory_args)

        if args.list:
            output = get_host_groups(inventory, refresh=args.refresh)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Beispiel #5
0
    def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = int(os.environ.get('OS_TEST_TIMEOUT', 0))
        try:
            test_timeout = int(test_timeout * self.TIMEOUT_SCALING_FACTOR)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        shade.simple_logging(debug=True)
        self.log_fixture = self.useFixture(fixtures.FakeLogger())
Beispiel #6
0
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory_args = dict(
            refresh=args.refresh,
            config_files=config_files,
        )
        if hasattr(shade.inventory.OpenStackInventory, 'extra_config'):
            inventory_args.update(
                dict(config_key='ansible',
                     config_defaults={
                         'use_hostnames': False,
                         'expand_hostvars': True,
                     }))

        inventory = shade.inventory.OpenStackInventory(**inventory_args)

        sshconfig = build_sshconfig(args.ucl)
        sshkey = build_sshkey(args.sshkey)

        if (sshconfig is not None):
            infor = get_host_groups(inventory, refresh=args.refresh)

            build_bastion(sshconfig, sshkey, infor)
            store_group_vars(infor)

    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Beispiel #7
0
def set_logging(debug_mode):
    if debug_mode:
        log_format = "%(asctime)-15s %(message)s"
        logging.basicConfig(format=log_format, level=logging.DEBUG)
        shade.simple_logging(debug=debug_mode)
    else:
        log_format = "%(message)s"
        logging.basicConfig(format=log_format, level=logging.INFO)
Beispiel #8
0
def set_logging(debug_mode):
    if debug_mode:
        log_format = "%(asctime)-15s %(message)s"
        logging.basicConfig(format=log_format, level=logging.DEBUG)
        shade.simple_logging(debug=debug_mode)
    else:
        log_format = "%(message)s"
        logging.basicConfig(format=log_format, level=logging.INFO)
Beispiel #9
0
def serve():
    shade.simple_logging(debug=True)
    logging.getLogger().setLevel(logging.INFO)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    oaktree_pb2.add_OaktreeServicer_to_server(OaktreeServicer(), server)
    server.add_insecure_port('[::]:50051')
    logging.info("Starting server")
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
Beispiel #10
0
def serve():
    shade.simple_logging(debug=True)
    logging.getLogger().setLevel(logging.INFO)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    oaktree_pb2.add_OaktreeServicer_to_server(OaktreeServicer(), server)
    server.add_insecure_port('[::]:50051')
    logging.info("Starting server")
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
Beispiel #11
0
def main():
    args = parse_args()
    try:
        shade.simple_logging(debug=args.debug)
        inventory = shade.inventory.OpenStackInventory(refresh=args.refresh,
                                                       private=args.private)
        if args.list:
            output = inventory.list_hosts()
        elif args.host:
            output = inventory.get_host(args.host)
        print(output_format_dict(output, args.yaml))
    except shade.OpenStackCloudException as e:
        sys.stderr.write(e.message + '\n')
        sys.exit(1)
    sys.exit(0)
Beispiel #12
0
def main():
    args = parse_args()
    try:
        shade.simple_logging(debug=args.debug)
        inventory = shade.inventory.OpenStackInventory(
            refresh=args.refresh, private=args.private)
        if args.list:
            output = inventory.list_hosts()
        elif args.host:
            output = inventory.get_host(args.host)
        print(output_format_dict(output, args.yaml))
    except shade.OpenStackCloudException as e:
        sys.stderr.write(e.message + '\n')
        sys.exit(1)
    sys.exit(0)
Beispiel #13
0
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory = shade.inventory.OpenStackInventory(
            refresh=args.refresh,
            config_files=config_files,
            private=args.private,
        )

        if args.list:
            output = get_host_groups(inventory)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Beispiel #14
0
def main():
    args = parse_args()
    try:
        config_files = os_client_config.config.CONFIG_FILES + CONFIG_FILES
        shade.simple_logging(debug=args.debug)
        inventory = shade.inventory.OpenStackInventory(
            refresh=args.refresh,
            config_files=config_files,
            private=args.private,
        )

        if args.list:
            output = get_host_groups(inventory)
        elif args.host:
            output = to_json(inventory.get_host(args.host))
        print(output)
    except shade.OpenStackCloudException as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Beispiel #15
0
def main():
    module = AnsibleModule(
        argument_spec={
            'method': {'required': True, 'type': 'str'},
            'args': {'required': False, 'type': 'list', 'default': []},
            'kwargs': {'required': False, 'type': 'dict', 'default': {}},
            'os_auth': {'required': False, 'type': 'dict', 'default': {}},
            'fact_name': {'required': True, 'type': 'str'},
        }
    )

    if not SHADE_PRESENT:
        module.fail_json(msg="shade not found")
    shade.simple_logging(debug=True)
    params = module.params
    method = params['method']
    args = params['args']
    kwargs = params['kwargs']
    os_auth = params['os_auth']
    fact_name = params['fact_name']
    if os_auth:
        os.environ.update(os_auth)

    c = shade.openstack_cloud()
    module.debug(args)
    module.debug(kwargs)
    ret = getattr(c, method)(*args, **kwargs)
    if ret:
        try:
            # convert to regular dict, might not be necessary
            ret = ret.toDict()
        except AttributeError:
            pass
    else:
        ret = {}
    ansible_facts = {
        fact_name: ret
    }
    module.exit_json(ansible_facts=ansible_facts)
Beispiel #16
0
def build_vm():

    # set env vars and build vm
    shade.simple_logging(debug=False)
    cloud = shade.openstack_cloud(name='yolocloud')
    image = cloud.get_image(image_name)
    key = cloud.search_keypairs(name_or_id=keypair_name)
    flavor = cloud.get_flavor_by_ram(1000)
    server_name = "vpci-testnode-" + str(uuid.uuid4())
    cloud.create_server(server_name, image['id'], flavor['id'], key_name=key[0]['id'])
    server = cloud.get_server(server_name)

    # poll until the node comes up
    while True:
        print "HODOR, cloud slow"
        time.sleep(2)
        server = cloud.get_server(server_name)
        if len(server.addresses) > 0:
            break

    print "server created, sleeping 2 minutes for it to boot"
    time.sleep(120)
    return server
Beispiel #17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="server name")
    parser.add_argument("--cloud",
                        dest="cloud",
                        required=True,
                        help="cloud name")
    parser.add_argument("--region", dest="region", help="cloud region")
    parser.add_argument("--flavor",
                        dest="flavor",
                        default='1GB',
                        help="name (or substring) of flavor")
    parser.add_argument("--image",
                        dest="image",
                        default="Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)",
                        help="image name")
    parser.add_argument("--volume",
                        dest="volume",
                        help="UUID of volume to attach to the new server.",
                        default=None)
    parser.add_argument("--mount-path",
                        dest="mount_path",
                        help="Path to mount cinder volume at.",
                        default=None)
    parser.add_argument("--fs-label",
                        dest="fs_label",
                        help="FS label to use when mounting cinder volume.",
                        default=None)
    parser.add_argument("--boot-from-volume",
                        dest="boot_from_volume",
                        help="Create a boot volume for the server and use it.",
                        action='store_true',
                        default=False)
    parser.add_argument("--keep",
                        dest="keep",
                        help="Don't clean up or delete the server on error.",
                        action='store_true',
                        default=False)
    parser.add_argument("--verbose",
                        dest="verbose",
                        default=False,
                        action='store_true',
                        help="Be verbose about logging cloud actions")
    parser.add_argument("--network",
                        dest="network",
                        default=None,
                        help="network label to attach instance to")
    parser.add_argument("--config-drive",
                        dest="config_drive",
                        help="Boot with config_drive attached.",
                        action='store_true',
                        default=False)
    parser.add_argument("--az",
                        dest="availability_zone",
                        default=None,
                        help="AZ to boot in.")
    options = parser.parse_args()

    shade.simple_logging(debug=options.verbose)

    cloud_kwargs = {}
    if options.region:
        cloud_kwargs['region_name'] = options.region
    cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
        options.cloud, **cloud_kwargs)

    cloud = shade.OpenStackCloud(cloud_config)

    flavor = cloud.get_flavor(options.flavor)
    if flavor:
        print "Found flavor", flavor.name
    else:
        print "Unable to find matching flavor; flavor list:"
        for i in cloud.list_flavors():
            print i.name
        sys.exit(1)

    image = cloud.get_image_exclude(options.image, 'deprecated')
    if image:
        print "Found image", image.name
    else:
        print "Unable to find matching image; image list:"
        for i in cloud.list_images():
            print i.name
        sys.exit(1)

    server = build_server(cloud, options.name, image, flavor, options.volume,
                          options.keep, options.network,
                          options.boot_from_volume, options.config_drive,
                          options.mount_path, options.fs_label,
                          options.availability_zone)
    dns.print_dns(cloud, server)
Beispiel #18
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="server name")
    parser.add_argument("--cloud", dest="cloud", required=True,
                        help="cloud name")
    parser.add_argument("--region", dest="region",
                        help="cloud region")
    parser.add_argument("--flavor", dest="flavor", default='1GB',
                        help="name (or substring) of flavor")
    parser.add_argument("--image", dest="image",
                        default="Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)",
                        help="image name")
    parser.add_argument("--volume", dest="volume",
                        help="UUID of volume to attach to the new server.",
                        default=None)
    parser.add_argument("--boot-from-volume", dest="boot_from_volume",
                        help="Create a boot volume for the server and use it.",
                        action='store_true',
                        default=False)
    parser.add_argument("--keep", dest="keep",
                        help="Don't clean up or delete the server on error.",
                        action='store_true',
                        default=False)
    parser.add_argument("--verbose", dest="verbose", default=False,
                        action='store_true',
                        help="Be verbose about logging cloud actions")
    parser.add_argument("--network", dest="network", default=None,
                        help="network label to attach instance to")
    parser.add_argument("--config-drive", dest="config_drive",
                        help="Boot with config_drive attached.",
                        action='store_true',
                        default=True)
    options = parser.parse_args()

    shade.simple_logging(debug=options.verbose)

    cloud_kwargs = {}
    if options.region:
        cloud_kwargs['region_name'] = options.region
    cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
        options.cloud, **cloud_kwargs)

    cloud = shade.OpenStackCloud(cloud_config)

    flavor = cloud.get_flavor(options.flavor)
    if flavor:
        print "Found flavor", flavor.name
    else:
        print "Unable to find matching flavor; flavor list:"
        for i in cloud.list_flavors():
            print i.name
        sys.exit(1)

    image = cloud.get_image_exclude(options.image, 'deprecated')
    if image:
        print "Found image", image.name
    else:
        print "Unable to find matching image; image list:"
        for i in cloud.list_images():
            print i.name
        sys.exit(1)

    server = build_server(cloud, options.name, image, flavor,
                          options.volume, options.keep,
                          options.network, options.boot_from_volume,
                          options.config_drive)
    dns.print_dns(cloud, server)

    # Zero the ansible inventory cache so that next run finds the new server
    inventory_cache = '/var/cache/ansible-inventory/ansible-inventory.cache'
    if os.path.exists(inventory_cache):
        with open(inventory_cache, 'w'):
            pass
    # Remove cloud and region from the environment to work around a bug in occ
    expand_env = os.environ.copy()
    expand_env.pop('OS_CLOUD', None)
    expand_env.pop('OS_REGION_NAME', None)

    print subprocess.check_output(
        '/usr/local/bin/expand-groups.sh',
        env=expand_env,
        stderr=subprocess.STDOUT)
Beispiel #19
0
import shade
shade.simple_logging()

cloud = shade.openstack_cloud(cloud='fuga', region_name='cystack', strict=True)
image = cloud.get_image(
    'Ubuntu 16.04 LTS - Xenial Xerus - 64-bit - Fuga Cloud Based Image')
cloud.pprint(image)
Beispiel #20
0
    def parse(self, inventory, loader, path, cache=True):

        super(InventoryModule, self).parse(inventory, loader, path)

        cache_key = self._get_cache_prefix(path)

        # file is config file
        self._config_data = self._read_config_data(path)

        msg = ''
        if not self._config_data:
            msg = 'File empty. this is not my config file'
        elif 'plugin' in self._config_data and self._config_data['plugin'] != self.NAME:
            msg = 'plugin config file, but not for us: %s' % self._config_data['plugin']
        elif 'plugin' not in self._config_data and 'clouds' not in self._config_data:
            msg = "it's not a plugin configuration nor a clouds.yaml file"
        elif not HAS_SHADE:
            msg = "shade is required for the OpenStack inventory plugin. OpenStack inventory sources will be skipped."

        if msg:
            raise AnsibleParserError(msg)

        # The user has pointed us at a clouds.yaml file. Use defaults for
        # everything.
        if 'clouds' in self._config_data:
            self._config_data = {}

        source_data = None
        if cache and cache_key in self._cache:
            try:
                source_data = self._cache[cache_key]
            except KeyError:
                pass

        if not source_data:
            clouds_yaml_path = self._config_data.get('clouds_yaml_path')
            if clouds_yaml_path:
                config_files = (clouds_yaml_path +
                                os_client_config.config.CONFIG_FILES)
            else:
                config_files = None

            # TODO(mordred) Integrate shade's logging with ansible's logging
            shade.simple_logging()

            cloud_inventory = shade.inventory.OpenStackInventory(
                config_files=config_files,
                private=self._config_data.get('private', False))
            only_clouds = self._config_data.get('only_clouds', [])
            if only_clouds and not isinstance(only_clouds, list):
                raise ValueError(
                    'OpenStack Inventory Config Error: only_clouds must be'
                    ' a list')
            if only_clouds:
                new_clouds = []
                for cloud in cloud_inventory.clouds:
                    if cloud.name in only_clouds:
                        new_clouds.append(cloud)
                cloud_inventory.clouds = new_clouds

            expand_hostvars = self._config_data.get('expand_hostvars', False)
            fail_on_errors = self._config_data.get('fail_on_errors', False)

            source_data = cloud_inventory.list_hosts(
                expand=expand_hostvars, fail_on_cloud_config=fail_on_errors)

            self._cache[cache_key] = source_data

        self._populate_from_source(source_data)
Beispiel #21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="server name")
    parser.add_argument("--cloud", dest="cloud", required=True,
                        help="cloud name")
    parser.add_argument("--region", dest="region",
                        help="cloud region")
    parser.add_argument("--flavor", dest="flavor", default='1GB',
                        help="name (or substring) of flavor")
    parser.add_argument("--image", dest="image",
                        default="Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)",
                        help="image name")
    parser.add_argument("--volume", dest="volume",
                        help="UUID of volume to attach to the new server.",
                        default=None)
    parser.add_argument("--mount-path", dest="mount_path",
                        help="Path to mount cinder volume at.",
                        default=None)
    parser.add_argument("--fs-label", dest="fs_label",
                        help="FS label to use when mounting cinder volume.",
                        default=None)
    parser.add_argument("--boot-from-volume", dest="boot_from_volume",
                        help="Create a boot volume for the server and use it.",
                        action='store_true',
                        default=False)
    parser.add_argument("--keep", dest="keep",
                        help="Don't clean up or delete the server on error.",
                        action='store_true',
                        default=False)
    parser.add_argument("--verbose", dest="verbose", default=False,
                        action='store_true',
                        help="Be verbose about logging cloud actions")
    parser.add_argument("--network", dest="network", default=None,
                        help="network label to attach instance to")
    parser.add_argument("--config-drive", dest="config_drive",
                        help="Boot with config_drive attached.",
                        action='store_true',
                        default=True)
    parser.add_argument("--az", dest="availability_zone", default=None,
                        help="AZ to boot in.")
    options = parser.parse_args()

    shade.simple_logging(debug=options.verbose)

    cloud_kwargs = {}
    if options.region:
        cloud_kwargs['region_name'] = options.region
    cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
        options.cloud, **cloud_kwargs)

    cloud = shade.OpenStackCloud(cloud_config)

    flavor = cloud.get_flavor(options.flavor)
    if flavor:
        print "Found flavor", flavor.name
    else:
        print "Unable to find matching flavor; flavor list:"
        for i in cloud.list_flavors():
            print i.name
        sys.exit(1)

    image = cloud.get_image_exclude(options.image, 'deprecated')
    if image:
        print "Found image", image.name
    else:
        print "Unable to find matching image; image list:"
        for i in cloud.list_images():
            print i.name
        sys.exit(1)

    server = build_server(cloud, options.name, image, flavor,
                          options.volume, options.keep,
                          options.network, options.boot_from_volume,
                          options.config_drive,
                          options.mount_path, options.fs_label,
                          options.availability_zone)
    dns.print_dns(cloud, server)

    # Zero the ansible inventory cache so that next run finds the new server
    inventory_cache = '/var/cache/ansible-inventory/ansible-inventory.cache'
    if os.path.exists(inventory_cache):
        with open(inventory_cache, 'w'):
            pass
    # Remove cloud and region from the environment to work around a bug in occ
    expand_env = os.environ.copy()
    expand_env.pop('OS_CLOUD', None)
    expand_env.pop('OS_REGION_NAME', None)

    print subprocess.check_output(
        '/usr/local/bin/expand-groups.sh',
        env=expand_env,
        stderr=subprocess.STDOUT)
    def parse(self, inventory, loader, path, cache=False):

        super(InventoryModule, self).parse(inventory, loader, path)

        cache_key = self.get_cache_prefix(path)

        # file is config file
        try:
            self._config_data = self.loader.load_from_file(path)
        except Exception as e:
            raise AnsibleParserError(e)

        msg = ''
        if not self._config_data:
            msg = 'File empty. this is not my config file'
        elif 'plugin' in self._config_data and self._config_data[
                'plugin'] != self.NAME:
            msg = 'plugin config file, but not for us: %s' % self._config_data[
                'plugin']
        elif 'plugin' not in self._config_data and 'clouds' not in self._config_data:
            msg = "it's not a plugin configuration nor a clouds.yaml file"
        elif not HAS_SHADE:
            msg = "shade is required for the OpenStack inventory plugin. OpenStack inventory sources will be skipped."

        if msg:
            raise AnsibleParserError(msg)

        # The user has pointed us at a clouds.yaml file. Use defaults for
        # everything.
        if 'clouds' in self._config_data:
            self._config_data = {}

        source_data = None
        if cache and cache_key in inventory.cache:
            try:
                source_data = inventory.cache[cache_key]
            except KeyError:
                pass

        if not source_data:
            clouds_yaml_path = self._config_data.get('clouds_yaml_path')
            if clouds_yaml_path:
                config_files = (clouds_yaml_path +
                                os_client_config.config.CONFIG_FILES)
            else:
                config_files = None

            # TODO(mordred) Integrate shade's logging with ansible's logging
            shade.simple_logging()

            cloud_inventory = shade.inventory.OpenStackInventory(
                config_files=config_files,
                private=self._config_data.get('private', False))
            only_clouds = self._config_data.get('only_clouds', [])
            if only_clouds and not isinstance(only_clouds, list):
                raise ValueError(
                    'OpenStack Inventory Config Error: only_clouds must be'
                    ' a list')
            if only_clouds:
                new_clouds = []
                for cloud in cloud_inventory.clouds:
                    if cloud.name in only_clouds:
                        new_clouds.append(cloud)
                cloud_inventory.clouds = new_clouds

            expand_hostvars = self._config_data.get('expand_hostvars', False)
            fail_on_errors = self._config_data.get('fail_on_errors', False)

            source_data = cloud_inventory.list_hosts(
                expand=expand_hostvars, fail_on_cloud_config=fail_on_errors)

            inventory.cache[cache_key] = source_data

        self._populate_from_source(source_data)
Beispiel #23
0
import shade
shade.simple_logging(http_debug=True)

cloud = shade.openstack_cloud(
    cloud='datacentred', app_name='AmazingApp', app_version='1.0')
cloud.list_networks()
Beispiel #24
0
import shade
shade.simple_logging()

cloud = shade.openstack_cloud(cloud='fuga', region_name='cystack')
image = cloud.get_image(
    'Ubuntu 16.04 LTS - Xenial Xerus - 64-bit - Fuga Cloud Based Image')
cloud.pprint(image)
Beispiel #25
0
#!/usr/bin/env python2

import shade
import os_client_config

# Name variables
name_prefix = ''
private_network_name = name_prefix + 'private-net'
private_subnet_name = name_prefix + 'private-subnet'
router_name = name_prefix + 'router'
security_group_name = name_prefix + 'sg'
keypair_name = name_prefix + 'keypair'
instance_name = name_prefix + 'instance'

# Toggle Debug logging
shade.simple_logging(debug=False)


def delete_all_resources():

    # delete instances
    for server in cloud.list_servers():
        if server.name == instance_name:
            print('Deleting instance {} ({})'.format(server.name, server.id))
            cloud.delete_server(server.id, wait=True)

    # delete keypairs
    for keypair in cloud.list_keypairs():
        if keypair.name == keypair_name:
            print('Deleting keypair {} ({})'.format(
                keypair.name,
Beispiel #26
0
def delete_vm(server):
    print "Deleting server {0}".format(server.name)
    shade.simple_logging(debug=True)
    cloud = shade.openstack_cloud(name='yolocloud')
    cloud.delete_server(server.name)
Beispiel #27
0

def add_command_parsers(subparsers):
    parser = subparsers.add_parser('start')
    parser.set_defaults(func=start)
    parser.add_argument('--flavor', required=True, help='Flavor name or ID')
    parser.add_argument('--floating', action='store_true', default=False, help='Assign floating IP address')
    parser.add_argument('--image', required=True, help='Image name or ID')
    parser.add_argument('--key', required=True, help='SSH key name')
    parser.add_argument('--network', required=True, help='Network name or ID')
    parser.add_argument('--number', required=True, type=int, help='Number of instances')
    parser.add_argument('--parallel', required=False, type=int, default=1, help='Spawn in parallel')
    parser.add_argument('--prefix', required=True, help='Instance name prefix')

commands = cfg.SubCommandOpt(
    'command', title='Commands',
    help='Show available commands.',
    handler=add_command_parsers
)
CONF.register_cli_opts([commands])


if __name__ == '__main__':
    log.register_options(CONF)
    CONF(sys.argv[1:], project=PROJECT_NAME)
    log.set_defaults()
    log.setup(CONF, PROJECT_NAME)
    shade.simple_logging(debug=CONF.debug)
    CLOUD = shade.openstack_cloud(cloud=CONF.cloud)
    CONF.command.func()
Beispiel #28
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="server name")
    parser.add_argument("--cloud", dest="cloud", required=True,
                        help="cloud name")
    parser.add_argument("--region", dest="region",
                        help="cloud region")
    parser.add_argument("--flavor", dest="flavor", default='1GB',
                        help="name (or substring) of flavor")
    parser.add_argument("--image", dest="image",
                        default="Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)",
                        help="image name")
    parser.add_argument("--environment", dest="environment",
                        help="Puppet environment to use",
                        default=None)
    parser.add_argument("--volume", dest="volume",
                        help="UUID of volume to attach to the new server.",
                        default=None)
    parser.add_argument("--mount-path", dest="mount_path",
                        help="Path to mount cinder volume at.",
                        default=None)
    parser.add_argument("--fs-label", dest="fs_label",
                        help="FS label to use when mounting cinder volume.",
                        default=None)
    parser.add_argument("--boot-from-volume", dest="boot_from_volume",
                        help="Create a boot volume for the server and use it.",
                        action='store_true',
                        default=False)
    parser.add_argument("--keep", dest="keep",
                        help="Don't clean up or delete the server on error.",
                        action='store_true',
                        default=False)
    parser.add_argument("--verbose", dest="verbose", default=False,
                        action='store_true',
                        help="Be verbose about logging cloud actions")
    parser.add_argument("--network", dest="network", default=None,
                        help="network label to attach instance to")
    parser.add_argument("--config-drive", dest="config_drive",
                        help="Boot with config_drive attached.",
                        action='store_true',
                        default=False)
    parser.add_argument("--az", dest="availability_zone", default=None,
                        help="AZ to boot in.")
    options = parser.parse_args()

    shade.simple_logging(debug=options.verbose)

    cloud_kwargs = {}
    if options.region:
        cloud_kwargs['region_name'] = options.region
    cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
        options.cloud, **cloud_kwargs)

    cloud = shade.OpenStackCloud(cloud_config)

    flavor = cloud.get_flavor(options.flavor)
    if flavor:
        print "Found flavor", flavor.name
    else:
        print "Unable to find matching flavor; flavor list:"
        for i in cloud.list_flavors():
            print i.name
        sys.exit(1)

    image = cloud.get_image_exclude(options.image, 'deprecated')
    if image:
        print "Found image", image.name
    else:
        print "Unable to find matching image; image list:"
        for i in cloud.list_images():
            print i.name
        sys.exit(1)

    server = build_server(cloud, options.name, image, flavor,
                          options.volume, options.keep,
                          options.network, options.boot_from_volume,
                          options.config_drive,
                          options.mount_path, options.fs_label,
                          options.availability_zone,
                          options.environment)
    dns.print_dns(cloud, server)
Beispiel #29
0
def create_resources(config):
    shade.simple_logging(debug=True)

    cloud = shade.openstack_cloud(cloud=config.cloud)

    domain_id = cloud.get_domain('default').id
    project_id = cloud.get_project('service').id

    user = cloud.get_user('demo')
    if not user:
        user = cloud.create_user(name='demo',
                                 domain_id=domain_id,
                                 password='******')

    granted = cloud.grant_role("admin", user="******", project="service")

    flavor_tiny = cloud.get_flavor("m1.tiny")
    if not flavor_tiny:
        flavor_tiny = cloud.create_flavor("m1.tiny", 512, 1, 1)

    flavor_small = cloud.get_flavor("m1.small")
    if not flavor_small:
        flavor_small = cloud.create_flavor("m1.small", 1024, 2, 2)

    image = cloud.get_image(config.image_name)
    if not image:
        image = cloud.create_image(config.image_name,
                                   filename=config.image_filename,
                                   container_format="bare",
                                   disk_format="qcow2",
                                   wait=True,
                                   is_public=True)

    updated = cloud.update_image_properties(image=image,
                                            os_command_line='console=ttyAMA0',
                                            hw_disk_bus='scsi',
                                            hw_scsi_model='virtio-scsi',
                                            hw_firmware_type='uefi')

    external_network = cloud.get_network("ext-net")
    if not external_network:
        external_network = cloud.create_network("ext-net",
                                                external=True,
                                                provider={
                                                    'physical_network':
                                                    "external",
                                                    'network_type': "flat"
                                                })

    external_floating = cloud.get_subnet("ext-net-floating")
    if not external_floating:
        external_floating = cloud.create_subnet(
            "ext-net",
            subnet_name="ext-net-floating",
            enable_dhcp=False,
            allocation_pools=[{
                "start": config.floating_range_start,
                "end": config.floating_range_end,
            }],
            gateway_ip=config.floating_gateway_ip,
            cidr=config.floating_cidr)

    # Create network for demo project
    demo_network = cloud.get_network("demo-net")
    if not demo_network:
        demo_network = cloud.create_network("demo-net",
                                            project_id=project_id,
                                            provider={'network_type': "vxlan"})

    demo_subnet = cloud.get_subnet("demo-subnet")
    if not demo_subnet:
        demo_subnet = cloud.create_subnet(demo_network.id,
                                          subnet_name="demo-subnet",
                                          gateway_ip="192.168.1.1",
                                          enable_dhcp=True,
                                          cidr="192.168.1.0/24",
                                          dns_nameservers=["8.8.8.8"])

    router = cloud.get_router("demo-router")
    if not router:
        router = cloud.create_router(
            name="demo-router",
            ext_gateway_net_id=cloud.get_network("ext-net").id)
        interface = cloud.add_router_interface(
            router, subnet_id=cloud.get_subnet("demo-subnet").id)

    security_group = cloud.get_security_group("default")

    allow_ping = cloud.create_security_group_rule(security_group.id,
                                                  protocol="icmp",
                                                  direction="ingress")

    allow_ssh = cloud.create_security_group_rule(security_group.id,
                                                 protocol="tcp",
                                                 direction="ingress",
                                                 port_range_min=22,
                                                 port_range_max=22)

    keypair = cloud.get_keypair("demo-default")
    if not keypair:
        keypair = cloud.create_keypair("demo-default",
                                       config.public_key_file.read())

    # Create a instance
    server = cloud.create_server(
        name="demo-vm",
        image=image.id,
        wait=True,
        auto_ip=False,
        flavor=flavor_small.id,
        security_groups=[security_group.id, 'default'],
        network=demo_network.id,
        key_name="demo-default",
    )

    # Assign a floating ip to the server
    floating_ip_address = cloud.add_auto_ip(
        server,
        wait=True,
    )

    print('Access your server at cirros@{}'.format(floating_ip_address, ))
Beispiel #30
0
import shade
shade.simple_logging(debug=True)

cloud = shade.openstack_cloud(cloud='ovh', region_name='SBG1')
cloud.create_object(
    container='my-container', name='my-object',
    filename='/home/mordred/briarcliff.sh3d',
    segment_size=1000000)
cloud.delete_object('my-container', 'my-object')
cloud.delete_container('my-container')
Beispiel #31
0
def set_debug(debug_mode):
    if debug_mode:
        shade.simple_logging(debug=debug_mode)
Beispiel #32
0
import shade

shade.simple_logging(debug=True)

cloud = shade.openstack_cloud(cloud='devstack')

flavors = cloud.list_flavors()

for flavor in flavors:
    print("Flavor ID: %s, Name: %s" % (flavor.id, flavor.name))

endpoints = cloud.list_endpoints()

for endpoint in endpoints:
    print("Endpoint URL: %s, Type: %s" % (endpoint.url, "?"))
    service = cloud.get_service(endpoint.service_id)
    print("  ", "Service Name: %s, Type: %s" % (service.name, service.type))
Beispiel #33
0
#!/usr/bin/env python

import os
import shutil
import subprocess
import tempfile
import time
import yaml

import os_client_config
import requests
import shade

shade.simple_logging(debug=os.environ.get('DEBUG', False))

CLOUD = os.environ.get('CLOUD', 'images')
IMAGESFILE = os.environ.get('IMAGESFILE', 'images.yml')
REQUIRED_KEYS = ['name', 'format', 'status', 'visibility']

with open(IMAGESFILE) as fp:
    images = yaml.load(fp)

cloud = shade.openstack_cloud(cloud=CLOUD)
glance = os_client_config.make_client("image", cloud=CLOUD)


def get_images(cloud):
    result = {}
    for image in cloud.list_images():
        if image.is_public or image.owner == cloud.current_project_id:
            result[image.name] = image