Templates

You are viewing documentation for a release that is no longer supported. The latest supported version of version 3 is [3.11]. For the most recent version 4, see [4]

You are viewing documentation for a release that is no longer supported. The latest supported version of version 3 is [3.11]. For the most recent version 4, see [4]

Overview

A template describes a set of objects that can be parameterized and processed to produce a list of objects for creation by OKD. A template can be processed to create anything you have permission to create within a project, for example services, build configurations, and deployment configurations. A template may also define a set of labels to apply to every object defined in the template.

You can create a list of objects from a template using the CLI or, if a template has been uploaded to your project or the global template library, using the web console. For a curated set of templates, see the OpenShift Image Streams and Templates library.

Uploading a Template

If you have a JSON or YAML file that defines a template, for example as seen in this example, you can upload the template to projects using the CLI. This saves the template to the project for repeated use by any user with appropriate access to that project. Instructions on writing your own templates are provided later in this topic.

To upload a template to your current project’s template library, pass the JSON or YAML file with the following command:

  1. $ oc create -f <filename>

You can upload a template to a different project using the -n option with the name of the project:

  1. $ oc create -f <filename> -n <project>

The template is now available for selection using the web console or the CLI.

Creating from Templates Using the Web Console

See Creating an Application Using the Web Console.

Creating from Templates Using the CLI

You can use the CLI to process templates and use the configuration that is generated to create objects.

Labels

Labels are used to manage and organize generated objects, such as pods. The labels specified in the template are applied to every object that is generated from the template.

There is also the ability to add labels in the template from the command line.

  1. $ oc process -f <filename> -l name=otherLabel

Parameters

The list of parameters that you can override are listed in the parameters section of the template. You can list them with the CLI by using the following command and specifying the file to be used:

  1. $ oc process --parameters -f <filename>

Alternatively, if the template is already uploaded:

  1. $ oc process --parameters -n <project> <template_name>

For example, the following shows the output when listing the parameters for one of the Quickstart templates in the default openshift project:

  1. $ oc process --parameters -n openshift rails-postgresql-example
  2. NAME DESCRIPTION GENERATOR VALUE
  3. SOURCE_REPOSITORY_URL The URL of the repository with your application source code https://github.com/sclorg/rails-ex.git
  4. SOURCE_REPOSITORY_REF Set this to a branch name, tag or other ref of your repository if you are not using the default branch
  5. CONTEXT_DIR Set this to the relative path to your project if it is not in the root of your repository
  6. APPLICATION_DOMAIN The exposed hostname that will route to the Rails service rails-postgresql-example.openshiftapps.com
  7. GITHUB_WEBHOOK_SECRET A secret string used to configure the GitHub webhook expression [a-zA-Z0-9]{40}
  8. SECRET_KEY_BASE Your secret key for verifying the integrity of signed cookies expression [a-z0-9]{127}
  9. APPLICATION_USER The application user that is used within the sample application to authorize access on pages openshift
  10. APPLICATION_PASSWORD The application password that is used within the sample application to authorize access on pages secret
  11. DATABASE_SERVICE_NAME Database service name postgresql
  12. POSTGRESQL_USER database username expression user[A-Z0-9]{3}
  13. POSTGRESQL_PASSWORD database password expression [a-zA-Z0-9]{8}
  14. POSTGRESQL_DATABASE database name root
  15. POSTGRESQL_MAX_CONNECTIONS database max connections 10
  16. POSTGRESQL_SHARED_BUFFERS database shared buffers 12MB

The output identifies several parameters that are generated with a regular expression-like generator when the template is processed.

Generating a List of Objects

Using the CLI, you can process a file defining a template to return the list of objects to standard output:

  1. $ oc process -f <filename>

Alternatively, if the template has already been uploaded to the current project:

  1. $ oc process <template_name>

You can create objects from a template by processing the template and piping the output to oc create:

  1. $ oc process -f <filename> | oc create -f -

Alternatively, if the template has already been uploaded to the current project:

  1. $ oc process <template> | oc create -f -

You can override any parameter values defined in the file by adding the -p option for each <name>=<value> pair you want to override. A parameter reference may appear in any text field inside the template items.

For example, in the following the POSTGRESQL_USER and POSTGRESQL_DATABASE parameters of a template are overridden to output a configuration with customized environment variables:

Example 1. Creating a List of Objects from a Template

  1. $ oc process -f my-rails-postgresql \
  2. -p POSTGRESQL_USER=bob \
  3. -p POSTGRESQL_DATABASE=mydatabase

The JSON file can either be redirected to a file or applied directly without uploading the template by piping the processed output to the oc create command:

  1. $ oc process -f my-rails-postgresql \
  2. -p POSTGRESQL_USER=bob \
  3. -p POSTGRESQL_DATABASE=mydatabase \
  4. | oc create -f -

If you have large number of parameters, you can store them in a file and then pass this file to oc process:

  1. $ cat postgres.env
  2. POSTGRESQL_USER=bob
  3. POSTGRESQL_DATABASE=mydatabase
  4. $ oc process -f my-rails-postgresql --param-file=postgres.env

You can also read the environment from standard input by using "-" as the argument to --param-file:

  1. $ sed s/bob/alice/ postgres.env | oc process -f my-rails-postgresql --param-file=-

Modifying an Uploaded Template

You can edit a template that has already been uploaded to your project by using the following command:

  1. $ oc edit template <template>

Using the Instant App and Quickstart Templates

OKD provides a number of default Instant App and Quickstart templates to make it easy to quickly get started creating a new application for different languages. Templates are provided for Rails (Ruby), Django (Python), Node.js, CakePHP (PHP), and Dancer (Perl). Your cluster administrator should have created these templates in the default, global openshift project so you have access to them. You can list the available default Instant App and Quickstart templates with:

  1. $ oc get templates -n openshift

If they are not available, direct your cluster administrator to the Loading the Default Image Streams and Templates topic.

By default, the templates build using a public source repository on GitHub that contains the necessary application code. In order to be able to modify the source and build your own version of the application, you must:

  1. Fork the repository referenced by the template’s default SOURCE_REPOSITORY_URL parameter.

  2. Override the value of the SOURCE_REPOSITORY_URL parameter when creating from the template, specifying your fork instead of the default value.

By doing this, the build configuration created by the template will now point to your fork of the application code, and you can modify the code and rebuild the application at will.

A walkthrough of this process using the web console is provided in Getting Started for Developers: Web Console.

Some of the Instant App and Quickstart templates define a database deployment configuration. The configuration they define uses ephemeral storage for the database content. These templates should be used for demonstration purposes only as all database data will be lost if the database pod restarts for any reason.

Writing Templates

You can define new templates to make it easy to recreate all the objects of your application. The template will define the objects it creates along with some metadata to guide the creation of those objects.

Example 2. A Simple Template Object Definition (YAML)

  1. apiVersion: v1
  2. kind: Template
  3. metadata:
  4. name: redis-template
  5. annotations:
  6. description: "Description"
  7. iconClass: "icon-redis"
  8. tags: "database,nosql"
  9. objects:
  10. - apiVersion: v1
  11. kind: Pod
  12. metadata:
  13. name: redis-master
  14. spec:
  15. containers:
  16. - env:
  17. - name: REDIS_PASSWORD
  18. value: ${REDIS_PASSWORD}
  19. image: dockerfile/redis
  20. name: master
  21. ports:
  22. - containerPort: 6379
  23. protocol: TCP
  24. parameters:
  25. - description: Password used for Redis authentication
  26. from: '[A-Z0-9]{8}'
  27. generate: expression
  28. name: REDIS_PASSWORD
  29. labels:
  30. redis: master

Description

The template description informs users what the template does and helps them find it when searching in the web console. Additional metadata beyond the template name is optional, but useful to have. In addition to general descriptive information, the metadata also includes a set of tags. Useful tags include the name of the language the template is related to (for example, java, php, ruby, and so on).

Example 3. Template Description Metadata

  1. kind: Template
  2. apiVersion: v1
  3. metadata:
  4. name: cakephp-mysql-example (1)
  5. annotations:
  6. openshift.io/display-name: "CakePHP MySQL Example (Ephemeral)" (2)
  7. description: >-
  8. An example CakePHP application with a MySQL database. For more information
  9. about using this template, including OpenShift considerations, see
  10. https://github.com/sclorg/cakephp-ex/blob/master/README.md.
  11. WARNING: Any data stored will be lost upon pod destruction. Only use this
  12. template for testing." (3)
  13. openshift.io/long-description: >-
  14. This template defines resources needed to develop a CakePHP application,
  15. including a build configuration, application deployment configuration, and
  16. database deployment configuration. The database is stored in
  17. non-persistent storage, so this configuration should be used for
  18. experimental purposes only. (4)
  19. tags: "quickstart,php,cakephp" (5)
  20. iconClass: icon-php (6)
  21. openshift.io/provider-display-name: "Red Hat, Inc." (7)
  22. openshift.io/documentation-url: "https://github.com/sclorg/cakephp-ex" (8)
  23. openshift.io/support-url: "https://access.redhat.com" (9)
  24. message: "Your admin credentials are ${ADMIN_USERNAME}:${ADMIN_PASSWORD}" (10)
1The unique name of the template.
2A brief, user-friendly name, which can be employed by user interfaces.
3A description of the template. Include enough detail that the user will understand what is being deployed and any caveats they need to know before deploying. It should also provide links to additional information, such as a README file. Newlines can be included to create paragraphs.
4Additional template description. This may be displayed by the service catalog, for example.
5Tags to be associated with the template for searching and grouping. Add tags that will include it into one of the provided catalog categories. Refer to the id and categoryAliases in CATALOG_CATEGORIES in the console’s constants file. The categories can also be customized for the whole cluster.
6An icon to be displayed with your template in the web console. Choose from our existing logo icons when possible. You can also use icons from FontAwesome and PatternFly. Alternatively, provide icons through CSS customizations that can be added to an OKD cluster that uses your template. You must specify an icon class that exists, or it will prevent falling back to the generic icon.
7The name of the person or organization providing the template.
8A URL referencing further documentation for the template.
9A URL where support can be obtained for the template.
10An instructional message that is displayed when this template is instantiated. This field should inform the user how to use the newly created resources. Parameter substitution is performed on the message before being displayed so that generated credentials and other parameters can be included in the output. Include links to any next-steps documentation that users should follow.

Labels

Templates can include a set of labels. These labels will be added to each object created when the template is instantiated. Defining a label in this way makes it easy for users to find and manage all the objects created from a particular template.

Example 4. Template Object Labels

  1. kind: "Template"
  2. apiVersion: "v1"
  3. ...
  4. labels:
  5. template: "cakephp-mysql-example" (1)
  6. app: "${NAME}" (2)
1A label that will be applied to all objects created from this template.
2A parameterized label that will also be applied to all objects created from this template. Parameter expansion is carried out on both label keys and values.

Parameters

Parameters allow a value to be supplied by the user or generated when the template is instantiated. Then, that value is substituted wherever the parameter is referenced. References can be defined in any field in the objects list field. This is useful for generating random passwords or allowing the user to supply a host name or other user-specific value that is required to customize the template. Parameters can be referenced in two ways:

  • As a string value by placing values in the form ${PARAMETER_NAME} in any string field in the template.

  • As a json/yaml value by placing values in the form ${{PARAMETER_NAME}} in place of any field in the template.

When using the ${PARAMETER_NAME} syntax, multiple parameter references can be combined in a single field and the reference can be embedded within fixed data, such as http://${PARAMETER\_1}${PARAMETER\_2}. Both parameter values will be substituted and the resulting value will be a quoted string.

When using the ${{PARAMETER_NAME}} syntax only a single parameter reference is allowed and leading/trailing characters are not permitted. The resulting value will be unquoted unless, after substitution is performed, the result is not a valid json object. If the result is not a valid json value, the resulting value will be quoted and treated as a standard string.

A single parameter can be referenced multiple times within a template and it can be referenced using both substitution syntaxes within a single template.

A default value can be provided, which is used if the user does not supply a different value:

Example 5. Setting an Explicit Value as the Default Value

  1. parameters:
  2. - name: USERNAME
  3. description: "The user name for Joe"
  4. value: joe

Parameter values can also be generated based on rules specified in the parameter definition:

Example 6. Generating a Parameter Value

  1. parameters:
  2. - name: PASSWORD
  3. description: "The random user password"
  4. generate: expression
  5. from: "[a-zA-Z0-9]{12}"

In the example above, processing will generate a random password 12 characters long consisting of all upper and lowercase alphabet letters and numbers.

The syntax available is not a full regular expression syntax. However, you can use \w, \d, and \a modifiers:

  • [\w]{10} produces 10 alphabet characters, numbers, and underscores. This follows the PCRE standard and is equal to [a-zA-Z0-9_]{10}.

  • [\d]{10} produces 10 numbers. This is equal to [0-9]{10}.

  • [\a]{10} produces 10 alphabetical characters. This is equal to [a-zA-Z]{10}.

Here is an example of a full template with parameter definitions and references:

Example 7. A full template with parameter definitions and references

  1. kind: Template
  2. apiVersion: v1
  3. metadata:
  4. name: my-template
  5. objects:
  6. - kind: BuildConfig
  7. apiVersion: v1
  8. metadata:
  9. name: cakephp-mysql-example
  10. annotations:
  11. description: Defines how to build the application
  12. spec:
  13. source:
  14. type: Git
  15. git:
  16. uri: "${SOURCE_REPOSITORY_URL}" (1)
  17. ref: "${SOURCE_REPOSITORY_REF}"
  18. contextDir: "${CONTEXT_DIR}"
  19. - kind: DeploymentConfig
  20. apiVersion: v1
  21. metadata:
  22. name: frontend
  23. spec:
  24. replicas: "${{REPLICA_COUNT}}" (2)
  25. parameters:
  26. - name: SOURCE_REPOSITORY_URL (3)
  27. displayName: Source Repository URL (4)
  28. description: The URL of the repository with your application source code (5)
  29. value: https://github.com/sclorg/cakephp-ex.git (6)
  30. required: true (7)
  31. - name: GITHUB_WEBHOOK_SECRET
  32. description: A secret string used to configure the GitHub webhook
  33. generate: expression (8)
  34. from: "[a-zA-Z0-9]{40}" (9)
  35. - name: REPLICA_COUNT
  36. description: Number of replicas to run
  37. value: "2"
  38. required: true
  39. message: "... The GitHub webhook secret is ${GITHUB_WEBHOOK_SECRET} ..." (10)
1This value will be replaced with the value of the SOURCE_REPOSITORY_URL parameter when the template is instantiated.
2This value will be replaced with the unquoted value of the REPLICA_COUNT parameter when the template is instantiated.
3The name of the parameter. This value is used to reference the parameter within the template.
4The user-friendly name for the parameter. This will be displayed to users.
5A description of the parameter. Provide more detailed information for the purpose of the parameter, including any constraints on the expected value. Descriptions should use complete sentences to follow the console’s text standards. Don’t make this a duplicate of the display name.
6A default value for the parameter which will be used if the user does not override the value when instantiating the template. Avoid using default values for things like passwords, instead use generated parameters in combination with Secrets.
7Indicates this parameter is required, meaning the user cannot override it with an empty value. If the parameter does not provide a default or generated value, the user must supply a value.
8A parameter which has its value generated.
9The input to the generator. In this case, the generator will produce a 40 character alphanumeric value including upper and lowercase characters.
10Parameters can be included in the template message. This informs the user about generated values.

Object List

The main portion of the template is the list of objects which will be created when the template is instantiated. This can be any valid API object, such as a BuildConfig, DeploymentConfig, Service, etc. The object will be created exactly as defined here, with any parameter values substituted in prior to creation. The definition of these objects can reference parameters defined earlier.

  1. kind: "Template"
  2. apiVersion: "v1"
  3. metadata:
  4. name: my-template
  5. objects:
  6. - kind: "Service" (1)
  7. apiVersion: "v1"
  8. metadata:
  9. name: "cakephp-mysql-example"
  10. annotations:
  11. description: "Exposes and load balances the application pods"
  12. spec:
  13. ports:
  14. - name: "web"
  15. port: 8080
  16. targetPort: 8080
  17. selector:
  18. name: "cakephp-mysql-example"
1The definition of a Service which will be created by this template.

If an object definition’s metadata includes a fixed namespace field value, the field will be stripped out of the definition during template instantiation. If the namespace field contains a parameter reference, normal parameter substitution will be performed and the object will be created in whatever namespace the parameter substitution resolved the value to, assuming the user has permission to create objects in that namespace.

Marking Templates as Bindable

The template service broker advertises one service in its catalog for each Template object that it is aware of. By default, each of these services is advertised as being “bindable”, meaning an end user is permitted to bind against the provisioned service.

Template authors can prevent end users from binding against services provisioned from a given Template by adding the annotation template.openshift.io/bindable: "false" to the Template.

Exposing Object Fields

Template authors can indicate that fields of particular objects in a template should be exposed. The template service broker recognizes exposed fields on ConfigMap, Secret, Service and Route objects, and returns the values of the exposed fields when a user binds a service backed by the broker.

To expose one or more fields of an object, add annotations prefixed by template.openshift.io/expose- or template.openshift.io/base64-expose- to the object in the template.

Each annotation key, with its prefix removed, is passed through to become a key in a bind response.

Each annotation value is a Kubernetes JSONPath expression, which is resolved at bind time to indicate the object field whose value should be returned in the bind response.

Bind response key/value pairs can be used in other parts of the system as environment variables. Therefore, it is recommended that every annotation key with its prefix removed should be a valid environment variable name — beginning with a character A-Z, a-z, or underscore, and being followed by zero or more characters A-Z, a-z, 0-9, or underscore.

Use the template.openshift.io/expose- annotation to return the field value as a string. This is convenient, although it does not handle arbitrary binary data. If you want to return binary data, use the template.openshift.io/base64-expose- annotation instead to base64 encode the data before it is returned.

Unless escaped with a backslash, Kubernetes’ JSONPath implementation interprets characters such as ., @, and others as metacharacters, regardless of their position in the expression. Therefore, for example, to refer to a ConfigMap datum named my.key, the required JSONPath expression would be {.data[‘my.key’]}. Depending on how the JSONPath expression is then written in YAML, an additional backslash might be required, for example “{.data[‘my\.key’]}”.

The following is an example of different objects’ fields being exposed:

  1. kind: Template
  2. apiVersion: v1
  3. metadata:
  4. name: my-template
  5. objects:
  6. - kind: ConfigMap
  7. apiVersion: v1
  8. metadata:
  9. name: my-template-config
  10. annotations:
  11. template.openshift.io/expose-username: "{.data['my\\.username']}"
  12. data:
  13. my.username: foo
  14. - kind: Secret
  15. apiVersion: v1
  16. metadata:
  17. name: my-template-config-secret
  18. annotations:
  19. template.openshift.io/base64-expose-password: "{.data['password']}"
  20. stringData:
  21. password: bar
  22. - kind: Service
  23. apiVersion: v1
  24. metadata:
  25. name: my-template-service
  26. annotations:
  27. template.openshift.io/expose-service_ip_port: "{.spec.clusterIP}:{.spec.ports[?(.name==\"web\")].port}"
  28. spec:
  29. ports:
  30. - name: "web"
  31. port: 8080
  32. - kind: Route
  33. apiVersion: v1
  34. metadata:
  35. name: my-template-route
  36. annotations:
  37. template.openshift.io/expose-uri: "http://{.spec.host}{.spec.path}"
  38. spec:
  39. path: mypath

An example response to a bind operation given the above partial template follows:

  1. {
  2. "credentials": {
  3. "username": "foo",
  4. "password": "YmFy",
  5. "service_ip_port": "172.30.12.34:8080",
  6. "uri": "http://route-test.router.default.svc.cluster.local/mypath"
  7. }
  8. }

Waiting for Template Readiness

Template authors can indicate that certain objects within a template should be waited for before a template instantiation by the service catalog, Template Service Broker, or TemplateInstance API is considered complete.

To use this feature, mark one or more objects of kind Build, BuildConfig, Deployment, DeploymentConfig, Job, or StatefulSet in a template with the following annotation:

  1. "template.alpha.openshift.io/wait-for-ready": "true"

Template instantiation will not complete until all objects marked with the annotation report ready. Similarly, if any of the annotated objects report failed, or if the template fails to become ready within a fixed timeout of one hour, the template instantiation will fail.

For the purposes of instantiation, readiness and failure of each object kind are defined as follows:

KindReadinessFailure

Build

Object reports phase Complete

Object reports phase Canceled, Error, or Failed

BuildConfig

Latest associated Build object reports phase Complete

Latest associated Build object reports phase Canceled, Error, or Failed

Deployment

Object reports new ReplicaSet and deployment available (this honors readiness probes defined on the object)

Object reports Progressing condition as false

DeploymentConfig

Object reports new ReplicationController and deployment available (this honors readiness probes defined on the object)

Object reports Progressing condition as false

Job

Object reports completion

Object reports that one or more failures have occurred

StatefulSet

Object reports all replicas ready (this honors readiness probes defined on the object)

Not applicable

The following is an example template extract, which uses the wait-for-ready annotation. Further examples can be found in the OpenShift quickstart templates.

  1. kind: Template
  2. apiVersion: v1
  3. metadata:
  4. name: my-template
  5. objects:
  6. - kind: BuildConfig
  7. apiVersion: v1
  8. metadata:
  9. name: ...
  10. annotations:
  11. # wait-for-ready used on BuildConfig ensures that template instantiation
  12. # will fail immediately if build fails
  13. template.alpha.openshift.io/wait-for-ready: "true"
  14. spec:
  15. ...
  16. - kind: DeploymentConfig
  17. apiVersion: v1
  18. metadata:
  19. name: ...
  20. annotations:
  21. template.alpha.openshift.io/wait-for-ready: "true"
  22. spec:
  23. ...
  24. - kind: Service
  25. apiVersion: v1
  26. metadata:
  27. name: ...
  28. spec:
  29. ...

Other Recommendations

  • Set memory, CPU, and storage default sizes to make sure your application is given enough resources to run smoothly.

  • Avoid referencing the latest tag from images if that tag is used across major versions. This may cause running applications to break when new images are pushed to that tag.

  • A good template builds and deploys cleanly without requiring modifications after the template is deployed.

Creating a Template from Existing Objects

Rather than writing an entire template from scratch, you can export existing objects from your project in YAML form, and then modify the YAML from there by adding parameters and other customizations as template form. To export objects in a project in YAML form, run:

  1. $ oc get -o yaml --export all > <yaml_filename>

You can also substitute a particular resource type or multiple resources instead of all. Run oc get -h for more examples.

The object types included in oc get --export all are:

  • BuildConfig

  • Build

  • DeploymentConfig

  • ImageStream

  • Pod

  • ReplicationController

  • Route

  • Service