{"id":22281811,"url":"https://github.com/manageiq/kubeclient","last_synced_at":"2025-05-15T09:04:50.320Z","repository":{"id":25203286,"uuid":"28627094","full_name":"ManageIQ/kubeclient","owner":"ManageIQ","description":"A Ruby client for Kubernetes REST API","archived":false,"fork":false,"pushed_at":"2025-03-11T22:17:43.000Z","size":1117,"stargazers_count":423,"open_issues_count":77,"forks_count":168,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-04-03T04:09:26.390Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ManageIQ.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-12-30T10:38:54.000Z","updated_at":"2025-03-23T13:00:20.000Z","dependencies_parsed_at":"2024-04-02T18:52:04.457Z","dependency_job_id":"f43006d7-2cf3-4442-bd40-d09b84a892d2","html_url":"https://github.com/ManageIQ/kubeclient","commit_stats":null,"previous_names":["abonas/kubeclient"],"tags_count":73,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ManageIQ%2Fkubeclient","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ManageIQ%2Fkubeclient/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ManageIQ%2Fkubeclient/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ManageIQ%2Fkubeclient/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ManageIQ","download_url":"https://codeload.github.com/ManageIQ/kubeclient/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248166865,"owners_count":21058481,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest"],"created_at":"2024-12-03T16:22:20.597Z","updated_at":"2025-04-10T06:20:31.888Z","avatar_url":"https://github.com/ManageIQ.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Kubeclient\n\n[![Gem Version](https://badge.fury.io/rb/kubeclient.svg)](http://badge.fury.io/rb/kubeclient)\n[![Build Status](https://github.com/ManageIQ/kubeclient/actions/workflows/ci.yml/badge.svg)](https://github.com/ManageIQ/kubeclient/actions?branch=master)\n[![Code Climate](https://codeclimate.com/github/ManageIQ/kubeclient.svg)](https://codeclimate.com/github/ManageIQ/kubeclient)\n[![Downloads rate by version](https://img.shields.io/badge/downloads%20rate-by%20version-blue)](https://ui.honeycomb.io/ruby-together/datasets/rubygems.org/result/7mZHKUfmHkj)\n\nA Ruby client for Kubernetes REST api.\nThe client supports GET, POST, PUT, DELETE on all the entities available in kubernetes in both the core and group apis.\nThe client currently supports Kubernetes REST api version v1.\nTo learn more about groups and versions in kubernetes refer to [k8s docs](https://kubernetes.io/docs/api/)\n\n## VULNERABILITY in \u003c= v4.9.2❗\n\nIf you use `Kubeclient::Config`, all gem versions \u003c= v4.9.3 can return incorrect `ssl_options[:verify_ssl]`,\nallowing MITM attacks on your connection and thereby stealing your cluster credentials.\nSee https://github.com/ManageIQ/kubeclient/issues/554 for details and which versions got a fix.\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'kubeclient'\n```\n\nAnd then execute:\n\n```Bash\nbundle\n```\n\nOr install it yourself as:\n\n```Bash\ngem install kubeclient\n```\n\n## Usage\n\nInitialize the client:\n\n```ruby\nclient = Kubeclient::Client.new('http://localhost:8080/api', 'v1')\n```\n\nFor A Group Api:\n\n```ruby\nclient = Kubeclient::Client.new('http://localhost:8080/apis/batch', 'v1')\n```\n\nAnother option is to initialize the client with URI object:\n\n```ruby\nuri = URI::HTTP.build(host: \"somehostname\", port: 8080)\nclient = Kubeclient::Client.new(uri, 'v1')\n```\n\n### SSL\n\nIt is also possible to use https and configure ssl with:\n\n```ruby\nssl_options = {\n  client_cert: OpenSSL::X509::Certificate.new(File.read('/path/to/client.crt')),\n  client_key:  OpenSSL::PKey::RSA.new(File.read('/path/to/client.key')),\n  ca_file:     '/path/to/ca.crt',\n  verify_ssl:  OpenSSL::SSL::VERIFY_PEER\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', ssl_options: ssl_options\n)\n```\n\nAs an alternative to the `ca_file` it's possible to use the `cert_store`:\n\n```ruby\ncert_store = OpenSSL::X509::Store.new\ncert_store.add_cert(OpenSSL::X509::Certificate.new(ca_cert_data))\nssl_options = {\n  cert_store: cert_store,\n  verify_ssl: OpenSSL::SSL::VERIFY_PEER\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', ssl_options: ssl_options\n)\n```\n\nFor testing and development purpose you can disable the ssl check with:\n\n```ruby\nssl_options = { verify_ssl: OpenSSL::SSL::VERIFY_NONE }\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', ssl_options: ssl_options\n)\n```\n\n### Authentication\n\nIf you are using basic authentication or bearer tokens as described\n[here](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/authentication.md)\nthen you can specify one of the following:\n\n```ruby\nauth_options = {\n  username: 'username',\n  password: 'password'\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', auth_options: auth_options\n)\n```\n\nor (fixed token, if it expires it's up to you to create a new `Client` object):\n\n```ruby\nauth_options = {\n  bearer_token: 'MDExMWJkMjItOWY1Ny00OGM5LWJlNDEtMjBiMzgxODkxYzYz'\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', auth_options: auth_options\n)\n```\n\nor (will automatically re-read the token if file is updated):\n\n```ruby\nauth_options = {\n  bearer_token_file: '/path/to/token_file'\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', auth_options: auth_options\n)\n```\n\n### Middleware\n\nThe Faraday HTTP client used by kubeclient allows configuration of custom middlewares. For example, you may want to add instrumentation, or add custom retry options. Kubeclient provides a hook for injecting these custom middlewares into the request/response chain, via `Client#configure_faraday(\u0026block)`. This provides an access point to the `Faraday::Connection` object during initialization. As an example, the following code adds retry options to client requests:\n\n```ruby\nclient = Kubeclient::Client.new('http://localhost:8080/api', 'v1')\nretry_options = { max: 2, interval: 0.05, interval_randomness: 0.5, backoff_factor: 2 }\nclient.configure_faraday { |conn| conn.request(:retry, retry_options) }\n```\n\nFor more examples and documentation, consult the [Faraday docs](https://lostisland.github.io/faraday/).\nNote that certain middlewares (e.g. `:raise_error`) are always included since Kubeclient is dependent on their behaviour to function correctly.\n\n#### Inside a Kubernetes cluster\n\nThe [recommended way to locate the API server](https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#accessing-the-api-from-a-pod) within the pod is with the `kubernetes.default.svc` DNS name, which resolves to a Service IP which in turn will be routed to an API server.\n\nThe recommended way to authenticate to the API server is with a [service account](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/). kube-system associates a pod with a service account and a bearer token for that service account is placed into the filesystem tree of each container in that pod at `/var/run/secrets/kubernetes.io/serviceaccount/token`.\n\nIf available, a certificate bundle is placed into the filesystem tree of each container at `/var/run/secrets/kubernetes.io/serviceaccount/ca.crt`, and should be used to verify the serving certificate of the API server.\n\nFor example:\n\n```ruby\nauth_options = {\n  bearer_token_file: '/var/run/secrets/kubernetes.io/serviceaccount/token'\n}\nssl_options = {}\nif File.exist?(\"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\")\n  ssl_options[:ca_file] = \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\nend\nclient = Kubeclient::Client.new(\n  'https://kubernetes.default.svc',\n  'v1',\n  auth_options: auth_options,\n  ssl_options:  ssl_options\n)\n```\n\nFinally, the default namespace to be used for namespaced API operations is placed in a file at `/var/run/secrets/kubernetes.io/serviceaccount/namespace` in each container. It is recommended that you use this namespace when issuing API commands below.\n\n```ruby\nnamespace = File.read('/var/run/secrets/kubernetes.io/serviceaccount/namespace')\n```\nYou can find information about tokens in [this guide](https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#accessing-the-api-from-a-pod) and in [this reference](http://kubernetes.io/docs/admin/authentication/).\n\n### Non-blocking IO\n\nYou can also use kubeclient with non-blocking sockets such as Celluloid::IO, see [here](https://github.com/httprb/http/wiki/Parallel-requests-with-Celluloid%3A%3AIO)\nfor details. For example:\n\n```ruby\nrequire 'celluloid/io'\nsocket_options = {\n  socket_class: Celluloid::IO::TCPSocket,\n  ssl_socket_class: Celluloid::IO::SSLSocket\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', socket_options: socket_options\n)\n```\n\nThis affects only `.watch_*` sockets, not one-off actions like `.get_*`, `.delete_*` etc.\n\n### Proxies\n\nYou can also use kubeclient with an http proxy server such as tinyproxy. It can be entered as a string or a URI object.\nFor example:\n```ruby\nproxy_uri = URI::HTTP.build(host: \"myproxyhost\", port: 8443)\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', http_proxy_uri: proxy_uri\n)\n```\n\n### Redirects\n\nYou can optionally not allow redirection with kubeclient. For example:\n\n```ruby\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', http_max_redirects: 0\n)\n```\n\n### Timeouts\n\nWatching configures the socket to never time out by default (however, sooner or later all watches terminate).\n\nOne-off actions like `.get_*`, `.delete_*` have a configurable timeout:\n```ruby\ntimeouts = {\n  open: 10,  # unit is seconds\n  read: nil  # nil means never time out\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', timeouts: timeouts\n)\n```\n\nDefault timeouts match `Net::HTTP` and `RestClient`:\n- open is 60 seconds\n- read is 60 seconds.\n\nIf you want ruby-independent behavior, always specify `:open`.\n\n### Errors\n\nIf an error occurs while performing a request to the API server, `Kubeclient::HttpError` will be raised.\n\nThere are also certain case-specific errors that can be raised (which also inherit from `Kubeclient::HttpError`):\n\n- `Kubeclient::ResourceNotFoundError` when attempting to fetch a resource that does not exist or any other situation that results in the API server returning a 404.\n- `Kubeclient::ResourceAlreadyExistsError` when attempting to create a resource that already exists.\n\n### Discovery\n\nDiscovery from the kube-apiserver is done lazily on method calls so it would not change behavior.\n\nIt can also  be done explicitly:\n\n```ruby\nclient = Kubeclient::Client.new('http://localhost:8080/api', 'v1')\nclient.discover\n```\n\nIt is possible to check the status of discovery\n\n```ruby\nunless client.discovered\n  client.discover\nend\n```\n\n### Kubeclient::Config\n\nIf you've been using `kubectl` and have a `.kube/config` file (possibly referencing other files in fields such as `client-certificate`), you can auto-populate a config object using `Kubeclient::Config`:\n\n```ruby\n# assuming $KUBECONFIG is one file, won't merge multiple like kubectl\nconfig = Kubeclient::Config.read(ENV['KUBECONFIG'] || '/path/to/.kube/config')\n```\n\nThis will lookup external files; relative paths will be resolved relative to the file's directory, if config refers to them with relative path.\nThis includes external [`exec:` credential plugins][exec] to be executed.\n\n[exec]: https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins\n\nYou can also construct `Config` directly from nested data. For example if you have JSON or YAML config data in a variable:\n\n```ruby\nconfig = Kubeclient::Config.new(YAML.safe_load(yaml_text), nil)\n# or\nconfig = Kubeclient::Config.new(JSON.parse(json_text), nil)\n```\n\nThe 2nd argument is a base directory for finding external files, if config refers to them with relative path.\nSetting it to `nil` disables file lookups, and `exec:` execution - such configs will raise an exception.  (A config can be self-contained by using inline fields such as `client-certificate-data`.)\n\nTo create a client based on a Config object:\n\n```ruby\n# default context according to `current-context` field:\ncontext = config.context\n# or to use a specific context, by name:\ncontext = config.context('default/192-168-99-100:8443/system:admin')\n\nKubeclient::Client.new(\n  context.api_endpoint,\n  'v1',\n  ssl_options: context.ssl_options,\n  auth_options: context.auth_options\n)\n```\n\n\n#### Amazon EKS Credentials\n\nOn Amazon EKS by default the authentication method is IAM.  When running kubectl a temporary token is generated by shelling out to\nthe aws-iam-authenticator binary which is sent to authenticate the user.\nSee [aws-iam-authenticator](https://github.com/kubernetes-sigs/aws-iam-authenticator).\nTo replicate that functionality, the `Kubeclient::AmazonEksCredentials` class can accept a set of IAM credentials and\ncontains a helper method to generate the authentication token for you.\n\nThis requires a set of gems which are _not_ included in\n`kubeclient` dependencies (`aws-sigv4`) so you should add them to your bundle.\nYou will also require either the `aws-sdk` v2 or `aws-sdk-core` v3 gems to generate the required `Aws:Credentials` object to pass to this method.\n\nTo obtain a token:\n\n```ruby\nrequire 'aws-sdk-core'\n# Use keys\ncredentials = Aws::Credentials.new(access_key, secret_key)\n# Or a profile\ncredentials = Aws::SharedCredentials.new(profile_name: 'default').credentials\n# Or for an STS Assumed Role Credentials or any other credential Provider other than Static Credentials\ncredentials = Aws::AssumeRoleCredentials.new({ client: sts_client, role_arn: role_arn, role_session_name: session_name })\n\n# Kubeclient Auth Options\nauth_options = {\n  bearer_token: Kubeclient::AmazonEksCredentials.token(credentials, eks_cluster_name)\n}\n\nclient = Kubeclient::Client.new(\n  eks_cluster_https_endpoint, 'v1', auth_options: auth_options\n)\n```\n\nNote that this returns a token good for one minute. If your code requires authorization for longer than that, you should plan to\nacquire a new one, see [How to manually renew](#how-to-manually-renew-expired-credentials) section.\n\n#### Google GCP credential plugin\n\nIf kubeconfig file has `user: {auth-provider: {name: gcp, cmd-path: ..., cmd-args: ..., token-key: ...}}`, the command will be executed to obtain a token.\n(Normally this would be a `gcloud config config-helper` command.)\n\nNote that this returns an expiring token. If your code requires authorization for a long time, you should plan to acquire a new one, see [How to manually renew](#how-to-manually-renew-expired-credentials) section.\n\n#### Google's Application Default Credentials\n\nOn Google Compute Engine, Google App Engine, or Google Cloud Functions, as well as `gcloud`-configured systems\nwith [application default credentials](https://developers.google.com/identity/protocols/application-default-credentials),\nkubeclient can use `googleauth` gem to authorize.\n\nThis requires the [`googleauth` gem](https://github.com/google/google-auth-library-ruby) that is _not_ included in\n`kubeclient` dependencies so you should add it to your bundle.\n\nIf you use `Config.context(...).auth_options` and the kubeconfig file has `user: {auth-provider: {name: gcp}}`, but does not contain `cmd-path` key, kubeclient will automatically try this (raising LoadError if you don't have `googleauth` in your bundle).\n\nOr you can obtain a token manually:\n\n```ruby\nrequire 'googleauth'\n\nauth_options = {\n  bearer_token: Kubeclient::GoogleApplicationDefaultCredentials.token\n}\nclient = Kubeclient::Client.new(\n  'https://localhost:8443/api', 'v1', auth_options: auth_options\n)\n```\n\nNote that this returns a token good for one hour. If your code requires authorization for longer than that, you should plan to\nacquire a new one, see [How to manually renew](#how-to-manually-renew-expired-credentials) section.\n\n#### OIDC Auth Provider\n\nIf the cluster you are using has OIDC authentication enabled you can use the `openid_connect` gem to obtain\nid-tokens if the one in your kubeconfig has expired.\n\nThis requires the [`openid_connect` gem](https://github.com/nov/openid_connect) which is not included in\nthe `kubeclient` dependencies so should be added to your own applications bundle.\n\nThe OIDC Auth Provider will not perform the initial setup of your `$KUBECONFIG` file. You will need to use something\nlike [`dexter`](https://github.com/gini/dexter) in order to configure the auth-provider in your `$KUBECONFIG` file.\n\nIf you use `Config.context(...).auth_options` and the `$KUBECONFIG` file has user: `{auth-provider: {name: oidc}}`,\nkubeclient will automatically obtain a token (or use `id-token` if still valid)\n\nTokens are typically short-lived (e.g. 1 hour) and the expiration time is determined by the OIDC Provider (e.g. Google).\nIf your code requires authentication for longer than that you should obtain a new token periodically, see [How to manually renew](#how-to-manually-renew-expired-credentials) section.\n\nNote: id-tokens retrieved via this provider are not written back to the `$KUBECONFIG` file as they would be when\nusing `kubectl`.\n\n#### How to manually renew expired credentials\n\nKubeclient [does not yet](https://github.com/ManageIQ/kubeclient/issues/393) help with this.\n\nThe division of labor between `Config` and `Context` objects may change, for now please make no assumptions at which stage `exec:` and `auth-provider:` are handled and whether they're cached.\nThe currently guaranteed way to renew is create a new `Config` object.\n\nThe more painful part is that you'll then need to create new `Client` object(s) with the credentials from new config.\nSo repeat all of this:\n```ruby\nconfig = Kubeclient::Config.read(ENV['KUBECONFIG'] || '/path/to/.kube/config')\ncontext = config.context\nssl_options = context.ssl_options\nauth_options = context.auth_options\n\nclient = Kubeclient::Client.new(\n    context.api_endpoint, 'v1',\n    ssl_options: ssl_options, auth_options: auth_options\n)\n# and additional Clients if needed...\n```\n\n#### Security: Don't use config from untrusted sources\n\n`Config.read` is catastrophically unsafe — it will execute arbitrary command lines specified by the config!\n\n`Config.new(data, nil)` is better but Kubeclient was never reviewed for behaving safely with malicious / malformed config.\nIt might crash / misbehave in unexpected ways...\n\n#### namespace\n\nAdditionally, the `config.context` object will contain a `namespace` attribute, if it was defined in the file.\nIt is recommended that you use this namespace when issuing API commands below.\nThis is the same behavior that is implemented by `kubectl` command.\n\nYou can read it as follows:\n\n```ruby\nputs config.context.namespace\n```\n\n### Impersonation\n\nImpersonation is supported when loading a kubectl config and via the Ruby API, for example:\n\n```ruby\nclient = Kubeclient::Client.new(\n  context.api_endpoint, 'v1',\n  auth_options: {\n    as: \"admin\",\n    as_groups: [\"system:masters\"],\n    as_uid: \"123\", # optional\n    as_user_extra: {\n      \"reason\" =\u003e [\"admin access\"]\n    }\n  }\n)\n```\n\nNote that only one group and one value per each extra field are currently supported. Using list of multiple values\nwill result in `ArgumentError`.\n\n### Supported kubernetes versions\n\nWe try to support the last 3 minor versions, matching the [official support policy for Kubernetes](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/release/versioning.md#supported-releases-and-component-skew).\nKubernetes 1.2 and below have known issues and are unsupported.\nKubernetes 1.3 presumed to still work although nobody is really testing on such old versions...\n\n## Supported actions \u0026 examples:\n\nSummary of main CRUD actions:\n\n```\nget_foos(namespace: 'namespace', **opts)  # namespaced collection\nget_foos(**opts)                          # all namespaces or global collection\n\nget_foo('name', 'namespace', opts)  # namespaced\nget_foo('name', nil, opts)          # global\n\nwatch_foos(namespace: ns, **opts)   # namespaced collection\nwatch_foos(**opts)                  # all namespaces or global collection\nwatch_foos(namespace: ns, name: 'name', **opts)   # namespaced single object\nwatch_foos(name: 'name', **opts)                  # global single object\n\ndelete_foo('name', 'namespace', opts)    # namespaced\ndelete_foo('name', nil, opts)            # global\ndelete_foos(namespace: 'ns', **opts)     # namespaced\n\ncreate_foo(Kubeclient::Resource.new({metadata: {name: 'name', namespace: 'namespace', ...}, ...}))\ncreate_foo(Kubeclient::Resource.new({metadata: {name: 'name', ...}, ...}))  # global\n\nupdate_foo(Kubeclient::Resource.new({metadata: {name: 'name', namespace: 'namespace', ...}, ...}))\nupdate_foo(Kubeclient::Resource.new({metadata: {name: 'name', ...}, ...}))  # global\n\npatch_foo('name', patch, 'namespace')    # namespaced\npatch_foo('name', patch)                 # global\n\napply_foo(Kubeclient::Resource.new({metadata: {name: 'name', namespace: 'namespace', ...}, ...}), field_manager: 'myapp', **opts)\napply_foo(Kubeclient::Resource.new({metadata: {name: 'name', ...}, ...}), field_manager: 'myapp', **opts)  # global\n```\n\nThese grew to be quite inconsistent :confounded:, see https://github.com/ManageIQ/kubeclient/issues/312 and https://github.com/ManageIQ/kubeclient/issues/332 for improvement plans.\n\n### Get all instances of a specific entity type\nSuch as: `get_pods`, `get_secrets`, `get_services`, `get_nodes`, `get_replication_controllers`, `get_resource_quotas`, `get_limit_ranges`, `get_persistent_volumes`, `get_persistent_volume_claims`, `get_component_statuses`, `get_service_accounts`\n\n```ruby\npods = client.get_pods\n```\n\nGet all entities of a specific type in a namespace:\n\n```ruby\nservices = client.get_services(namespace: 'development')\n```\n\nYou can get entities which have specific labels by specifying a parameter named `label_selector` (named `labelSelector` in Kubernetes server):\n\n```ruby\npods = client.get_pods(label_selector: 'name=redis-master')\n```\n\nYou can specify multiple labels (that option will return entities which have both labels:\n\n```ruby\npods = client.get_pods(label_selector: 'name=redis-master,app=redis')\n```\n\nThere is also [a ability to filter by *some* fields](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).  Which fields are supported is not documented, you can try and see if you get an error...\n```ruby\nclient.get_pods(field_selector: 'spec.nodeName=master-0')\n```\n\nYou can ask for entities at a specific version by specifying a parameter named `resource_version`:\n```ruby\npods = client.get_pods(resource_version: '0')\n```\nbut it's not guaranteed you'll get it.  See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions to understand the semantics.\n\nWith default (`as: :ros`) return format, the returned object acts like an array of the individual pods, but also supports a `.resourceVersion` method.\n\nWith `:parsed` and `:parsed_symbolized` formats, the returned data structure matches kubernetes list structure: it's a hash containing  `metadata` and `items` keys, the latter containing the individual pods.\n\n#### Get all entities of a specific type in chunks\n\n```ruby\ncontinue = nil\nloop do\n  entities = client.get_pods(limit: 1_000, continue: continue)\n  continue = entities.continue\n\n  break if entities.last?\nend\n```\n\nSee https://kubernetes.io/docs/reference/using-api/api-concepts/#retrieving-large-results-sets-in-chunks for more information.\n\nThe continue tokens expire after a short amount of time, so similar to a watch if you don't request a subsequent page within aprox. 5 minutes of the previous page being returned the server will return a `410 Gone` error and the client must request the list from the start (i.e. omit the continue token for the next call).\n\nSupport for chunking was added in v1.9 so previous versions will ignore the option and return the full collection.\n\n#### Get a specific instance of an entity (by name)\nSuch as: `get_service \"service name\"` , `get_pod \"pod name\"` , `get_replication_controller \"rc name\"`, `get_secret \"secret name\"`, `get_resource_quota \"resource quota name\"`, `get_limit_range \"limit range name\"` , `get_persistent_volume \"persistent volume name\"` , `get_persistent_volume_claim \"persistent volume claim name\"`, `get_component_status \"component name\"`, `get_service_account \"service account name\"`\n\nThe GET request should include the namespace name, except for nodes and namespaces entities.\n\n```ruby\nnode = client.get_node \"127.0.0.1\"\n```\n\n```ruby\nservice = client.get_service \"guestbook\", 'development'\n```\n\nNote - Kubernetes doesn't work with the uid, but rather with the 'name' property.\nQuerying with uid causes 404.\n\n#### Getting raw responses\n\nTo avoid overhead from parsing and building `RecursiveOpenStruct` objects for each reply, pass the `as: :raw` option when initializing `Kubeclient::Client` or when calling `get_` / `watch_` methods.\nThe result can then be printed, or searched with a regex, or parsed via `JSON.parse(r)`.\n\n```ruby\nclient = Kubeclient::Client.new(url, version, as: :raw)\n```\n\nor\n\n```ruby\npods = client.get_pods as: :raw\nnode = client.get_node \"127.0.0.1\", as: :raw\n```\n\nOther formats are:\n - `:ros` (default) for `RecursiveOpenStruct`\n - `:parsed` for `JSON.parse`\n - `:parsed_symbolized` for `JSON.parse(..., symbolize_names: true)`\n - a class of your choice (this will instantiate a new instance of that class with the raw value of the response body)\n\n### Watch — Receive entities updates\n\nSee https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes for an overview.\n\nIt is possible to receive live update notices watching the relevant entities:\n\n```ruby\nclient.watch_pods do |notice|\n  # process notice data\nend\n```\n\nThe notices have `.type` field which may be `'ADDED'`, `'MODIFIED'`, `'DELETED'`, or currently `'ERROR'`, and an `.object` field containing the object.  **UPCOMING CHANGE**: In next major version, we plan to raise exceptions instead of passing on ERROR into the block.\n\nFor namespaced entities, the default watches across all namespaces, and you can specify `client.watch_secrets(namespace: 'foo')` to only watch in a single namespace.\n\nYou can narrow down using `label_selector:` and `field_selector:` params, like with `get_pods` methods.\n\nYou can also watch a single object by specifying `name:` e.g. `client.watch_nodes(name: 'gandalf')` (not namespaced so a name is enough) or `client.watch_pods(namespace: 'foo', name: 'bar')` (namespaced, need both params).\nNote the method name is still plural!  There is no `watch_pod`, only `watch_pods`.  The yielded \"type\" remains the same — watch notices, it's just they'll always refer to the same object.\n\nYou can use `as:` param to control the format of the yielded notices.\n\nYou can use `allow_watch_bookmarks: true` to get `BOOKMARK` events returned regularly, see [watch bookmarks](https://kubernetes.io/docs/reference/using-api/api-concepts/#watch-bookmarks)\n```ruby\nclient.watch_pods allow_watch_bookmarks: true do |notice|\n  # process notice data\nend\n```\n\nTo limit the maximum duration of a watch on the server, pass the `timeout_seconds:` param.\n```ruby\nclient.watch_pods(timeout_seconds: 120, namespace: ns) do |notice|\n  ...\nend\n```\n\n#### All watches come to an end!\n\nWhile nominally the watch block *looks* like an infinite loop, that's unrealistic.  Network connections eventually get severed, and kubernetes apiserver is known to terminate watches.\n\nUnfortunately, this sometimes raises an exception and sometimes the loop just exits.  **UPCOMING CHANGE**: In next major version, non-deliberate termination will always raise an exception; the block will only exit silenty if stopped deliberately.\n\n#### Deliberately stopping a watch\n\nYou can use `break` or `return` inside the watch block.\n\nIt is possible to interrupt the watcher from another thread with:\n\n```ruby\nwatcher = client.watch_pods\n\nwatcher.each do |notice|\n  # process notice data\nend\n# \u003c- control will pass here after .finish is called\n\n### In another thread ###\nwatcher.finish\n```\n\n#### Starting watch version\n\nYou can specify version to start from, commonly used in \"List+Watch\" pattern:\n```\nlist = client.get_pods\ncollection_version = list.resourceVersion\n# or with other return formats:\nlist = client.get_pods(as: :parsed)\ncollection_version = list['metadata']['resourceVersion']\n\n# note spelling resource_version vs resourceVersion.\nclient.watch_pods(resource_version: collection_version) do |notice|\n  # process notice data\nend\n```\nIt's important to understand [the effects of unset/0/specific resource_version](https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions) as it modifies the behavior of the watch — in some modes you'll first see a burst of synthetic 'ADDED' notices for all existing objects.\n\nIf you re-try a terminated watch again without specific resourceVersion, you might see previously seen notices again, and might miss some events.\n\nTo attempt resuming a watch from same point, you can try using last resourceVersion observed during the watch.  Or do list+watch again.\n\nWhenever you ask for a specific version, you must be prepared for an 410 \"Gone\" error if the server no longer recognizes it.\n\n#### Watch events about a particular object\nEvents are [entities in their own right](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#event-v1-core).\nYou can use the `field_selector` option as part of the watch methods.\n\n```ruby\nclient.watch_events(namespace: 'development', field_selector: 'involvedObject.name=redis-master') do |notice|\n  # process notice date\nend\n```\n\n### Delete an entity (by name)\n\nFor example: `delete_pod \"pod name\"` , `delete_replication_controller \"rc name\"`, `delete_node \"node name\"`, `delete_secret \"secret name\"`\n\nInput parameter - name (string) specifying service name, pod name, replication controller name.\n\n```ruby\ndeleted = client.delete_service(\"redis-service\")\n```\n\nIf you want to cascade delete, for example a deployment, you can use the `delete_options` parameter.\n\n```ruby\ndeployment_name = 'redis-deployment'\nnamespace = 'default'\ndelete_options = Kubeclient::Resource.new(\n    apiVersion: 'meta/v1',\n    gracePeriodSeconds: 0,\n    kind: 'DeleteOptions',\n    propagationPolicy: 'Foreground' # Orphan, Foreground, or Background\n)\nclient.delete_deployment(deployment_name, namespace, delete_options: delete_options)\n```\n\n### Delete all instances of a specific entity type in a namespace\nSuch as: `delete_pods`, `delete_secrets`, `delete_services`, `delete_nodes`, `delete_replication_controllers`, `delete_resource_quotas`, `delete_limit_ranges`, `delete_persistent_volumes`, `delete_persistent_volume_claims`, `delete_component_statuses`, `delete_service_accounts`\n\nDelete all entities of a specific type in a namespace, entities are returned in the same manner as for `get_services`:\n\n```ruby\nservices = client.delete_services(namespace: 'development')\n```\n\nYou can get entities which have specific labels by specifying a parameter named `label_selector` (named `labelSelector` in Kubernetes server):\n\n```ruby\npods = client.delete_pods(namespace: 'development', label_selector: 'name=redis-master')\n```\n\nYou can specify multiple labels (that option will return entities which have both labels:\n\n```ruby\npods = client.delete_pods(namespace: 'default', label_selector: 'name=redis-master,app=redis')\n```\n\nThere is also [a ability to filter by *some* fields](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).  Which fields are supported is not documented, you can try and see if you get an error...\n```ruby\nclient.delete_pods(namespace: 'development', field_selector: 'spec.nodeName=master-0')\n```\n\nWith default (`as: :ros`) return format, the returned object acts like an array of the individual pods, but also supports a `.resourceVersion` method.\n\nWith `:parsed` and `:parsed_symbolized` formats, the returned data structure matches kubernetes list structure: it's a hash containing  `metadata` and `items` keys, the latter containing the individual pods.\n\n### Create an entity\nFor example: `create_pod pod_object`, `create_replication_controller rc_obj`, `create_secret secret_object`, `create_resource_quota resource_quota_object`, `create_limit_range limit_range_object`, `create_persistent_volume persistent_volume_object`, `create_persistent_volume_claim persistent_volume_claim_object`, `create_service_account service_account_object`\n\nInput parameter - object of type `Service`, `Pod`, `ReplicationController`.\n\nThe below example is for v1\n\n```ruby\nservice = Kubeclient::Resource.new\nservice.metadata = {}\nservice.metadata.name = \"redis-master\"\nservice.metadata.namespace = 'staging'\nservice.spec = {}\nservice.spec.ports = [{\n  'port' =\u003e 6379,\n  'targetPort' =\u003e 'redis-server'\n}]\nservice.spec.selector = {}\nservice.spec.selector.name = \"redis\"\nservice.spec.selector.role = \"master\"\nservice.metadata.labels = {}\nservice.metadata.labels.app = 'redis'\nservice.metadata.labels.role = 'slave'\nclient.create_service(service)\n```\n\n### Update an entity\nFor example: `update_pod`, `update_service`, `update_replication_controller`, `update_secret`, `update_resource_quota`, `update_limit_range`, `update_persistent_volume`, `update_persistent_volume_claim`, `update_service_account`\n\nInput parameter - object of type `Pod`, `Service`, `ReplicationController` etc.\n\nThe below example is for v1\n\n```ruby\nupdated = client.update_service(service1)\n```\n\n### Patch an entity (by name)\nFor example: `patch_pod`, `patch_service`, `patch_secret`, `patch_resource_quota`, `patch_persistent_volume`\n\nInput parameters - name (string) specifying the entity name, patch (hash) to be applied to the resource, optional: namespace name (string)\n\nThe PATCH request should include the namespace name, except for nodes and namespaces entities.\n\nThe below example is for v1\n\n```ruby\npatched = client.patch_pod(\"docker-registry\", {metadata: {annotations: {key: 'value'}}}, \"default\")\n```\n\n`patch_#{entity}` is called using a [strategic merge patch](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#notes-on-the-strategic-merge-patch). `json_patch_#{entity}` and `merge_patch_#{entity}` are also available that use JSON patch and JSON merge patch, respectively. These strategies are useful for resources that do not support strategic merge patch, such as Custom Resources. Consult the [Kubernetes docs](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) for more information about the different patch strategies.\n\n### Apply an entity\n\nThis is similar to `kubectl apply --server-side` (kubeclient doesn't implement logic for client-side apply). See https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply\n\nFor example: `apply_pod`\n\nInput parameters - resource (Kubeclient::Resource) representing the desired state of the resource, field_manager (String) to identify the system managing the state of the resource, force (Boolean) whether or not to override a field managed by someone else.\n\nExample:\n\n```ruby\nservice = Kubeclient::Resource.new(\n  metadata: {\n    name: 'redis-master',\n    namespace: 'staging',\n  },\n  spec: {\n    ...\n  }\n)\n\nclient.apply_service(service, field_manager: 'myapp')\n```\n\n### Get all entities of all types : all_entities\n\nMakes requests for all entities of each discovered kind (in this client's API group).  This method is a convenience method instead of calling each entity's get method separately.\n\nReturns a hash with keys being the *singular* entity kind, in lowercase underscore style.  For example for core API group may return keys `\"node'`, `\"secret\"`, `\"service\"`, `\"pod\"`, `\"replication_controller\"`, `\"namespace\"`, `\"resource_quota\"`, `\"limit_range\"`, `\"endpoint\"`, `\"event\"`, `\"persistent_volume\"`, `\"persistent_volume_claim\"`, `\"component_status\"`, `\"service_account\"`. Each key points to an EntityList of same type.\n\n```ruby\nclient.all_entities\n```\n\n### Get a proxy URL\nYou can get a complete URL for connecting a kubernetes entity via the proxy.\n\n```ruby\nclient.proxy_url('service', 'srvname', 'srvportname', 'ns')\n# =\u003e \"https://localhost.localdomain:8443/api/v1/proxy/namespaces/ns/services/srvname:srvportname\"\n```\n\nNote the third parameter, port, is a port name for services and an integer for pods:\n\n```ruby\nclient.proxy_url('pod', 'podname', 5001, 'ns')\n# =\u003e \"https://localhost.localdomain:8443/api/v1/namespaces/ns/pods/podname:5001/proxy\"\n```\n\n### Get the logs of a pod\nYou can get the logs of a running pod, specifying the name of the pod and the\nnamespace where the pod is running:\n\n```ruby\nclient.get_pod_log('pod-name', 'default')\n# =\u003e \"Running...\\nRunning...\\nRunning...\\n\"\n```\n\nIf that pod has more than one container, you must specify the container:\n\n```ruby\nclient.get_pod_log('pod-name', 'default', container: 'ruby')\n# =\u003e \"...\"\n```\n\nIf a container in a pod terminates, a new container is started, and you want to\nretrieve the logs of the dead container, you can pass in the `:previous` option:\n\n```ruby\nclient.get_pod_log('pod-name', 'default', previous: true)\n# =\u003e \"...\"\n```\n\nKubernetes can add timestamps to every log line or filter by lines time:\n```ruby\nclient.get_pod_log('pod-name', 'default', timestamps: true, since_time: '2018-04-27T18:30:17.480321984Z')\n# =\u003e \"...\"\n```\n`since_time` can be a a `Time`, `DateTime` or `String` formatted according to RFC3339\n\nKubernetes can fetch a specific number of lines from the end of the logs:\n```ruby\nclient.get_pod_log('pod-name', 'default', tail_lines: 10)\n# =\u003e \"...\"\n```\n\nKubernetes can fetch a specific number of bytes from the log, but the exact size is not guaranteed and last line may not be terminated:\n```ruby\nclient.get_pod_log('pod-name', 'default', limit_bytes: 10)\n# =\u003e \"...\"\n```\n\nYou can also watch the logs of a pod to get a stream of data:\n\n```ruby\nclient.watch_pod_log('pod-name', 'default', container: 'ruby') do |line|\n  puts line\nend\n```\n\n### OpenShift: Process a template\nReturns a processed template containing a list of objects to create.\nInput parameter - template (hash)\nBesides its metadata, the template should include a list of objects to be processed and a list of parameters\nto be substituted. Note that for a required parameter that does not provide a generated value, you must supply a value.\n\n##### Note: This functionality is not supported by K8s at this moment. See the following [issue](https://github.com/kubernetes/kubernetes/issues/23896)\n\n```ruby\nclient.process_template template\n```\n\n### Informer\n\nA list that is always updated because it is it kept in sync by a watch in the background.\nCan also share a list+watch with multiple threads.\n\n```ruby\nclient = Kubeclient::Client.new('http://localhost:8080/api/', 'v1')\ninformer = Kubeclient::Informer.new(client, \"pods\", reconcile_timeout: 15 * 60, logger: Logger.new(STDOUT))\ninformer.start_worker\n\ninformer.list # all current pods\ninformer.watch { |notice|  } # watch for changes (hides restarts and errors)\n```\n\nTo pass custom options to the list and watch request, like setting namespace, the\ninitializer accepts `options` keyword:\n\n```ruby\ninformer = Kubeclient::Informer.new(\n  client,\n  \"pods\",\n  options: { namespace: \"some-namespace\" },\n  reconcile_timeout: 15 * 60,\n  logger: Logger.new(STDOUT)\n)\n```\n\n## Contributing\n\n1. Fork it ( https://github.com/[my-github-username]/kubeclient/fork )\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Test your changes with `rake test rubocop`, add new tests if needed.\n4. If you added a new functionality, add it to README\n5. Commit your changes (`git commit -am 'Add some feature'`)\n6. Push to the branch (`git push origin my-new-feature`)\n7. Create a new Pull Request\n\n## Tests\n\nThis client is tested with Minitest and also uses VCR recordings in some tests.\nPlease run all tests before submitting a Pull Request, and add new tests for new functionality.\n\nRunning tests:\n```ruby\nrake test\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanageiq%2Fkubeclient","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmanageiq%2Fkubeclient","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmanageiq%2Fkubeclient/lists"}