def fetch_objects(self, connections): if connections: if not isinstance(connections, list): raise K8sInventoryException( "Expecting connections to be a list.") for connection in connections: if not isinstance(connection, dict): raise K8sInventoryException( "Expecting connection to be a dictionary.") client = get_api_client(**connection) name = connection.get( "name", self.get_default_host_name(client.configuration.host)) if connection.get("namespaces"): namespaces = connection["namespaces"] else: namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_pods_for_namespace(client, name, namespace) self.get_services_for_namespace(client, name, namespace) else: client = get_api_client() name = self.get_default_host_name(client.configuration.host) namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_pods_for_namespace(client, name, namespace) self.get_services_for_namespace(client, name, namespace)
def execute_module(module): from ansible_collections.kubernetes.core.plugins.module_utils.common import ( K8sAnsibleMixin, get_api_client, ) k8s_ansible_mixin = K8sAnsibleMixin(module, pyyaml_required=False) k8s_ansible_mixin.check_library_version() k8s_ansible_mixin.module = module k8s_ansible_mixin.argspec = module.argument_spec k8s_ansible_mixin.params = k8s_ansible_mixin.module.params k8s_ansible_mixin.fail_json = k8s_ansible_mixin.module.fail_json k8s_ansible_mixin.fail = k8s_ansible_mixin.module.fail_json k8s_ansible_mixin.client = get_api_client(module=module) containers = check_pod(k8s_ansible_mixin, module) if len(containers) > 1 and module.params.get("container") is None: module.fail_json( msg= "Pod contains more than 1 container, option 'container' should be set" ) state = module.params.get("state") if state == "to_pod": k8s_copy = K8SCopyToPod(module, k8s_ansible_mixin.client) else: k8s_copy = K8SCopyFromPod(module, k8s_ansible_mixin.client) try: k8s_copy.run() except Exception as e: module.fail_json("Failed to copy object due to: {0}".format( to_native(e)))
def execute_module(module): k8s_ansible_mixin = K8sAnsibleMixin(module, pyyaml_required=False) k8s_ansible_mixin.check_library_version() k8s_ansible_mixin.module = module k8s_ansible_mixin.argspec = module.argument_spec k8s_ansible_mixin.params = k8s_ansible_mixin.module.params k8s_ansible_mixin.fail_json = k8s_ansible_mixin.module.fail_json k8s_ansible_mixin.fail = k8s_ansible_mixin.module.fail_json k8s_ansible_mixin.client = get_api_client(module=module) containers = check_pod(k8s_ansible_mixin, module) if len(containers) > 1 and module.params.get('container') is None: module.fail_json( msg= "Pod contains more than 1 container, option 'container' should be set" ) try: load_class = {'to_pod': K8SCopyToPod, 'from_pod': K8SCopyFromPod} state = module.params.get('state') k8s_copy = load_class.get(state)(module, k8s_ansible_mixin.client) k8s_copy.run() except Exception as e: module.fail_json("Failed to copy object due to: {0}".format( to_native(e)))
def __init__(self, module): from ansible_collections.kubernetes.core.plugins.module_utils.common import ( K8sAnsibleMixin, get_api_client) self._module = module self._k8s_ansible_mixin = K8sAnsibleMixin(module) self._k8s_ansible_mixin.client = get_api_client(module=self._module) self._k8s_ansible_mixin.module = self._module self._k8s_ansible_mixin.argspec = self._module.argument_spec self._k8s_ansible_mixin.check_mode = self._module.check_mode self._k8s_ansible_mixin.params = self._module.params self._k8s_ansible_mixin.fail_json = self._module.fail_json self._k8s_ansible_mixin.fail = self._module.fail_json self._k8s_ansible_mixin.exit_json = self._module.exit_json self._k8s_ansible_mixin.warn = self._module.warn self._k8s_ansible_mixin.warnings = [] self._api_instance = core_v1_api.CoreV1Api( self._k8s_ansible_mixin.client.client) self._k8s_ansible_mixin.check_library_version() # delete options self._drain_options = module.params.get('delete_options', {}) self._delete_options = None if self._drain_options.get('terminate_grace_period'): self._delete_options = {} self._delete_options.update({'apiVersion': 'v1'}) self._delete_options.update({'kind': 'DeleteOptions'}) self._delete_options.update({ 'gracePeriodSeconds': self._drain_options.get('terminate_grace_period') }) self._changed = False
def main(): module = AnsibleModule(argument_spec=argspec(), supports_check_mode=True) from ansible_collections.kubernetes.core.plugins.module_utils.common import ( K8sAnsibleMixin, get_api_client) k8s_ansible_mixin = K8sAnsibleMixin(module) k8s_ansible_mixin.client = get_api_client(module=module) execute_module(module, k8s_ansible_mixin)
def main(): module = AnsibleModule(argument_spec=argspec(), supports_check_mode=True) if not HAS_K8S: module.fail_json(msg=missing_required_lib('kubernetes'), exception=K8S_IMP_EXC, error=to_native(K8S_IMP_ERR)) from ansible_collections.kubernetes.core.plugins.module_utils.common import get_api_client execute_module(module, client=get_api_client(module=module))
def main(): args = copy.deepcopy(AUTH_ARG_SPEC) args.update(copy.deepcopy(WAIT_ARG_SPEC)) args.update(JSON_PATCH_ARGS) module = AnsibleModule(argument_spec=args, supports_check_mode=True) k8s_module = K8sAnsibleMixin(module) k8s_module.params = module.params k8s_module.check_library_version() client = get_api_client(module) k8s_module.client = client execute_module(k8s_module, module)
def main(): mutually_exclusive = [ ('resource_definition', 'src'), ] module = AnsibleModule(argument_spec=argspec(), mutually_exclusive=mutually_exclusive, supports_check_mode=True) from ansible_collections.kubernetes.core.plugins.module_utils.common import ( K8sAnsibleMixin, get_api_client) k8s_ansible_mixin = K8sAnsibleMixin(module) k8s_ansible_mixin.client = get_api_client(module=module) execute_module(module, k8s_ansible_mixin)
def run(self, terms, variables=None, **kwargs): self.params = kwargs self.client = get_api_client(**kwargs) cluster_info = kwargs.get("cluster_info") if cluster_info == "version": return [self.client.version] if cluster_info == "api_groups": if isinstance(self.client.resources.api_groups, KeysView): return [list(self.client.resources.api_groups)] return [self.client.resources.api_groups] self.kind = kwargs.get("kind") self.name = kwargs.get("resource_name") self.namespace = kwargs.get("namespace") self.api_version = kwargs.get("api_version", "v1") self.label_selector = kwargs.get("label_selector") self.field_selector = kwargs.get("field_selector") self.include_uninitialized = kwargs.get("include_uninitialized", False) resource_definition = kwargs.get("resource_definition") src = kwargs.get("src") if src: resource_definition = self.load_resource_definitions(src)[0] if resource_definition: self.kind = resource_definition.get("kind", self.kind) self.api_version = resource_definition.get("apiVersion", self.api_version) self.name = resource_definition.get("metadata", {}).get("name", self.name) self.namespace = resource_definition.get("metadata", {}).get( "namespace", self.namespace) if not self.kind: raise AnsibleError( "Error: no Kind specified. Use the 'kind' parameter, or provide an object YAML configuration " "using the 'resource_definition' parameter.") resource = self.find_resource(self.kind, self.api_version, fail=True) try: k8s_obj = resource.get( name=self.name, namespace=self.namespace, label_selector=self.label_selector, field_selector=self.field_selector, ) except NotFoundError: return [] if self.name: return [k8s_obj.to_dict()] return k8s_obj.to_dict().get("items")
def fetch_objects(self, connections): super(InventoryModule, self).fetch_objects(connections) if connections: if not isinstance(connections, list): raise K8sInventoryException("Expecting connections to be a list.") for connection in connections: client = get_api_client(**connection) name = connection.get('name', self.get_default_host_name(client.configuration.host)) if connection.get('namespaces'): namespaces = connection['namespaces'] else: namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_routes_for_namespace(client, name, namespace) else: client = get_api_client() name = self.get_default_host_name(client.configuration.host) namespaces = self.get_available_namespaces(client) for namespace in namespaces: self.get_routes_for_namespace(client, name, namespace)
def run(self, terms, variables=None, **kwargs): self.params = kwargs self.client = get_api_client() cluster_info = kwargs.get('cluster_info') if cluster_info == 'version': return [self.client.version] if cluster_info == 'api_groups': if isinstance(self.client.resources.api_groups, KeysView): return [list(self.client.resources.api_groups)] return [self.client.resources.api_groups] self.kind = kwargs.get('kind') self.name = kwargs.get('resource_name') self.namespace = kwargs.get('namespace') self.api_version = kwargs.get('api_version', 'v1') self.label_selector = kwargs.get('label_selector') self.field_selector = kwargs.get('field_selector') self.include_uninitialized = kwargs.get('include_uninitialized', False) resource_definition = kwargs.get('resource_definition') src = kwargs.get('src') if src: resource_definition = self.load_resource_definitions(src)[0] if resource_definition: self.kind = resource_definition.get('kind', self.kind) self.api_version = resource_definition.get('apiVersion', self.api_version) self.name = resource_definition.get('metadata', {}).get('name', self.name) self.namespace = resource_definition.get('metadata', {}).get( 'namespace', self.namespace) if not self.kind: raise AnsibleError( "Error: no Kind specified. Use the 'kind' parameter, or provide an object YAML configuration " "using the 'resource_definition' parameter.") resource = self.find_resource(self.kind, self.api_version, fail=True) try: k8s_obj = resource.get(name=self.name, namespace=self.namespace, label_selector=self.label_selector, field_selector=self.field_selector) except NotFoundError: return [] if self.name: return [k8s_obj.to_dict()] return k8s_obj.to_dict().get('items')
def __init__(self, module): self.module = module self.k8s_ansible_mixin = K8sAnsibleMixin(module=self.module) self.k8s_ansible_mixin.client = get_api_client(module=self.module) self.k8s_ansible_mixin.module = self.module self.k8s_ansible_mixin.argspec = self.module.argument_spec self.k8s_ansible_mixin.check_mode = self.module.check_mode self.k8s_ansible_mixin.params = self.module.params self.k8s_ansible_mixin.fail_json = self.module.fail_json self.k8s_ansible_mixin.fail = self.module.fail_json self.k8s_ansible_mixin.exit_json = self.module.exit_json self.k8s_ansible_mixin.warn = self.module.warn self.k8s_ansible_mixin.warnings = [] self.api_instance = core_v1_api.CoreV1Api( self.k8s_ansible_mixin.client.client) self.k8s_ansible_mixin.check_library_version() self.changed = False
def __init__(self, module): self.module = module self.fail_json = self.module.fail_json self.exit_json = self.module.exit_json if not HAS_KUBERNETES_COLLECTION: self.module.fail_json( msg="The kubernetes.core collection must be installed", exception=K8S_COLLECTION_ERROR, error=to_native(k8s_collection_import_exception), ) super(OpenShiftProcess, self).__init__(self.module) self.params = self.module.params self.check_mode = self.module.check_mode self.client = get_api_client(self.module)
def __init__(self, module, k8s_kind=None, *args, **kwargs): self.module = module self.client = get_api_client(module=module) self.check_mode = self.module.check_mode self.params = self.module.params self.fail_json = self.module.fail_json self.fail = self.module.fail_json self.exit_json = self.module.exit_json super(OKDRawModule, self).__init__(module, *args, **kwargs) self.warnings = [] self.kind = k8s_kind or self.params.get('kind') self.api_version = self.params.get('api_version') self.name = self.params.get('name') self.namespace = self.params.get('namespace') self.check_library_version() self.set_resource_definitions(module)
def main(): mutually_exclusive = [ ("resource_definition", "src"), ("merge_type", "apply"), ("template", "resource_definition"), ("template", "src"), ("name", "generate_name"), ] module = AnsibleModule( argument_spec=argspec(), mutually_exclusive=mutually_exclusive, supports_check_mode=True, ) from ansible_collections.kubernetes.core.plugins.module_utils.common import ( K8sAnsibleMixin, get_api_client, ) k8s_ansible_mixin = K8sAnsibleMixin(module) k8s_ansible_mixin.client = get_api_client(module=module) execute_module(module, k8s_ansible_mixin)
def __init__(self, k8s_kind=None, *args, **kwargs): mutually_exclusive = [ ('resource_definition', 'src'), ('merge_type', 'apply'), ('template', 'resource_definition'), ('template', 'src'), ] module = AnsibleModule( argument_spec=self.argspec, mutually_exclusive=mutually_exclusive, supports_check_mode=True, ) self.module = module self.check_mode = self.module.check_mode self.params = self.module.params self.fail_json = self.module.fail_json self.fail = self.module.fail_json self.exit_json = self.module.exit_json if not HAS_KUBERNETES_COLLECTION: self.fail_json( msg="The kubernetes.core collection must be installed", exception=K8S_COLLECTION_ERROR, error=to_native(k8s_collection_import_exception)) super(OKDRawModule, self).__init__(module, *args, **kwargs) self.client = get_api_client(module) self.warnings = [] self.kind = k8s_kind or self.params.get('kind') self.api_version = self.params.get('api_version') self.name = self.params.get('name') self.namespace = self.params.get('namespace') self.check_library_version() self.set_resource_definitions(module)
def __init__(self): self.module = AnsibleModule( argument_spec=self.argspec, supports_check_mode=True, ) self.fail_json = self.module.fail_json if not HAS_KUBERNETES_COLLECTION: self.module.fail_json( msg="The kubernetes.core collection must be installed", exception=K8S_COLLECTION_ERROR, error=to_native(k8s_collection_import_exception)) super(OpenShiftRoute, self).__init__(self.module) self.params = self.module.params # TODO: should probably make it so that at least some of these aren't required for perform_action to work # Or at least explicitly pass them in self.append_hash = False self.apply = False self.check_mode = self.module.check_mode self.warnings = [] self.params['merge_type'] = None self.client = get_api_client(self.module)
def execute_module(self): self.client = get_api_client(self.module) v1_routes = self.find_resource('Route', 'route.openshift.io/v1', fail=True) service_name = self.params.get('service') namespace = self.params['namespace'] termination_type = self.params.get('termination') if termination_type == 'insecure': termination_type = None state = self.params.get('state') if state != 'absent' and not service_name: self.fail_json( "If 'state' is not 'absent' then 'service' must be provided") # We need to do something a little wonky to wait if the user doesn't supply a custom condition custom_wait = self.params.get('wait') and not self.params.get( 'wait_condition') and state != 'absent' if custom_wait: # Don't use default wait logic in perform_action self.params['wait'] = False route_name = self.params.get('name') or service_name labels = self.params.get('labels') hostname = self.params.get('hostname') path = self.params.get('path') wildcard_policy = self.params.get('wildcard_policy') port = self.params.get('port') if termination_type and self.params.get('tls'): tls_ca_cert = self.params['tls'].get('ca_certificate') tls_cert = self.params['tls'].get('certificate') tls_dest_ca_cert = self.params['tls'].get( 'destination_ca_certificate') tls_key = self.params['tls'].get('key') tls_insecure_policy = self.params['tls'].get('insecure_policy') if tls_insecure_policy == 'disallow': tls_insecure_policy = None else: tls_ca_cert = tls_cert = tls_dest_ca_cert = tls_key = tls_insecure_policy = None route = { 'apiVersion': 'route.openshift.io/v1', 'kind': 'Route', 'metadata': { 'name': route_name, 'namespace': namespace, 'labels': labels, }, 'spec': {} } if state != 'absent': route['spec'] = self.build_route_spec( service_name, namespace, port=port, wildcard_policy=wildcard_policy, hostname=hostname, path=path, termination_type=termination_type, tls_insecure_policy=tls_insecure_policy, tls_ca_cert=tls_ca_cert, tls_cert=tls_cert, tls_key=tls_key, tls_dest_ca_cert=tls_dest_ca_cert, ) result = self.perform_action(v1_routes, route) timeout = self.params.get('wait_timeout') sleep = self.params.get('wait_sleep') if custom_wait: success, result['result'], result['duration'] = self._wait_for( v1_routes, route_name, namespace, wait_predicate, sleep, timeout, state) self.module.exit_json(**result)
def execute_module(self): self.client = get_api_client(self.module) v1_templates = self.find_resource('templates', 'template.openshift.io/v1', fail=True) v1_processed_templates = self.find_resource('processedtemplates', 'template.openshift.io/v1', fail=True) name = self.params.get('name') namespace = self.params.get('namespace') namespace_target = self.params.get('namespace_target') definition = self.params.get('resource_definition') src = self.params.get('src') state = self.params.get('state') parameters = self.params.get('parameters') or {} parameter_file = self.params.get('parameter_file') if (name and definition) or (name and src) or (src and definition): self.fail_json( "Only one of src, name, or definition may be provided") if name and not namespace: self.fail_json("namespace is required when name is set") template = None if src or definition: self.set_resource_definitions(self.module) if len(self.resource_definitions) < 1: self.fail_json( 'Unable to load a Template resource from src or resource_definition' ) elif len(self.resource_definitions) > 1: self.fail_json( 'Multiple Template resources found in src or resource_definition, only one Template may be processed at a time' ) template = self.resource_definitions[0] template_namespace = template.get('metadata', {}).get('namespace') namespace = template_namespace or namespace or namespace_target or 'default' elif name and namespace: try: template = v1_templates.get(name=name, namespace=namespace).to_dict() except DynamicApiError as exc: self.fail_json( msg= "Failed to retrieve Template with name '{0}' in namespace '{1}': {2}" .format(name, namespace, exc.body), error=exc.status, status=exc.status, reason=exc.reason) except Exception as exc: self.module.fail_json( msg= "Failed to retrieve Template with name '{0}' in namespace '{1}': {2}" .format(name, namespace, to_native(exc)), error='', status='', reason='') else: self.fail_json( "One of resource_definition, src, or name and namespace must be provided" ) if parameter_file: parameters = self.parse_dotenv_and_merge(parameters, parameter_file) for k, v in parameters.items(): template = self.update_template_param(template, k, v) result = {'changed': False} try: response = v1_processed_templates.create( body=template, namespace=namespace).to_dict() except DynamicApiError as exc: self.fail_json( msg="Server failed to render the Template: {0}".format( exc.body), error=exc.status, status=exc.status, reason=exc.reason) except Exception as exc: self.module.fail_json( msg="Server failed to render the Template: {0}".format( to_native(exc)), error='', status='', reason='') result['message'] = "" if "message" in response: result['message'] = response['message'] result['resources'] = response['objects'] if state != 'rendered': self.resource_definitions = response['objects'] self.kind = self.api_version = self.name = None self.namespace = self.params.get('namespace_target') self.append_hash = False self.apply = False self.params['validate'] = None self.params['merge_type'] = None super(OpenShiftProcess, self).execute_module() self.module.exit_json(**result)
def main(): module = AnsibleModule(argument_spec=argspec(), supports_check_mode=True) from ansible_collections.kubernetes.core.plugins.module_utils.common import get_api_client execute_module(module, client=get_api_client(module=module))