Este contenido no está disponible en el idioma seleccionado.
Chapter 4. Knative CLI
4.1. Installing the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
The Knative (
kn
oc
oc login
For more information on installing the
oc
oc
OpenShift Serverless cannot be installed using the Knative (
kn
If you try to use an older version of the Knative (
kn
For example, if you use the 1.23.0 release of the Knative (
kn
Ensure that you are using the latest Knative (
kn
4.1.1. Installing the Knative CLI using the OpenShift Container Platform web console Copiar enlaceEnlace copiado en el portapapeles!
Using the OpenShift Container Platform web console provides a streamlined and intuitive user interface to install the Knative (
kn
kn
Prerequisites
- You have logged in to the OpenShift Container Platform web console.
The OpenShift Serverless Operator and Knative Serving are installed on your OpenShift Container Platform cluster.
ImportantIf libc is not available, you might see the following error when you run CLI commands:
$ kn: No such file or directory-
If you want to use the verification steps for this procedure, you must install the OpenShift () CLI.
oc
Procedure
-
Download the Knative () CLI from the Command Line Tools page. You can access the Command Line Tools page by clicking the
kn
icon in the top right corner of the web console and selecting Command Line Tools in the list.
Unpack the archive:
$ tar -xf <file>-
Move the binary to a directory on your
kn.PATH To check your
, run:PATH$ echo $PATH
Verification
Run the following commands to check that the correct Knative CLI resources and route have been created:
$ oc get ConsoleCLIDownloadExample output
NAME DISPLAY NAME AGE kn kn - OpenShift Serverless Command Line Interface (CLI) 2022-09-20T08:41:18Z oc-cli-downloads oc - OpenShift Command Line Interface (CLI) 2022-09-20T08:00:20Z$ oc get route -n openshift-serverlessExample output
NAME HOST/PORT PATH SERVICES PORT TERMINATION WILDCARD kn kn-openshift-serverless.apps.example.com knative-openshift-metrics-3 http-cli edge/Redirect None
4.1.2. Installing the Knative CLI for Linux by using an RPM package manager Copiar enlaceEnlace copiado en el portapapeles!
For Red Hat Enterprise Linux (RHEL), you can install the Knative (
kn
yum
dnf
dnf upgrade
kn
Prerequisites
- You have an active OpenShift Container Platform subscription on your Red Hat account.
Procedure
Register with Red Hat Subscription Manager:
# subscription-manager registerPull the latest subscription data:
# subscription-manager refreshAttach the subscription to the registered system:
# subscription-manager attach --pool=<pool_id>1 - 1
- Pool ID for an active OpenShift Container Platform subscription
Enable the repositories required by the Knative (
) CLI:knLinux (x86_64, amd64)
# subscription-manager repos --enable="openshift-serverless-1-for-rhel-8-x86_64-rpms"Linux on IBM Z and LinuxONE (s390x)
# subscription-manager repos --enable="openshift-serverless-1-for-rhel-8-s390x-rpms"Linux on IBM Power (ppc64le)
# subscription-manager repos --enable="openshift-serverless-1-for-rhel-8-ppc64le-rpms"
Install the Knative (
) CLI as an RPM by using a package manager:knExample
yumcommand# yum install openshift-serverless-clients
4.1.3. Installing the Knative CLI for Linux Copiar enlaceEnlace copiado en el portapapeles!
If you are using a Linux distribution that does not have RPM or another package manager installed, you can install the Knative (
kn
tar.gz
PATH
Prerequisites
If you are not using RHEL or Fedora, ensure that libc is installed in a directory on your library path.
ImportantIf libc is not available, you might see the following error when you run CLI commands:
$ kn: No such file or directory
Procedure
Download the relevant Knative (
) CLIknarchive:tar.gzYou can also download any version of
by navigating to that version’s corresponding directory in the Serverless client download mirror.knUnpack the archive:
$ tar -xf <filename>-
Move the binary to a directory on your
kn.PATH To check your
, run:PATH$ echo $PATH
4.1.4. Installing the Knative CLI for macOS Copiar enlaceEnlace copiado en el portapapeles!
If you are using macOS, you can install the Knative (
kn
tar.gz
PATH
Procedure
Download the Knative (
kn) CLItar.gzarchive.You can also download any version of
by navigating to that version’s corresponding directory in the Serverless client download mirror.kn- Unpack and extract the archive.
-
Move the binary to a directory on your
kn.PATH To check your
, open a terminal window and run:PATH$ echo $PATH
4.1.5. Installing the Knative CLI for Windows Copiar enlaceEnlace copiado en el portapapeles!
If you are using Windows, you can install the Knative (
kn
PATH
Procedure
Download the Knative (
kn) CLI ZIP archive.You can also download any version of
by navigating to that version’s corresponding directory in the Serverless client download mirror.kn- Extract the archive with a ZIP program.
-
Move the binary to a directory on your
kn.PATH To check your
, open the command prompt and run the command:PATHC:\> path
4.2. Configuring the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can customize your Knative (
kn
config.yaml
--config
For UNIX systems:
-
If the environment variable is set, the default configuration location that the Knative (
XDG_CONFIG_HOME) CLI looks for iskn.$XDG_CONFIG_HOME/kn -
If the environment variable is not set, the Knative (
XDG_CONFIG_HOME) CLI looks for the configuration in the home directory of the user atkn.$HOME/.config/kn/config.yaml
For Windows systems, the default Knative (
kn
%APPDATA%\kn
Example configuration file
plugins:
path-lookup: true
directory: ~/.config/kn/plugins
eventing:
sink-mappings:
- prefix: svc
group: core
version: v1
resource: services
- 1
- Specifies whether the Knative (
kn) CLI should look for plugins in thePATHenvironment variable. This is a boolean configuration option. The default value isfalse. - 2
- Specifies the directory where the Knative (
kn) CLI looks for plugins. The default path depends on the operating system, as described previously. This can be any directory that is visible to the user. - 3
- The
sink-mappingsspec defines the Kubernetes addressable resource that is used when you use the--sinkflag with a Knative (kn) CLI command. - 4
- The prefix you want to use to describe your sink.
svcfor a service,channel, andbrokerare predefined prefixes for the Knative (kn) CLI. - 5
- The API group of the Kubernetes resource.
- 6
- The version of the Kubernetes resource.
- 7
- The plural name of the Kubernetes resource type. For example,
servicesorbrokers.
4.3. Knative CLI plugins Copiar enlaceEnlace copiado en el portapapeles!
The Knative (
kn
kn
kn
kn
Currently, Red Hat supports the
kn-source-kafka
kn-event
The
kn-event
For more information about the support scope of Red Hat Technology Preview features, see https://access.redhat.com/support/offerings/techpreview/.
4.3.1. Building events by using the kn-event plugin Copiar enlaceEnlace copiado en el portapapeles!
You can use the builder-like interface of the
kn event build
Prerequisites
-
You have installed the Knative () CLI.
kn
Procedure
Build an event:
$ kn event build --field <field-name>=<value> --type <type-name> --id <id> --output <format>where:
-
The flag adds data to the event as a field-value pair. You can use it multiple times.
--field -
The flag enables you to specify a string that designates the type of the event.
--type -
The flag specifies the ID of the event.
--id You can use the
orjsonarguments with theyamlflag to change the output format of the event.--outputAll of these flags are optional.
Building a simple event
$ kn event build -o yamlResultant event in the YAML format
data: {} datacontenttype: application/json id: 81a402a2-9c29-4c27-b8ed-246a253c9e58 source: kn-event/v0.4.0 specversion: "1.0" time: "2021-10-15T10:42:57.713226203Z" type: dev.knative.cli.plugin.event.genericBuilding a sample transaction event
$ kn event build \ --field operation.type=local-wire-transfer \ --field operation.amount=2345.40 \ --field operation.from=87656231 \ --field operation.to=2344121 \ --field automated=true \ --field signature='FGzCPLvYWdEgsdpb3qXkaVp7Da0=' \ --type org.example.bank.bar \ --id $(head -c 10 < /dev/urandom | base64 -w 0) \ --output jsonResultant event in the JSON format
{ "specversion": "1.0", "id": "RjtL8UH66X+UJg==", "source": "kn-event/v0.4.0", "type": "org.example.bank.bar", "datacontenttype": "application/json", "time": "2021-10-15T10:43:23.113187943Z", "data": { "automated": true, "operation": { "amount": "2345.40", "from": 87656231, "to": 2344121, "type": "local-wire-transfer" }, "signature": "FGzCPLvYWdEgsdpb3qXkaVp7Da0=" } }
-
The
4.3.2. Sending events by using the kn-event plugin Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn event send
kn event build
Prerequisites
-
You have installed the Knative () CLI.
kn
Procedure
Send an event:
$ kn event send --field <field-name>=<value> --type <type-name> --id <id> --to-url <url> --to <cluster-resource> --namespace <namespace>where:
-
The flag adds data to the event as a field-value pair. You can use it multiple times.
--field -
The flag enables you to specify a string that designates the type of the event.
--type -
The flag specifies the ID of the event.
--id -
If you are sending the event to a publicly accessible destination, specify the URL using the flag.
--to-url If you are sending the event to an in-cluster Kubernetes resource, specify the destination using the
flag.--to-
Specify the Kubernetes resource using the format.
<Kind>:<ApiVersion>:<name>
-
Specify the Kubernetes resource using the
The
flag specifies the namespace. If omitted, the namespace is taken from the current context.--namespaceAll of these flags are optional, except for the destination specification, for which you need to use either
or--to-url.--toThe following example shows sending an event to a URL:
Example command
$ kn event send \ --field player.id=6354aa60-ddb1-452e-8c13-24893667de20 \ --field player.game=2345 \ --field points=456 \ --type org.example.gaming.foo \ --to-url http://ce-api.foo.example.com/The following example shows sending an event to an in-cluster resource:
Example command
$ kn event send \ --type org.example.kn.ping \ --id $(uuidgen) \ --field event.type=test \ --field event.data=98765 \ --to Service:serving.knative.dev/v1:event-display
-
The
4.4. Knative Serving CLI commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following Knative (
kn
4.4.1. kn service commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following commands to create and manage Knative services.
4.4.1.1. Creating serverless applications by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
Using the Knative (
kn
kn service create
Prerequisites
- OpenShift Serverless Operator and Knative Serving are installed on your cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
Procedure
Create a Knative service:
$ kn service create <service-name> --image <image> --tag <tag-value>Where:
-
is the URI of the image for the application.
--image - is an optional flag that can be used to add a tag to the initial revision that is created with the service.
--tagExample command
$ kn service create event-display \ --image quay.io/openshift-knative/knative-eventing-sources-event-display:latestExample output
Creating service 'event-display' in namespace 'default': 0.271s The Route is still working to reflect the latest desired specification. 0.580s Configuration "event-display" is waiting for a Revision to become ready. 3.857s ... 3.861s Ingress has not yet been reconciled. 4.270s Ready to serve. Service 'event-display' created with latest revision 'event-display-bxshg-1' and URL: http://event-display-default.apps-crc.testing
-
4.4.1.2. Updating serverless applications by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn service update
kn service apply
kn service update
Example commands
Update a service by adding a new environment variable:
$ kn service update <service_name> --env <key>=<value>Update a service by adding a new port:
$ kn service update <service_name> --port 80Update a service by adding new request and limit parameters:
$ kn service update <service_name> --request cpu=500m --limit memory=1024Mi --limit cpu=1000mAssign the
tag to a revision:latest$ kn service update <service_name> --tag <revision_name>=latestUpdate a tag from
totestingfor the lateststagingrevision of a service:READY$ kn service update <service_name> --untag testing --tag @latest=stagingAdd the
tag to a revision that receives 10% of traffic, and send the rest of the traffic to the latesttestrevision of a service:READY$ kn service update <service_name> --tag <revision_name>=test --traffic test=10,@latest=90
4.4.1.3. Applying service declarations Copiar enlaceEnlace copiado en el portapapeles!
You can declaratively configure a Knative service by using the
kn service apply
The
kn service apply
When using
kn service apply
kn service update
Example commands
Create a service:
$ kn service apply <service_name> --image <image>Add an environment variable to a service:
$ kn service apply <service_name> --image <image> --env <key>=<value>Read the service declaration from a JSON or YAML file:
$ kn service apply <service_name> -f <filename>
4.4.1.4. Describing serverless applications by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can describe a Knative service by using the
kn service describe
Example commands
Describe a service:
$ kn service describe --verbose <service_name>The
flag is optional but can be included to provide a more detailed description. The difference between a regular and verbose output is shown in the following examples:--verboseExample output without
--verboseflagName: hello Namespace: default Age: 2m URL: http://hello-default.apps.ocp.example.com Revisions: 100% @latest (hello-00001) [1] (2m) Image: docker.io/openshift/hello-openshift (pinned to aaea76) Conditions: OK TYPE AGE REASON ++ Ready 1m ++ ConfigurationsReady 1m ++ RoutesReady 1mExample output with
--verboseflagName: hello Namespace: default Annotations: serving.knative.dev/creator=system:admin serving.knative.dev/lastModifier=system:admin Age: 3m URL: http://hello-default.apps.ocp.example.com Cluster: http://hello.default.svc.cluster.local Revisions: 100% @latest (hello-00001) [1] (3m) Image: docker.io/openshift/hello-openshift (pinned to aaea76) Env: RESPONSE=Hello Serverless! Conditions: OK TYPE AGE REASON ++ Ready 3m ++ ConfigurationsReady 3m ++ RoutesReady 3mDescribe a service in YAML format:
$ kn service describe <service_name> -o yamlDescribe a service in JSON format:
$ kn service describe <service_name> -o jsonPrint the service URL only:
$ kn service describe <service_name> -o url
4.4.2. About the Knative CLI offline mode Copiar enlaceEnlace copiado en el portapapeles!
When you execute
kn service
kn service
The offline mode of the Knative CLI is a Technology Preview feature only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs) and might not be functionally complete. Red Hat does not recommend using them in production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features, see https://access.redhat.com/support/offerings/techpreview/.
After the descriptor file is created, you can manually modify it and track it in a version control system. You can also propagate changes to the cluster by using the
kn service create -f
kn service apply -f
oc apply -f
The offline mode has several uses:
- You can manually modify the descriptor file before using it to make changes on the cluster.
- You can locally track the descriptor file of a service in a version control system. This enables you to reuse the descriptor file in places other than the target cluster, for example in continuous integration (CI) pipelines, development environments, or demos.
-
You can examine the created descriptor files to learn about Knative services. In particular, you can see how the resulting service is influenced by the different arguments passed to the command.
kn
The offline mode has its advantages: it is fast, and does not require a connection to the cluster. However, offline mode lacks server-side validation. Consequently, you cannot, for example, verify that the service name is unique or that the specified image can be pulled.
4.4.2.1. Creating a service using offline mode Copiar enlaceEnlace copiado en el portapapeles!
You can execute
kn service
The offline mode of the Knative CLI is a Technology Preview feature only. Technology Preview features are not supported with Red Hat production service level agreements (SLAs) and might not be functionally complete. Red Hat does not recommend using them in production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features, see https://access.redhat.com/support/offerings/techpreview/.
Prerequisites
- OpenShift Serverless Operator and Knative Serving are installed on your cluster.
-
You have installed the Knative () CLI.
kn
Procedure
In offline mode, create a local Knative service descriptor file:
$ kn service create event-display \ --image quay.io/openshift-knative/knative-eventing-sources-event-display:latest \ --target ./ \ --namespace testExample output
Service 'event-display' created in namespace 'test'.The
flag enables offline mode and specifies--target ./as the directory for storing the new directory tree../If you do not specify an existing directory, but use a filename, such as
, then no directory tree is created. Instead, only the service descriptor file--target my-service.yamlis created in the current directory.my-service.yamlThe filename can have the
,.yaml, or.ymlextension. Choosing.jsoncreates the service descriptor file in the JSON format..jsonThe
option places the new service in the--namespace testnamespace.testIf you do not use
, and you are logged in to an OpenShift Container Platform cluster, the descriptor file is created in the current namespace. Otherwise, the descriptor file is created in the--namespacenamespace.default
Examine the created directory structure:
$ tree ./Example output
./ └── test └── ksvc └── event-display.yaml 2 directories, 1 file-
The current directory specified with
./contains the new--targetdirectory that is named after the specified namespace.test/ -
The directory contains the
test/directory, named after the resource type.ksvc -
The directory contains the descriptor file
ksvc, named according to the specified service name.event-display.yaml
-
The current
Examine the generated service descriptor file:
$ cat test/ksvc/event-display.yamlExample output
apiVersion: serving.knative.dev/v1 kind: Service metadata: creationTimestamp: null name: event-display namespace: test spec: template: metadata: annotations: client.knative.dev/user-image: quay.io/openshift-knative/knative-eventing-sources-event-display:latest creationTimestamp: null spec: containers: - image: quay.io/openshift-knative/knative-eventing-sources-event-display:latest name: "" resources: {} status: {}List information about the new service:
$ kn service describe event-display --target ./ --namespace testExample output
Name: event-display Namespace: test Age: URL: Revisions: Conditions: OK TYPE AGE REASONThe
option specifies the root directory for the directory structure containing namespace subdirectories.--target ./Alternatively, you can directly specify a YAML or JSON filename with the
option. The accepted file extensions are--target,.yaml, and.yml..jsonThe
option specifies the namespace, which communicates to--namespacethe subdirectory that contains the necessary service descriptor file.knIf you do not use
, and you are logged in to an OpenShift Container Platform cluster,--namespacesearches for the service in the subdirectory that is named after the current namespace. Otherwise,knsearches in theknsubdirectory.default/
Use the service descriptor file to create the service on the cluster:
$ kn service create -f test/ksvc/event-display.yamlExample output
Creating service 'event-display' in namespace 'test': 0.058s The Route is still working to reflect the latest desired specification. 0.098s ... 0.168s Configuration "event-display" is waiting for a Revision to become ready. 23.377s ... 23.419s Ingress has not yet been reconciled. 23.534s Waiting for load balancer to be ready 23.723s Ready to serve. Service 'event-display' created to latest revision 'event-display-00001' is available at URL: http://event-display-test.apps.example.com
4.4.3. kn container commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following commands to create and manage multiple containers in a Knative service spec.
4.4.3.1. Knative client multi-container support Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn container add
kn
The
kn container add
kn service create
kn container add
|
Example commands
Add a container from an image and print it to standard output:
$ kn container add <container_name> --image <image_uri>Example command
$ kn container add sidecar --image docker.io/example/sidecarExample output
containers: - image: docker.io/example/sidecar name: sidecar resources: {}Chain two
commands together, and then pass them to akn container addcommand to create a Knative service with two containers:kn service create$ kn container add <first_container_name> --image <image_uri> | \ kn container add <second_container_name> --image <image_uri> | \ kn service create <service_name> --image <image_uri> --extra-containers -specifies a special case where--extra-containers -reads the pipe input instead of a YAML file.knExample command
$ kn container add sidecar --image docker.io/example/sidecar:first | \ kn container add second --image docker.io/example/sidecar:second | \ kn service create my-service --image docker.io/example/my-app:latest --extra-containers -The
flag can also accept a path to a YAML file:--extra-containers$ kn service create <service_name> --image <image_uri> --extra-containers <filename>Example command
$ kn service create my-service --image docker.io/example/my-app:latest --extra-containers my-extra-containers.yaml
4.4.4. kn domain commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following commands to create and manage domain mappings.
4.4.4.1. Creating a custom domain mapping by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can customize the domain for your Knative service by mapping a custom domain name that you own to a Knative service. You can use the Knative (
kn
DomainMapping
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on your cluster.
You have created a Knative service or route, and control a custom domain that you want to map to that CR.
NoteYour custom domain must point to the DNS of the OpenShift Container Platform cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
Procedure
Map a domain to a CR in the current namespace:
$ kn domain create <domain_mapping_name> --ref <target_name>Example command
$ kn domain create example.com --ref example-serviceThe
flag specifies an Addressable target CR for domain mapping.--refIf a prefix is not provided when using the
flag, it is assumed that the target is a Knative service in the current namespace.--refMap a domain to a Knative service in a specified namespace:
$ kn domain create <domain_mapping_name> --ref <ksvc:service_name:service_namespace>Example command
$ kn domain create example.com --ref ksvc:example-service:example-namespaceMap a domain to a Knative route:
$ kn domain create <domain_mapping_name> --ref <kroute:route_name>Example command
$ kn domain create example.com --ref kroute:example-route
4.4.4.2. Managing custom domain mappings by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
After you have created a
DomainMapping
kn
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on your cluster.
-
You have created at least one CR.
DomainMapping -
You have installed the Knative () CLI tool.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
Procedure
List existing
CRs:DomainMapping$ kn domain list -n <domain_mapping_namespace>View details of an existing
CR:DomainMapping$ kn domain describe <domain_mapping_name>Update a
CR to point to a new target:DomainMapping$ kn domain update --ref <target>Delete a
CR:DomainMapping$ kn domain delete <domain_mapping_name>
4.5. Knative Eventing CLI commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following Knative (
kn
4.5.1. kn source commands Copiar enlaceEnlace copiado en el portapapeles!
You can use the following commands to list, create, and manage Knative event sources.
4.5.1.1. Listing available event source types by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
Using the Knative (
kn
kn source list-types
Prerequisites
- The OpenShift Serverless Operator and Knative Eventing are installed on the cluster.
-
You have installed the Knative () CLI.
kn
Procedure
List the available event source types in the terminal:
$ kn source list-typesExample output
TYPE NAME DESCRIPTION ApiServerSource apiserversources.sources.knative.dev Watch and send Kubernetes API events to a sink PingSource pingsources.sources.knative.dev Periodically send ping events to a sink SinkBinding sinkbindings.sources.knative.dev Binding for connecting a PodSpecable to a sinkOptional: You can also list the available event source types in YAML format:
$ kn source list-types -o yaml
4.5.1.2. Knative CLI sink flag Copiar enlaceEnlace copiado en el portapapeles!
When you create an event source by using the Knative (
kn
--sink
The following example creates a sink binding that uses a service,
http://event-display.svc.cluster.local
Example command using the sink flag
$ kn source binding create bind-heartbeat \
--namespace sinkbinding-example \
--subject "Job:batch/v1:app=heartbeat-cron" \
--sink http://event-display.svc.cluster.local \
--ce-override "sink=bound"
- 1
svcinhttp://event-display.svc.cluster.localdetermines that the sink is a Knative service. Other default sink prefixes includechannel, andbroker.
4.5.1.3. Creating and managing container sources by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn source container
kn
Create a container source
$ kn source container create <container_source_name> --image <image_uri> --sink <sink>
Delete a container source
$ kn source container delete <container_source_name>
Describe a container source
$ kn source container describe <container_source_name>
List existing container sources
$ kn source container list
List existing container sources in YAML format
$ kn source container list -o yaml
Update a container source
This command updates the image URI for an existing container source:
$ kn source container update <container_source_name> --image <image_uri>
4.5.1.4. Creating an API server source by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn source apiserver create
kn
kn
Prerequisites
- The OpenShift Serverless Operator and Knative Eventing are installed on the cluster.
- You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
-
You have installed the OpenShift CLI ().
oc -
You have installed the Knative () CLI.
kn
If you want to re-use an existing service account, you can modify your existing
ServiceAccount
Create a service account, role, and role binding for the event source as a YAML file:
apiVersion: v1 kind: ServiceAccount metadata: name: events-sa namespace: default1 --- apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: event-watcher namespace: default2 rules: - apiGroups: - "" resources: - events verbs: - get - list - watch --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: k8s-ra-event-watcher namespace: default3 roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: event-watcher subjects: - kind: ServiceAccount name: events-sa namespace: default4 Apply the YAML file:
$ oc apply -f <filename>Create an API server source that has an event sink. In the following example, the sink is a broker:
$ kn source apiserver create <event_source_name> --sink broker:<broker_name> --resource "event:v1" --service-account <service_account_name> --mode ResourceTo check that the API server source is set up correctly, create a Knative service that dumps incoming messages to its log:
$ kn service create <service_name> --image quay.io/openshift-knative/knative-eventing-sources-event-display:latestIf you used a broker as an event sink, create a trigger to filter events from the
broker to the service:default$ kn trigger create <trigger_name> --sink ksvc:<service_name>Create events by launching a pod in the default namespace:
$ oc create deployment hello-node --image quay.io/openshift-knative/knative-eventing-sources-event-display:latestCheck that the controller is mapped correctly by inspecting the output generated by the following command:
$ kn source apiserver describe <source_name>Example output
Name: mysource Namespace: default Annotations: sources.knative.dev/creator=developer, sources.knative.dev/lastModifier=developer Age: 3m ServiceAccountName: events-sa Mode: Resource Sink: Name: default Namespace: default Kind: Broker (eventing.knative.dev/v1) Resources: Kind: event (v1) Controller: false Conditions: OK TYPE AGE REASON ++ Ready 3m ++ Deployed 3m ++ SinkProvided 3m ++ SufficientPermissions 3m ++ EventTypesProvided 3m
Verification
You can verify that the Kubernetes events were sent to Knative by looking at the message dumper function logs.
Get the pods:
$ oc get podsView the message dumper function logs for the pods:
$ oc logs $(oc get pod -o name | grep event-display) -c user-containerExample output
☁️ cloudevents.Event Validation: valid Context Attributes, specversion: 1.0 type: dev.knative.apiserver.resource.update datacontenttype: application/json ... Data, { "apiVersion": "v1", "involvedObject": { "apiVersion": "v1", "fieldPath": "spec.containers{hello-node}", "kind": "Pod", "name": "hello-node", "namespace": "default", ..... }, "kind": "Event", "message": "Started container", "metadata": { "name": "hello-node.159d7608e3a3572c", "namespace": "default", .... }, "reason": "Started", ... }
Deleting the API server source
Delete the trigger:
$ kn trigger delete <trigger_name>Delete the event source:
$ kn source apiserver delete <source_name>Delete the service account, cluster role, and cluster binding:
$ oc delete -f authentication.yaml
4.5.1.5. Creating a ping source by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn source ping create
kn
Prerequisites
- The OpenShift Serverless Operator, Knative Serving and Knative Eventing are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
-
Optional: If you want to use the verification steps for this procedure, install the OpenShift CLI ().
oc
Procedure
To verify that the ping source is working, create a simple Knative service that dumps incoming messages to the service logs:
$ kn service create event-display \ --image quay.io/openshift-knative/knative-eventing-sources-event-display:latestFor each set of ping events that you want to request, create a ping source in the same namespace as the event consumer:
$ kn source ping create test-ping-source \ --schedule "*/2 * * * *" \ --data '{"message": "Hello world!"}' \ --sink ksvc:event-displayCheck that the controller is mapped correctly by entering the following command and inspecting the output:
$ kn source ping describe test-ping-sourceExample output
Name: test-ping-source Namespace: default Annotations: sources.knative.dev/creator=developer, sources.knative.dev/lastModifier=developer Age: 15s Schedule: */2 * * * * Data: {"message": "Hello world!"} Sink: Name: event-display Namespace: default Resource: Service (serving.knative.dev/v1) Conditions: OK TYPE AGE REASON ++ Ready 8s ++ Deployed 8s ++ SinkProvided 15s ++ ValidSchedule 15s ++ EventTypeProvided 15s ++ ResourcesCorrect 15s
Verification
You can verify that the Kubernetes events were sent to the Knative event sink by looking at the logs of the sink pod.
By default, Knative services terminate their pods if no traffic is received within a 60 second period. The example shown in this guide creates a ping source that sends a message every 2 minutes, so each message should be observed in a newly created pod.
Watch for new pods created:
$ watch oc get podsCancel watching the pods using Ctrl+C, then look at the logs of the created pod:
$ oc logs $(oc get pod -o name | grep event-display) -c user-containerExample output
☁️ cloudevents.Event Validation: valid Context Attributes, specversion: 1.0 type: dev.knative.sources.ping source: /apis/v1/namespaces/default/pingsources/test-ping-source id: 99e4f4f6-08ff-4bff-acf1-47f61ded68c9 time: 2020-04-07T16:16:00.000601161Z datacontenttype: application/json Data, { "message": "Hello world!" }
Deleting the ping source
Delete the ping source:
$ kn delete pingsources.sources.knative.dev <ping_source_name>
4.5.1.6. Creating a Kafka event source by using the Knative CLI Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn source kafka create
kn
Prerequisites
-
The OpenShift Serverless Operator, Knative Eventing, Knative Serving, and the custom resource (CR) are installed on your cluster.
KnativeKafka - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You have access to a Red Hat AMQ Streams (Kafka) cluster that produces the Kafka messages you want to import.
-
You have installed the Knative () CLI.
kn -
Optional: You have installed the OpenShift CLI () if you want to use the verification steps in this procedure.
oc
Procedure
To verify that the Kafka event source is working, create a Knative service that dumps incoming events into the service logs:
$ kn service create event-display \ --image quay.io/openshift-knative/knative-eventing-sources-event-displayCreate a
CR:KafkaSource$ kn source kafka create <kafka_source_name> \ --servers <cluster_kafka_bootstrap>.kafka.svc:9092 \ --topics <topic_name> --consumergroup my-consumer-group \ --sink event-displayNoteReplace the placeholder values in this command with values for your source name, bootstrap servers, and topics.
The
,--servers, and--topicsoptions specify the connection parameters to the Kafka cluster. The--consumergroupoption is optional.--consumergroupOptional: View details about the
CR you created:KafkaSource$ kn source kafka describe <kafka_source_name>Example output
Name: example-kafka-source Namespace: kafka Age: 1h BootstrapServers: example-cluster-kafka-bootstrap.kafka.svc:9092 Topics: example-topic ConsumerGroup: example-consumer-group Sink: Name: event-display Namespace: default Resource: Service (serving.knative.dev/v1) Conditions: OK TYPE AGE REASON ++ Ready 1h ++ Deployed 1h ++ SinkProvided 1h
Verification steps
Trigger the Kafka instance to send a message to the topic:
$ oc -n kafka run kafka-producer \ -ti --image=quay.io/strimzi/kafka:latest-kafka-2.7.0 --rm=true \ --restart=Never -- bin/kafka-console-producer.sh \ --broker-list <cluster_kafka_bootstrap>:9092 --topic my-topicEnter the message in the prompt. This command assumes that:
-
The Kafka cluster is installed in the namespace.
kafka -
The object has been configured to use the
KafkaSourcetopic.my-topic
-
The Kafka cluster is installed in the
Verify that the message arrived by viewing the logs:
$ oc logs $(oc get pod -o name | grep event-display) -c user-containerExample output
☁️ cloudevents.Event Validation: valid Context Attributes, specversion: 1.0 type: dev.knative.kafka.event source: /apis/v1/namespaces/default/kafkasources/example-kafka-source#example-topic subject: partition:46#0 id: partition:46/offset:0 time: 2021-03-10T11:21:49.4Z Extensions, traceparent: 00-161ff3815727d8755848ec01c866d1cd-7ff3916c44334678-00 Data, Hello!
4.6. Functions commands Copiar enlaceEnlace copiado en el portapapeles!
4.6.1. Creating functions Copiar enlaceEnlace copiado en el portapapeles!
Before you can build and deploy a function, you must create it by using the Knative (
kn
-c
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn
Procedure
Create a function project:
$ kn func create -r <repository> -l <runtime> -t <template> <path>-
Accepted runtime values include ,
quarkus,node,typescript,go,python, andspringboot.rust Accepted template values include
andhttp.cloudeventsExample command
$ kn func create -l typescript -t cloudevents examplefuncExample output
Created typescript function in /home/user/demo/examplefuncAlternatively, you can specify a repository that contains a custom template.
Example command
$ kn func create -r https://github.com/boson-project/templates/ -l node -t hello-world examplefuncExample output
Created node function in /home/user/demo/examplefunc
-
Accepted runtime values include
4.6.2. Running a function locally Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn func run
--path
kn func run
Example command to run a function in the current directory
$ kn func run
Example command to run a function in a directory specified as a path
$ kn func run --path=<directory_path>
You can also force a rebuild of an existing image before running the function, even if there have been no changes to the project files, by using the
--build
Example run command using the build flag
$ kn func run --build
If you set the
build
Example run command using the build flag
$ kn func run --build=false
You can use the help command to learn more about
kn func run
Build help command
$ kn func help run
4.6.3. Building functions Copiar enlaceEnlace copiado en el portapapeles!
Before you can run a function, you must build the function project. If you are using the
kn func run
kn func build
The
kn func build
4.6.3.1. Image container types Copiar enlaceEnlace copiado en el portapapeles!
By default,
kn func build
Example build command using Red Hat Source-to-Image (S2I)
$ kn func build
4.6.3.2. Image registry types Copiar enlaceEnlace copiado en el portapapeles!
The OpenShift Container Registry is used by default as the image registry for storing function images.
Example build command using OpenShift Container Registry
$ kn func build
Example output
Building function image
Function image has been built, image: registry.redhat.io/example/example-function:latest
You can override using OpenShift Container Registry as the default image registry by using the
--registry
Example build command overriding OpenShift Container Registry to use quay.io
$ kn func build --registry quay.io/username
Example output
Building function image
Function image has been built, image: quay.io/username/example-function:latest
4.6.3.3. Push flag Copiar enlaceEnlace copiado en el portapapeles!
You can add the
--push
kn func build
Example build command using OpenShift Container Registry
$ kn func build --push
4.6.3.4. Help command Copiar enlaceEnlace copiado en el portapapeles!
You can use the help command to learn more about
kn func build
Build help command
$ kn func help build
4.6.4. Deploying functions Copiar enlaceEnlace copiado en el portapapeles!
You can deploy a function to your cluster as a Knative service by using the
kn func deploy
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You must have already created and initialized the function that you want to deploy.
Procedure
Deploy a function:
$ kn func deploy [-n <namespace> -p <path> -i <image>]Example output
Function deployed at: http://func.example.com-
If no is specified, the function is deployed in the current namespace.
namespace -
The function is deployed from the current directory, unless a is specified.
path - The Knative service name is derived from the project name, and cannot be changed using this command.
-
If no
4.6.5. Listing existing functions Copiar enlaceEnlace copiado en el portapapeles!
You can list existing functions by using
kn func list
kn service list
Procedure
List existing functions:
$ kn func list [-n <namespace> -p <path>]Example output
NAME NAMESPACE RUNTIME URL READY example-function default node http://example-function.default.apps.ci-ln-g9f36hb-d5d6b.origin-ci-int-aws.dev.rhcloud.com TrueList functions deployed as Knative services:
$ kn service list -n <namespace>Example output
NAME URL LATEST AGE CONDITIONS READY REASON example-function http://example-function.default.apps.ci-ln-g9f36hb-d5d6b.origin-ci-int-aws.dev.rhcloud.com example-function-gzl4c 16m 3 OK / 3 True
4.6.6. Describing a function Copiar enlaceEnlace copiado en el portapapeles!
The
kn func info
Procedure
Describe a function:
$ kn func info [-f <format> -n <namespace> -p <path>]Example command
$ kn func info -p function/example-functionExample output
Function name: example-function Function is built in image: docker.io/user/example-function:latest Function is deployed as Knative Service: example-function Function is deployed in namespace: default Routes: http://example-function.default.apps.ci-ln-g9f36hb-d5d6b.origin-ci-int-aws.dev.rhcloud.com
4.6.7. Invoking a deployed function with a test event Copiar enlaceEnlace copiado en el portapapeles!
You can use the
kn func invoke
Prerequisites
- The OpenShift Serverless Operator and Knative Serving are installed on the cluster.
-
You have installed the Knative () CLI.
kn - You have created a project or have access to a project with the appropriate roles and permissions to create applications and other workloads in OpenShift Container Platform.
- You must have already deployed the function that you want to invoke.
Procedure
Invoke a function:
$ kn func invoke-
The command only works when there is either a local container image currently running, or when there is a function deployed in the cluster.
kn func invoke -
The command executes on the local directory by default, and assumes that this directory is a function project.
kn func invoke
-
The
4.6.7.1. kn func invoke optional parameters Copiar enlaceEnlace copiado en el portapapeles!
You can specify optional parameters for the request by using the following
kn func invoke
| Flags | Description |
|---|---|
|
| Specifies the target instance of the invoked function, for example,
|
|
| Specifies the format of the message, for example,
|
|
| Specifies a unique string identifier for the request. |
|
| Specifies the namespace on the cluster. |
|
| Specifies sender name for the request. This corresponds to the CloudEvent
|
|
| Specifies the type of request, for example,
|
|
| Specifies content for the request. For CloudEvent requests, this is the CloudEvent
|
|
| Specifies path to a local file containing data to be sent. |
|
| Specifies the MIME content type for the request. |
|
| Specifies path to the project directory. |
|
| Enables prompting to interactively confirm all options. |
|
| Enables printing verbose output. |
|
| Prints information on usage of
|
4.6.7.1.1. Main parameters Copiar enlaceEnlace copiado en el portapapeles!
The following parameters define the main properties of the
kn func invoke
- Event target (
-t,--target) -
The target instance of the invoked function. Accepts the
localvalue for a locally deployed function, theremotevalue for a remotely deployed function, or a URL for a function deployed to an arbitrary endpoint. If a target is not specified, it defaults tolocal. - Event message format (
-f,--format) -
The message format for the event, such as
httporcloudevent. This defaults to the format of the template that was used when creating the function. - Event type (
--type) -
The type of event that is sent. You can find information about the
typeparameter that is set in the documentation for each event producer. For example, the API server source might set thetypeparameter of produced events asdev.knative.apiserver.resource.update. - Event source (
--source) -
The unique event source that produced the event. This might be a URI for the event source, for example
https://10.96.0.1/, or the name of the event source. - Event ID (
--id) - A random, unique ID that is created by the event producer.
- Event data (
--data) Allows you to specify a
value for the event sent by thedatacommand. For example, you can specify akn func invokevalue such as--dataso that the event contains this data string. By default, no data is included in the events created by"Hello World".kn func invokeNoteFunctions that have been deployed to a cluster can respond to events from an existing event source that provides values for properties such as
andsource. These events often have atypevalue in JSON format, which captures the domain specific context of the event. By using the CLI flags noted in this document, developers can simulate those events for local testing.dataYou can also send event data using the
flag to provide a local file containing data for the event. In this case, specify the content type using--file.--content-type- Data content type (
--content-type) -
If you are using the
--dataflag to add data for events, you can use the--content-typeflag to specify what type of data is carried by the event. In the previous example, the data is plain text, so you might specifykn func invoke --data "Hello world!" --content-type "text/plain".
4.6.7.1.2. Example commands Copiar enlaceEnlace copiado en el portapapeles!
This is the general invocation of the
kn func invoke
$ kn func invoke --type <event_type> --source <event_source> --data <event_data> --content-type <content_type> --id <event_ID> --format <format> --namespace <namespace>
For example, to send a "Hello world!" event, you can run:
$ kn func invoke --type ping --source example-ping --data "Hello world!" --content-type "text/plain" --id example-ID --format http --namespace my-ns
4.6.7.1.2.1. Specifying the file with data Copiar enlaceEnlace copiado en el portapapeles!
To specify the file on disk that contains the event data, use the
--file
--content-type
$ kn func invoke --file <path> --content-type <content-type>
For example, to send JSON data stored in the
test.json
$ kn func invoke --file ./test.json --content-type application/json
4.6.7.1.2.2. Specifying the function project Copiar enlaceEnlace copiado en el portapapeles!
You can specify a path to the function project by using the
--path
$ kn func invoke --path <path_to_function>
For example, to use the function project located in the
./example/example-function
$ kn func invoke --path ./example/example-function
4.6.7.1.2.3. Specifying where the target function is deployed Copiar enlaceEnlace copiado en el portapapeles!
By default,
kn func invoke
$ kn func invoke
To use a different deployment, use the
--target
$ kn func invoke --target <target>
For example, to use the function deployed on the cluster, use the
--target remote
$ kn func invoke --target remote
To use the function deployed at an arbitrary URL, use the
--target <URL>
$ kn func invoke --target "https://my-event-broker.example.com"
You can explicitly target the local deployment. In this case, if the function is not running locally, the command fails:
$ kn func invoke --target local
4.6.8. Deleting a function Copiar enlaceEnlace copiado en el portapapeles!
You can delete a function by using the
kn func delete
Procedure
Delete a function:
$ kn func delete [<function_name> -n <namespace> -p <path>]-
If the name or path of the function to delete is not specified, the current directory is searched for a file that is used to determine the function to delete.
func.yaml -
If the namespace is not specified, it defaults to the value in the
namespacefile.func.yaml
-
If the name or path of the function to delete is not specified, the current directory is searched for a