def create_connection(): """ Create a connection to oVirt engine API. """ # Get the path of the configuration file, by default use # 'ovirt.ini' file in script directory: default_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'ovirt.ini', ) config_path = os.environ.get('OVIRT_INI_PATH', default_path) # Create parser and add ovirt section if it doesn't exist: config = configparser.SafeConfigParser( defaults={ 'ovirt_url': os.environ.get('OVIRT_URL'), 'ovirt_username': os.environ.get('OVIRT_USERNAME'), 'ovirt_password': os.environ.get('OVIRT_PASSWORD'), 'ovirt_ca_file': os.environ.get('OVIRT_CAFILE', ''), }) if not config.has_section('ovirt'): config.add_section('ovirt') config.read(config_path) # Create a connection with options defined in ini file: return sdk.Connection( url=config.get('ovirt', 'ovirt_url'), username=config.get('ovirt', 'ovirt_username'), password=config.get('ovirt', 'ovirt_password', raw=True), ca_file=config.get('ovirt', 'ovirt_ca_file') or None, insecure=not config.get('ovirt', 'ovirt_ca_file'), )
def read_settings(self): ''' Reads the settings from the rudder.ini file ''' if six.PY2: config = configparser.SafeConfigParser() else: config = configparser.ConfigParser() rudder_default_ini_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'rudder.ini') rudder_ini_path = os.path.expanduser( os.path.expandvars( os.environ.get('RUDDER_INI_PATH', rudder_default_ini_path))) config.read(rudder_ini_path) self.token = os.environ.get('RUDDER_API_TOKEN', config.get('rudder', 'token')) self.version = os.environ.get('RUDDER_API_VERSION', config.get('rudder', 'version')) self.uri = os.environ.get('RUDDER_API_URI', config.get('rudder', 'uri')) self.disable_ssl_validation = config.getboolean( 'rudder', 'disable_ssl_certificate_validation') self.group_name = config.get('rudder', 'group_name') self.fail_if_name_collision = config.getboolean( 'rudder', 'fail_if_name_collision') self.cache_path = config.get('rudder', 'cache_path') self.cache_max_age = config.getint('rudder', 'cache_max_age')
def parse_ini_file(self): config = configparser.SafeConfigParser() config.read( os.path.dirname(os.path.realpath(__file__)) + '/nagios_livestatus.ini') for section in config.sections(): if not config.has_option(section, 'livestatus_uri'): continue # If fields_to_retrieve is not set, using default fields fields_to_retrieve = self.default_fields_to_retrieve if config.has_option(section, 'fields_to_retrieve'): fields_to_retrieve = [ field.strip() for field in config.get( section, 'fields_to_retrieve').split(',') ] fields_to_retrieve = tuple(fields_to_retrieve) # default section values section_values = { 'var_prefix': 'livestatus_', 'host_filter': None, 'host_field': 'name', 'group_field': 'groups' } for key, value in section_values.items(): if config.has_option(section, key): section_values[key] = config.get(section, key).strip() # Retrieving livestatus string connection livestatus_uri = config.get(section, 'livestatus_uri') backend_definition = None # Local unix socket unix_match = re.match('unix:(.*)', livestatus_uri) if unix_match is not None: backend_definition = {'connection': unix_match.group(1)} # Remote tcp connection tcp_match = re.match('tcp:(.*):([^:]*)', livestatus_uri) if tcp_match is not None: backend_definition = { 'connection': (tcp_match.group(1), int(tcp_match.group(2))) } # No valid livestatus_uri => exiting if backend_definition is None: raise Exception( 'livestatus_uri field is invalid (%s). Expected: unix:/path/to/live or tcp:host:port' % livestatus_uri) # Updating backend_definition with current value backend_definition['name'] = section backend_definition['fields'] = fields_to_retrieve for key, value in section_values.items(): backend_definition[key] = value self.backends.append(backend_definition)
def read_settings(self): ''' Reads the settings from the libcloud.ini file ''' config = ConfigParser.SafeConfigParser() libcloud_default_ini_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'libcloud.ini') libcloud_ini_path = os.environ.get('LIBCLOUD_INI_PATH', libcloud_default_ini_path) config.read(libcloud_ini_path) if not config.has_section('driver'): raise ValueError( 'libcloud.ini file must contain a [driver] section') if config.has_option('driver', 'provider'): self.provider = config.get('driver', 'provider') else: raise ValueError('libcloud.ini does not have a provider defined') if config.has_option('driver', 'key'): self.key = config.get('driver', 'key') else: raise ValueError('libcloud.ini does not have a key defined') if config.has_option('driver', 'secret'): self.secret = config.get('driver', 'secret') else: raise ValueError('libcloud.ini does not have a secret defined') if config.has_option('driver', 'host'): self.host = config.get('driver', 'host') if config.has_option('driver', 'secure'): self.secure = config.get('driver', 'secure') if config.has_option('driver', 'verify_ssl_cert'): self.verify_ssl_cert = config.get('driver', 'verify_ssl_cert') if config.has_option('driver', 'port'): self.port = config.get('driver', 'port') if config.has_option('driver', 'path'): self.path = config.get('driver', 'path') if config.has_option('driver', 'api_version'): self.api_version = config.get('driver', 'api_version') Driver = get_driver(getattr(Provider, self.provider)) self.conn = Driver(key=self.key, secret=self.secret, secure=self.secure, host=self.host, path=self.path) # Cache related cache_path = config.get('cache', 'cache_path') self.cache_path_cache = cache_path + "/ansible-libcloud.cache" self.cache_path_index = cache_path + "/ansible-libcloud.index" self.cache_max_age = config.getint('cache', 'cache_max_age')
def __init__(self, guests_only=None): self.config = configparser.SafeConfigParser() if os.environ.get('VMWARE_INI', ''): config_files = [os.environ['VMWARE_INI']] else: config_files = [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini'] for config_file in config_files: if os.path.exists(config_file): self.config.read(config_file) break # Retrieve only guest VMs, or include host systems? if guests_only is not None: self.guests_only = guests_only elif self.config.has_option('defaults', 'guests_only'): self.guests_only = self.config.getboolean('defaults', 'guests_only') else: self.guests_only = True # Read authentication information from VMware environment variables # (if set), otherwise from INI file. auth_host = os.environ.get('VMWARE_HOST') if not auth_host and self.config.has_option('auth', 'host'): auth_host = self.config.get('auth', 'host') auth_user = os.environ.get('VMWARE_USER') if not auth_user and self.config.has_option('auth', 'user'): auth_user = self.config.get('auth', 'user') auth_password = os.environ.get('VMWARE_PASSWORD') if not auth_password and self.config.has_option('auth', 'password'): auth_password = self.config.get('auth', 'password') sslcheck = os.environ.get('VMWARE_SSLCHECK') if not sslcheck and self.config.has_option('auth', 'sslcheck'): sslcheck = self.config.get('auth', 'sslcheck') if not sslcheck: sslcheck = True else: if sslcheck.lower() in ['no', 'false']: sslcheck = False else: sslcheck = True # Limit the clusters being scanned self.filter_clusters = os.environ.get('VMWARE_CLUSTERS') if not self.filter_clusters and self.config.has_option('defaults', 'clusters'): self.filter_clusters = self.config.get('defaults', 'clusters') if self.filter_clusters: self.filter_clusters = [x.strip() for x in self.filter_clusters.split(',') if x.strip()] # Override certificate checks if not sslcheck: if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context # Create the VMware client connection. self.client = Client(auth_host, auth_user, auth_password)
def read_settings(self): """Reads the settings from the .ini file.""" config = ConfigParser.SafeConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/linode.ini') # Cache related cache_path = config.get('linode', 'cache_path') self.cache_path_cache = cache_path + "/ansible-linode.cache" self.cache_path_index = cache_path + "/ansible-linode.index" self.cache_max_age = config.getint('linode', 'cache_max_age') self.use_public_ip = config.getboolean('linode', 'use_public_ip')
def get_from_rhc_config(variable): global configparser CONF_FILE = os.path.expanduser('~/.openshift/express.conf') if os.path.exists(CONF_FILE): if not configparser: ini_str = '[root]\n' + open(CONF_FILE, 'r').read() configparser = ConfigParser.SafeConfigParser() configparser.readfp(StringIO.StringIO(ini_str)) try: return configparser.get('root', variable) except ConfigParser.NoOptionError: return None
def read_config(self): config = configparser.SafeConfigParser() conf_path = './spacewalk.ini' if not os.path.exists(conf_path): conf_path = '/etc/ansible/custom/spacewalk.ini' if os.path.exists(conf_path): config.read(conf_path) # URL if config.has_option('spacewalk', 'URL'): self.spacewalk_url = config.get('spacewalk', 'URL') # login if config.has_option('spacewalk', 'login'): self.spacewalk_login = config.get('spacewalk', 'login') # password if config.has_option('spacewalk', 'password'): self.spacewalk_password = config.get('spacewalk', 'password')
def read_settings(self): config = configparser.SafeConfigParser() conf_path = './one.ini' if not os.path.exists(conf_path): conf_path = os.path.dirname(os.path.realpath(__file__)) + '/one.ini' if os.path.exists(conf_path): config.read(conf_path) # server configuration if config.has_option('one', 'server'): self.one_server = config.get('one', 'server') # login information if config.has_option('one', 'username'): self.one_username = config.get('one', 'username') if config.has_option('one', 'password'): self.one_password = config.get('one', 'password') # ssl valid-certs if config.has_option('one', 'validate_certs'): if config.get('one', 'validate_certs') in ['false', 'False', False]: self.validate_certs = False
def read_settings(self): ''' Reads the settings from the mdt.ini file ''' config = configparser.SafeConfigParser() config.read('mdt.ini') # MDT Server and instance and database self.mdt_server = config.get('mdt', 'server') self.mdt_instance = config.get('mdt', 'instance') self.mdt_database = config.get('mdt', 'database') # MDT Login credentials if config.has_option('mdt', 'user'): self.mdt_user = config.get('mdt', 'user') if config.has_option('mdt', 'password'): self.mdt_password = config.get('mdt', 'password') # Group name in Tower if config.has_option('tower', 'groupname'): self.mdt_groupname = config.get('tower', 'groupname')
def read_settings(self): """ Reads the settings from the cobbler.ini file """ if(self.ignore_settings): return config = ConfigParser.SafeConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/cobbler.ini') self.cobbler_host = config.get('cobbler', 'host') self.cobbler_username = None self.cobbler_password = None if config.has_option('cobbler', 'username'): self.cobbler_username = config.get('cobbler', 'username') if config.has_option('cobbler', 'password'): self.cobbler_password = config.get('cobbler', 'password') # Cache related cache_path = config.get('cobbler', 'cache_path') self.cache_path_cache = cache_path + "/ansible-cobbler.cache" self.cache_path_inventory = cache_path + "/ansible-cobbler.index" self.cache_max_age = config.getint('cobbler', 'cache_max_age')
def read_settings(self): ''' Reads the settings from the consul_io.ini file (or consul.ini for backwards compatibility)''' config = configparser.SafeConfigParser() if os.path.isfile( os.path.dirname(os.path.realpath(__file__)) + '/consul_io.ini'): config.read( os.path.dirname(os.path.realpath(__file__)) + '/consul_io.ini') else: config.read( os.path.dirname(os.path.realpath(__file__)) + '/consul.ini') config_options = [ 'host', 'token', 'datacenter', 'servers_suffix', 'tags', 'kv_metadata', 'kv_groups', 'availability', 'unavailable_suffix', 'available_suffix', 'url', 'domain', 'suffixes', 'bulk_load' ] for option in config_options: value = None if config.has_option('consul', option): value = config.get('consul', option).lower() setattr(self, option, value)
def read_settings(self): """ Reads the settings from the collins.ini file """ config_loc = os.getenv( 'COLLINS_CONFIG', os.path.dirname(os.path.realpath(__file__)) + '/collins.ini') config = ConfigParser.SafeConfigParser() config.read( os.path.dirname(os.path.realpath(__file__)) + '/collins.ini') self.collins_host = config.get('collins', 'host') self.collins_username = os.getenv('COLLINS_USERNAME', config.get('collins', 'username')) self.collins_password = os.getenv('COLLINS_PASSWORD', config.get('collins', 'password')) self.collins_asset_type = os.getenv( 'COLLINS_ASSET_TYPE', config.get('collins', 'asset_type')) self.collins_timeout_secs = config.getint('collins', 'timeout_secs') self.collins_max_retries = config.getint('collins', 'max_retries') self.results_per_query = config.getint('collins', 'results_per_query') self.ip_address_index = config.getint('collins', 'ip_address_index') self.query_remote_dcs = config.getboolean('collins', 'query_remote_dcs') self.prefer_hostnames = config.getboolean('collins', 'prefer_hostnames') cache_path = config.get('collins', 'cache_path') self.cache_path_cache = cache_path + \ '/ansible-collins-%s.cache' % self.collins_asset_type self.cache_path_inventory = cache_path + \ '/ansible-collins-%s.index' % self.collins_asset_type self.cache_max_age = config.getint('collins', 'cache_max_age') log_path = config.get('collins', 'log_path') self.log_location = log_path + '/ansible-collins.log'
def main(): """ read settings from proxmox.ini file """ config = ConfigParser.SafeConfigParser() config.read(os.path.dirname(os.path.realpath(__file__)) + '/proxmox.ini') proxmox_host = config.get('proxmox', 'host') proxmox_url = 'https://{host}:8006/'.format(host=proxmox_host) proxmox_username = config.get('proxmox', 'username') proxmox_password = config.get('proxmox', 'password') proxmox_validate_certs = config.getboolean('proxmox', 'validate_certs') parser = OptionParser(usage='%prog [options] --list | --host HOSTNAME') parser.add_option('--list', action="store_true", default=False, dest="list") parser.add_option('--host', dest="host") parser.add_option('--url', default=proxmox_url, dest='url') parser.add_option('--username', default=proxmox_username, dest='username') parser.add_option('--password', default=proxmox_password, dest='password') parser.add_option('--pretty', action="store_true", default=False, dest='pretty') parser.add_option('--no-validate-certs', default=proxmox_validate_certs, dest='validatecerts') (options, args) = parser.parse_args() if options.list: data = main_list(options) elif options.host: data = main_host(options) else: parser.print_help() sys.exit(1) indent = None if options.pretty: indent = 2 print(json.dumps(data, indent=indent))
def read_settings(self): ''' Reads the settings from the vmware_inventory.ini file ''' scriptbasename = __file__ scriptbasename = os.path.basename(scriptbasename) scriptbasename = scriptbasename.replace('.py', '') defaults = { 'vmware': { 'server': '', 'port': 443, 'username': '', 'password': '', 'validate_certs': True, 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename), 'cache_name': 'ansible-vmware', 'cache_path': '~/.ansible/tmp', 'cache_max_age': 3600, 'max_object_level': 1, 'skip_keys': 'declaredalarmstate,' 'disabledmethod,' 'dynamicproperty,' 'dynamictype,' 'environmentbrowser,' 'managedby,' 'parent,' 'childtype,' 'resourceconfig', 'alias_pattern': '{{ config.name + "_" + config.uuid }}', 'host_pattern': '{{ guest.ipaddress }}', 'host_filters': '{{ runtime.powerstate == "poweredOn" }}', 'groupby_patterns': '{{ guest.guestid }},{{ "templates" if config.template else "guests"}}', 'lower_var_keys': True, 'custom_field_group_prefix': 'vmware_tag_', 'groupby_custom_field_excludes': '', 'groupby_custom_field': False } } if PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() # where is the config? vmware_ini_path = os.environ.get('VMWARE_INI_PATH', defaults['vmware']['ini_path']) vmware_ini_path = os.path.expanduser( os.path.expandvars(vmware_ini_path)) config.read(vmware_ini_path) if 'vmware' not in config.sections(): config.add_section('vmware') # apply defaults for k, v in defaults['vmware'].items(): if not config.has_option('vmware', k): config.set('vmware', k, str(v)) # where is the cache? self.cache_dir = os.path.expanduser(config.get('vmware', 'cache_path')) if self.cache_dir and not os.path.exists(self.cache_dir): os.makedirs(self.cache_dir) # set the cache filename and max age cache_name = config.get('vmware', 'cache_name') self.cache_path_cache = self.cache_dir + "/%s.cache" % cache_name self.debugl('cache path is %s' % self.cache_path_cache) self.cache_max_age = int(config.getint('vmware', 'cache_max_age')) # mark the connection info self.server = os.environ.get('VMWARE_SERVER', config.get('vmware', 'server')) self.debugl('server is %s' % self.server) self.port = int( os.environ.get('VMWARE_PORT', config.get('vmware', 'port'))) self.username = os.environ.get('VMWARE_USERNAME', config.get('vmware', 'username')) self.debugl('username is %s' % self.username) self.password = os.environ.get( 'VMWARE_PASSWORD', config.get('vmware', 'password', raw=True)) self.validate_certs = os.environ.get( 'VMWARE_VALIDATE_CERTS', config.get('vmware', 'validate_certs')) if self.validate_certs in ['no', 'false', 'False', False]: self.validate_certs = False self.debugl('cert validation is %s' % self.validate_certs) # behavior control self.maxlevel = int(config.get('vmware', 'max_object_level')) self.debugl('max object level is %s' % self.maxlevel) self.lowerkeys = config.get('vmware', 'lower_var_keys') if type(self.lowerkeys) != bool: if str(self.lowerkeys).lower() in ['yes', 'true', '1']: self.lowerkeys = True else: self.lowerkeys = False self.debugl('lower keys is %s' % self.lowerkeys) self.skip_keys = list(config.get('vmware', 'skip_keys').split(',')) self.debugl('skip keys is %s' % self.skip_keys) temp_host_filters = list( config.get('vmware', 'host_filters').split('}},')) for host_filter in temp_host_filters: host_filter = host_filter.rstrip() if host_filter != "": if not host_filter.endswith("}}"): host_filter += "}}" self.host_filters.append(host_filter) self.debugl('host filters are %s' % self.host_filters) temp_groupby_patterns = list( config.get('vmware', 'groupby_patterns').split('}},')) for groupby_pattern in temp_groupby_patterns: groupby_pattern = groupby_pattern.rstrip() if groupby_pattern != "": if not groupby_pattern.endswith("}}"): groupby_pattern += "}}" self.groupby_patterns.append(groupby_pattern) self.debugl('groupby patterns are %s' % self.groupby_patterns) temp_groupby_custom_field_excludes = config.get( 'vmware', 'groupby_custom_field_excludes') self.groupby_custom_field_excludes = [ x.strip('"') for x in [ y.strip("'") for y in temp_groupby_custom_field_excludes.split(",") ] ] self.debugl('groupby exclude strings are %s' % self.groupby_custom_field_excludes) # Special feature to disable the brute force serialization of the # virtual machine objects. The key name for these properties does not # matter because the values are just items for a larger list. if config.has_section('properties'): self.guest_props = [] for prop in config.items('properties'): self.guest_props.append(prop[1]) # save the config self.config = config
parser.add_option('--host', default=None, dest="host", help="Generate additional host specific details for given host for Ansible") parser.add_option('-H', '--human', dest="human", default=False, action="store_true", help="Produce a friendlier version of either server list or host detail") parser.add_option('-o', '--org', default=None, dest="org_number", help="Limit to spacewalk organization number") parser.add_option('-p', default=False, dest="prefix_org_name", action="store_true", help="Prefix the group name with the organization number") (options, args) = parser.parse_args() # read spacewalk.ini if present # ------------------------------ if os.path.exists(INI_FILE): config = ConfigParser.SafeConfigParser() config.read(INI_FILE) if config.has_option('spacewalk', 'cache_age'): CACHE_AGE = config.get('spacewalk', 'cache_age') if not options.org_number and config.has_option('spacewalk', 'org_number'): options.org_number = config.get('spacewalk', 'org_number') if not options.prefix_org_name and config.has_option('spacewalk', 'prefix_org_name'): options.prefix_org_name = config.getboolean('spacewalk', 'prefix_org_name') # Generate dictionary for mapping group_id to org_id # ------------------------------ org_groups = {} try: for group in spacewalk_report('system-groups'): org_groups[group['spacewalk_group_id']] = group['spacewalk_org_id']
inv = get_cache('scaleway_ansible_inventory.json', config) else: inv = generate_inv_from_api(config) save_cache(inv, config) return json.dumps(inv) if __name__ == '__main__': inventory = {} # Read config if six.PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() for configfilename in [ os.path.abspath(sys.argv[0]).rsplit('.py')[0] + '.ini', 'scaleway.ini' ]: if os.path.exists(configfilename): config.read(configfilename) break if cache_available(config): inventory = get_cache('scaleway_ansible_inventory.json', config) else: inventory = get_inventory(config) # return to ansible sys.stdout.write(str(inventory))
def read_settings(self): ''' Reads the settings from the packet_net.ini file ''' if six.PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() _ini_path_raw = os.environ.get('PACKET_NET_INI_PATH') if _ini_path_raw: packet_ini_path = os.path.expanduser( os.path.expandvars(_ini_path_raw)) else: packet_ini_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'packet_net.ini') config.read(packet_ini_path) # items per page self.items_per_page = 999 if config.has_option(ini_section, 'items_per_page'): config.get(ini_section, 'items_per_page') # Instance states to be gathered in inventory. Default is all of them. packet_valid_device_states = [ 'active', 'inactive', 'queued', 'provisioning' ] self.packet_device_states = [] if config.has_option(ini_section, 'device_states'): for device_state in config.get(ini_section, 'device_states').split(','): device_state = device_state.strip() if device_state not in packet_valid_device_states: continue self.packet_device_states.append(device_state) else: self.packet_device_states = packet_valid_device_states # Cache related cache_dir = os.path.expanduser(config.get(ini_section, 'cache_path')) if not os.path.exists(cache_dir): os.makedirs(cache_dir) self.cache_path_cache = cache_dir + "/ansible-packet.cache" self.cache_path_index = cache_dir + "/ansible-packet.index" self.cache_max_age = config.getint(ini_section, 'cache_max_age') # Configure nested groups instead of flat namespace. if config.has_option(ini_section, 'nested_groups'): self.nested_groups = config.getboolean(ini_section, 'nested_groups') else: self.nested_groups = False # Replace dash or not in group names if config.has_option(ini_section, 'replace_dash_in_groups'): self.replace_dash_in_groups = config.getboolean( ini_section, 'replace_dash_in_groups') else: self.replace_dash_in_groups = True # Configure which groups should be created. group_by_options = [ 'group_by_device_id', 'group_by_hostname', 'group_by_facility', 'group_by_project', 'group_by_operating_system', 'group_by_plan_type', 'group_by_tags', 'group_by_tag_none', ] for option in group_by_options: if config.has_option(ini_section, option): setattr(self, option, config.getboolean(ini_section, option)) else: setattr(self, option, True) # Do we need to just include hosts that match a pattern? try: pattern_include = config.get(ini_section, 'pattern_include') if pattern_include and len(pattern_include) > 0: self.pattern_include = re.compile(pattern_include) else: self.pattern_include = None except configparser.NoOptionError: self.pattern_include = None # Do we need to exclude hosts that match a pattern? try: pattern_exclude = config.get(ini_section, 'pattern_exclude') if pattern_exclude and len(pattern_exclude) > 0: self.pattern_exclude = re.compile(pattern_exclude) else: self.pattern_exclude = None except configparser.NoOptionError: self.pattern_exclude = None # Projects self.projects = [] configProjects = config.get(ini_section, 'projects') configProjects_exclude = config.get(ini_section, 'projects_exclude') if (configProjects == 'all'): for projectInfo in self.get_projects(): if projectInfo.name not in configProjects_exclude: self.projects.append(projectInfo.name) else: self.projects = configProjects.split(",")
def get_config(self): """ Reads the settings from the gce.ini file. Populates a SafeConfigParser object with defaults and attempts to read an .ini-style configuration from the filename specified in GCE_INI_PATH. If the environment variable is not present, the filename defaults to gce.ini in the current working directory. """ gce_ini_default_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "gce.ini") gce_ini_path = os.environ.get('GCE_INI_PATH', gce_ini_default_path) # Create a ConfigParser. # This provides empty defaults to each key, so that environment # variable configuration (as opposed to INI configuration) is able # to work. config = configparser.SafeConfigParser( defaults={ 'gce_service_account_email_address': '', 'gce_service_account_pem_file_path': '', 'gce_project_id': '', 'gce_zone': '', 'libcloud_secrets': '', 'instance_tags': '', 'inventory_ip_type': '', 'cache_path': '~/.ansible/tmp', 'cache_max_age': '300' }) if 'gce' not in config.sections(): config.add_section('gce') if 'inventory' not in config.sections(): config.add_section('inventory') if 'cache' not in config.sections(): config.add_section('cache') config.read(gce_ini_path) ######### # Section added for processing ini settings ######### # Set the instance_states filter based on config file options self.instance_states = [] if config.has_option('gce', 'instance_states'): states = config.get('gce', 'instance_states') # Ignore if instance_states is an empty string. if states: self.instance_states = states.split(',') # Set the instance_tags filter, env var overrides config from file # and cli param overrides all if self.args.instance_tags: self.instance_tags = self.args.instance_tags else: self.instance_tags = os.environ.get( 'GCE_INSTANCE_TAGS', config.get('gce', 'instance_tags')) if self.instance_tags: self.instance_tags = self.instance_tags.split(',') # Caching cache_path = config.get('cache', 'cache_path') cache_max_age = config.getint('cache', 'cache_max_age') # TOOD(supertom): support project-specific caches cache_name = 'ansible-gce.cache' self.cache = CloudInventoryCache(cache_path=cache_path, cache_max_age=cache_max_age, cache_name=cache_name) return config
def read_settings(self): """ Reads the settings from the cloudforms.ini file """ config = ConfigParser.SafeConfigParser() config_paths = [ os.path.dirname(os.path.realpath(__file__)) + '/cloudforms.ini', "/etc/ansible/cloudforms.ini", ] env_value = os.environ.get('CLOUDFORMS_INI_PATH') if env_value is not None: config_paths.append( os.path.expanduser(os.path.expandvars(env_value))) if self.args.debug: for config_path in config_paths: print("Reading from configuration file [%s]" % config_path) config.read(config_paths) # CloudForms API related if config.has_option('cloudforms', 'url'): self.cloudforms_url = config.get('cloudforms', 'url') else: self.cloudforms_url = None if not self.cloudforms_url: warnings.warn( "No url specified, expected something like 'https://cfme.example.com'" ) if config.has_option('cloudforms', 'username'): self.cloudforms_username = config.get('cloudforms', 'username') else: self.cloudforms_username = None if not self.cloudforms_username: warnings.warn( "No username specified, you need to specify a CloudForms username." ) if config.has_option('cloudforms', 'password'): self.cloudforms_pw = config.get('cloudforms', 'password', raw=True) else: self.cloudforms_pw = None if not self.cloudforms_pw: warnings.warn( "No password specified, you need to specify a password for the CloudForms user." ) if config.has_option('cloudforms', 'ssl_verify'): self.cloudforms_ssl_verify = config.getboolean( 'cloudforms', 'ssl_verify') else: self.cloudforms_ssl_verify = True if config.has_option('cloudforms', 'version'): self.cloudforms_version = config.get('cloudforms', 'version') else: self.cloudforms_version = None if config.has_option('cloudforms', 'limit'): self.cloudforms_limit = config.getint('cloudforms', 'limit') else: self.cloudforms_limit = 100 if config.has_option('cloudforms', 'purge_actions'): self.cloudforms_purge_actions = config.getboolean( 'cloudforms', 'purge_actions') else: self.cloudforms_purge_actions = True if config.has_option('cloudforms', 'clean_group_keys'): self.cloudforms_clean_group_keys = config.getboolean( 'cloudforms', 'clean_group_keys') else: self.cloudforms_clean_group_keys = True if config.has_option('cloudforms', 'nest_tags'): self.cloudforms_nest_tags = config.getboolean( 'cloudforms', 'nest_tags') else: self.cloudforms_nest_tags = False if config.has_option('cloudforms', 'suffix'): self.cloudforms_suffix = config.get('cloudforms', 'suffix') if self.cloudforms_suffix[0] != '.': raise AnsibleError( 'Leading fullstop is required for Cloudforms suffix') else: self.cloudforms_suffix = None if config.has_option('cloudforms', 'prefer_ipv4'): self.cloudforms_prefer_ipv4 = config.getboolean( 'cloudforms', 'prefer_ipv4') else: self.cloudforms_prefer_ipv4 = False # Ansible related try: group_patterns = config.get('ansible', 'group_patterns') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): group_patterns = "[]" self.group_patterns = eval(group_patterns) # Cache related try: cache_path = os.path.expanduser(config.get('cache', 'path')) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): cache_path = '.' (script, ext) = os.path.splitext(os.path.basename(__file__)) self.cache_path_hosts = cache_path + "/%s.hosts" % script self.cache_path_inventory = cache_path + "/%s.inventory" % script self.cache_max_age = config.getint('cache', 'max_age') if self.args.debug: print("CloudForms settings:") print("cloudforms_url = %s" % self.cloudforms_url) print("cloudforms_username = %s" % self.cloudforms_username) print("cloudforms_pw = %s" % self.cloudforms_pw) print("cloudforms_ssl_verify = %s" % self.cloudforms_ssl_verify) print("cloudforms_version = %s" % self.cloudforms_version) print("cloudforms_limit = %s" % self.cloudforms_limit) print("cloudforms_purge_actions = %s" % self.cloudforms_purge_actions) print("Cache settings:") print("cache_max_age = %s" % self.cache_max_age) print("cache_path_hosts = %s" % self.cache_path_hosts) print("cache_path_inventory = %s" % self.cache_path_inventory)
def read_settings(self): config = configparser.SafeConfigParser() config.read( os.path.dirname(os.path.realpath(__file__)) + '/nagios_ndo.ini') if config.has_option('ndo', 'database_uri'): self.ndo_database_uri = config.get('ndo', 'database_uri')
def get_ovirt_driver(): """ Determine the ovirt authorization settings and return a ovirt_sdk driver. :rtype : ovirtsdk.api.API """ kwargs = {} ovirt_ini_default_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "ovirt.ini") ovirt_ini_path = os.environ.get('OVIRT_INI_PATH', ovirt_ini_default_path) # Create a ConfigParser. # This provides empty defaults to each key, so that environment # variable configuration (as opposed to INI configuration) is able # to work. config = ConfigParser.SafeConfigParser(defaults={ 'ovirt_url': '', 'ovirt_username': '', 'ovirt_password': '', 'ovirt_api_secrets': '', }) if 'ovirt' not in config.sections(): config.add_section('ovirt') config.read(ovirt_ini_path) # Attempt to get ovirt params from a configuration file, if one # exists. secrets_path = config.get('ovirt', 'ovirt_api_secrets') secrets_found = False try: # noinspection PyUnresolvedReferences,PyPackageRequirements import secrets kwargs = getattr(secrets, 'OVIRT_KEYWORD_PARAMS', {}) secrets_found = True except ImportError: pass if not secrets_found and secrets_path: if not secrets_path.endswith('secrets.py'): err = "Must specify ovirt_sdk secrets file as /absolute/path/to/secrets.py" print(err) sys.exit(1) sys.path.append(os.path.dirname(secrets_path)) try: # noinspection PyUnresolvedReferences,PyPackageRequirements import secrets kwargs = getattr(secrets, 'OVIRT_KEYWORD_PARAMS', {}) except ImportError: pass if not secrets_found: kwargs = { 'url': config.get('ovirt', 'ovirt_url'), 'username': config.get('ovirt', 'ovirt_username'), 'password': config.get('ovirt', 'ovirt_password'), } # If the appropriate environment variables are set, they override # other configuration; process those into our args and kwargs. kwargs['url'] = os.environ.get('OVIRT_URL', kwargs['url']) kwargs['username'] = next(val for val in [os.environ.get('OVIRT_EMAIL'), os.environ.get('OVIRT_USERNAME'), kwargs['username']] if val is not None) kwargs['password'] = next(val for val in [os.environ.get('OVIRT_PASS'), os.environ.get('OVIRT_PASSWORD'), kwargs['password']] if val is not None) # Retrieve and return the ovirt driver. return API(insecure=True, **kwargs)
def read_settings(self): """Reads the settings from the foreman.ini file""" config = ConfigParser.SafeConfigParser() config.read(self.config_paths) # Foreman API related try: self.foreman_url = config.get('foreman', 'url') self.foreman_user = config.get('foreman', 'user') self.foreman_pw = config.get('foreman', 'password', raw=True) self.foreman_ssl_verify = config.getboolean('foreman', 'ssl_verify') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e: print("Error parsing configuration: %s" % e, file=sys.stderr) return False # Ansible related try: group_patterns = config.get('ansible', 'group_patterns') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): group_patterns = "[]" self.group_patterns = json.loads(group_patterns) try: self.group_prefix = config.get('ansible', 'group_prefix') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.group_prefix = "foreman_" try: self.want_facts = config.getboolean('ansible', 'want_facts') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.want_facts = True try: self.want_hostcollections = config.getboolean('ansible', 'want_hostcollections') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.want_hostcollections = False try: self.want_ansible_ssh_host = config.getboolean('ansible', 'want_ansible_ssh_host') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.want_ansible_ssh_host = False # Do we want parameters to be interpreted if possible as JSON? (no by default) try: self.rich_params = config.getboolean('ansible', 'rich_params') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.rich_params = False try: self.host_filters = config.get('foreman', 'host_filters') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.host_filters = None # Cache related try: cache_path = os.path.expanduser(config.get('cache', 'path')) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): cache_path = '.' (script, ext) = os.path.splitext(os.path.basename(__file__)) self.cache_path_cache = cache_path + "/%s.cache" % script self.cache_path_inventory = cache_path + "/%s.index" % script self.cache_path_params = cache_path + "/%s.params" % script self.cache_path_facts = cache_path + "/%s.facts" % script self.cache_path_hostcollections = cache_path + "/%s.hostcollections" % script try: self.cache_max_age = config.getint('cache', 'max_age') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.cache_max_age = 60 try: self.scan_new_hosts = config.getboolean('cache', 'scan_new_hosts') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.scan_new_hosts = False return True