Questo contenuto non è disponibile nella lingua selezionata.
Chapter 2. Builds
2.1. Understanding image builds Copia collegamentoCollegamento copiato negli appunti!
2.1.1. Builds Copia collegamentoCollegamento copiato negli appunti!
A build is the process of transforming input parameters into a resulting object. Most often, the process is used to transform input parameters or source code into a runnable image. A
BuildConfig
OpenShift Container Platform uses Kubernetes by creating containers from build images and pushing them to a container image registry.
Build objects share common characteristics including inputs for a build, the requirement to complete a build process, logging the build process, publishing resources from successful builds, and publishing the final status of the build. Builds take advantage of resource restrictions, specifying limitations on resources such as CPU usage, memory usage, and build or pod execution time.
The OpenShift Container Platform build system provides extensible support for build strategies that are based on selectable types specified in the build API. There are three primary build strategies available:
- Docker build
- Source-to-image (S2I) build
- Custom build
By default, docker builds and S2I builds are supported.
The resulting object of a build depends on the builder used to create it. For docker and S2I builds, the resulting objects are runnable images. For custom builds, the resulting objects are whatever the builder image author has specified.
Additionally, the pipeline build strategy can be used to implement sophisticated workflows:
- Continuous integration
- Continuous deployment
2.1.1.1. Docker build Copia collegamentoCollegamento copiato negli appunti!
OpenShift Container Platform uses Buildah to build a container image from a Dockerfile. For more information on building container images with Dockerfiles, see the Dockerfile reference documentation.
If you set Docker build arguments by using the
buildArgs
2.1.1.2. Source-to-image build Copia collegamentoCollegamento copiato negli appunti!
Source-to-image (S2I) is a tool for building reproducible container images. It produces ready-to-run images by injecting application source into a container image and assembling a new image. The new image incorporates the base image, the builder, and built source and is ready to use with the
buildah run
2.1.1.3. Custom build Copia collegamentoCollegamento copiato negli appunti!
The custom build strategy allows developers to define a specific builder image responsible for the entire build process. Using your own builder image allows you to customize your build process.
A custom builder image is a plain container image embedded with build process logic, for example for building RPMs or base images.
Custom builds run with a high level of privilege and are not available to users by default. Only users who can be trusted with cluster administration permissions should be granted access to run custom builds.
2.1.1.4. Pipeline build Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
The Pipeline build strategy allows developers to define a Jenkins pipeline for use by the Jenkins pipeline plugin. The build can be started, monitored, and managed by OpenShift Container Platform in the same way as any other build type.
Pipeline workflows are defined in a
jenkinsfile
2.2. Understanding build configurations Copia collegamentoCollegamento copiato negli appunti!
The following sections define the concept of a build, build configuration, and outline the primary build strategies available.
2.2.1. BuildConfigs Copia collegamentoCollegamento copiato negli appunti!
A build configuration describes a single build definition and a set of triggers for when a new build is created. Build configurations are defined by a
BuildConfig
A build configuration, or
BuildConfig
Depending on how you choose to create your application using OpenShift Container Platform, a
BuildConfig
BuildConfig
The following example
BuildConfig
BuildConfig object definition
kind: BuildConfig
apiVersion: build.openshift.io/v1
metadata:
name: "ruby-sample-build"
spec:
runPolicy: "Serial"
triggers:
-
type: "GitHub"
github:
secret: "secret101"
- type: "Generic"
generic:
secret: "secret101"
-
type: "ImageChange"
source:
git:
uri: "https://github.com/openshift/ruby-hello-world"
strategy:
sourceStrategy:
from:
kind: "ImageStreamTag"
name: "ruby-20-centos7:latest"
output:
to:
kind: "ImageStreamTag"
name: "origin-ruby-sample:latest"
postCommit:
script: "bundle exec rake test"
- 1
- This specification creates a new
BuildConfignamedruby-sample-build. - 2
- The
runPolicyfield controls whether builds created from this build configuration can be run simultaneously. The default value isSerial, which means new builds run sequentially, not simultaneously. - 3
- You can specify a list of triggers, which cause a new build to be created.
- 4
- The
sourcesection defines the source of the build. The source type determines the primary source of input, and can be eitherGit, to point to a code repository location,Dockerfile, to build from an inline Dockerfile, orBinary, to accept binary payloads. It is possible to have multiple sources at once. See the documentation for each source type for details. - 5
- The
strategysection describes the build strategy used to execute the build. You can specify aSource,Docker, orCustomstrategy here. This example uses theruby-20-centos7container image that Source-to-image (S2I) uses for the application build. - 6
- After the container image is successfully built, it is pushed into the repository described in the
outputsection. - 7
- The
postCommitsection defines an optional build hook.
2.3. Creating build inputs Copia collegamentoCollegamento copiato negli appunti!
Use the following sections for an overview of build inputs, instructions on how to use inputs to provide source content for builds to operate on, and how to use build environments and create secrets.
2.3.1. Build inputs Copia collegamentoCollegamento copiato negli appunti!
A build input provides source content for builds to operate on. You can use the following build inputs to provide sources in OpenShift Container Platform, listed in order of precedence:
- Inline Dockerfile definitions
- Content extracted from existing images
- Git repositories
- Binary (Local) inputs
- Input secrets
- External artifacts
You can combine multiple inputs in a single build. However, as the inline Dockerfile takes precedence, it can overwrite any other file named Dockerfile provided by another input. Binary (local) input and Git repositories are mutually exclusive inputs.
You can use input secrets when you do not want certain resources or credentials used during a build to be available in the final application image produced by the build, or want to consume a value that is defined in a secret resource. External artifacts can be used to pull in additional files that are not available as one of the other build input types.
When you run a build:
- A working directory is constructed and all input content is placed in the working directory. For example, the input Git repository is cloned into the working directory, and files specified from input images are copied into the working directory using the target path.
-
The build process changes directories into the , if one is defined.
contextDir - The inline Dockerfile, if any, is written to the current directory.
-
The content from the current directory is provided to the build process for reference by the Dockerfile, custom builder logic, or script. This means any input content that resides outside the
assembleis ignored by the build.contextDir
The following example of a source definition includes multiple input types and an explanation of how they are combined. For more details on how each input type is defined, see the specific sections for each input type.
source:
git:
uri: https://github.com/openshift/ruby-hello-world.git
ref: "master"
images:
- from:
kind: ImageStreamTag
name: myinputimage:latest
namespace: mynamespace
paths:
- destinationDir: app/dir/injected/dir
sourcePath: /usr/lib/somefile.jar
contextDir: "app/dir"
dockerfile: "FROM centos:7\nRUN yum install -y httpd"
- 1
- The repository to be cloned into the working directory for the build.
- 2
/usr/lib/somefile.jarfrommyinputimageis stored in<workingdir>/app/dir/injected/dir.- 3
- The working directory for the build becomes
<original_workingdir>/app/dir. - 4
- A Dockerfile with this content is created in
<original_workingdir>/app/dir, overwriting any existing file with that name.
2.3.2. Dockerfile source Copia collegamentoCollegamento copiato negli appunti!
When you supply a
dockerfile
dockerfile
The source definition is part of the
spec
BuildConfig
source:
dockerfile: "FROM centos:7\nRUN yum install -y httpd"
- 1
- The
dockerfilefield contains an inline Dockerfile that is built.
2.3.3. Image source Copia collegamentoCollegamento copiato negli appunti!
You can add additional files to the build process with images. Input images are referenced in the same way the
From
To
The source path can be any absolute path within the image specified. The destination must be a relative directory path. At build time, the image is loaded and the indicated files and directories are copied into the context directory of the build process. This is the same directory into which the source repository content is cloned. If the source path ends in
/.
Image inputs are specified in the
source
BuildConfig
source:
git:
uri: https://github.com/openshift/ruby-hello-world.git
ref: "master"
images:
- from:
kind: ImageStreamTag
name: myinputimage:latest
namespace: mynamespace
paths:
- destinationDir: injected/dir
sourcePath: /usr/lib/somefile.jar
- from:
kind: ImageStreamTag
name: myotherinputimage:latest
namespace: myothernamespace
pullSecret: mysecret
paths:
- destinationDir: injected/dir
sourcePath: /usr/lib/somefile.jar
- 1
- An array of one or more input images and files.
- 2
- A reference to the image containing the files to be copied.
- 3
- An array of source/destination paths.
- 4
- The directory relative to the build root where the build process can access the file.
- 5
- The location of the file to be copied out of the referenced image.
- 6
- An optional secret provided if credentials are needed to access the input image.Note
If your cluster uses an
object to configure repository mirroring, you can use only global pull secrets for mirrored registries. You cannot add a pull secret to a project.ImageContentSourcePolicy
Images that require pull secrets
When using an input image that requires a pull secret, you can link the pull secret to the service account used by the build. By default, builds use the
builder
$ oc secrets link builder dockerhub
This feature is not supported for builds using the custom strategy.
Images on mirrored registries that require pull secrets
When using an input image from a mirrored registry, if you get a
build error: failed to pull image
- Create an input secret that contains the authentication credentials for the builder image’s repository and all known mirrors. In this case, create a pull secret for credentials to the image registry and its mirrors.
-
Use the input secret as the pull secret on the object.
BuildConfig
2.3.4. Git source Copia collegamentoCollegamento copiato negli appunti!
When specified, source code is fetched from the supplied location.
If you supply an inline Dockerfile, it overwrites the Dockerfile in the
contextDir
The source definition is part of the
spec
BuildConfig
source:
git:
uri: "https://github.com/openshift/ruby-hello-world"
ref: "master"
contextDir: "app/dir"
dockerfile: "FROM openshift/ruby-22-centos7\nUSER example"
- 1
- The
gitfield contains the Uniform Resource Identifier (URI) to the remote Git repository of the source code. You must specify the value of thereffield to check out a specific Git reference. A validrefcan be a SHA1 tag or a branch name. The default value of thereffield ismaster. - 2
- The
contextDirfield allows you to override the default location inside the source code repository where the build looks for the application source code. If your application exists inside a sub-directory, you can override the default location (the root folder) using this field. - 3
- If the optional
dockerfilefield is provided, it should be a string containing a Dockerfile that overwrites any Dockerfile that may exist in the source repository.
If the
ref
git fetch
FETCH_HEAD
When no
ref
--depth=1
master
git clone
ref
main
Git clone operations that go through a proxy that is performing man in the middle (MITM) TLS hijacking or reencrypting of the proxied connection do not work.
2.3.4.1. Using a proxy Copia collegamentoCollegamento copiato negli appunti!
If your Git repository can only be accessed using a proxy, you can define the proxy to use in the
source
NoProxy
Your source URI must use the HTTP or HTTPS protocol for this to work.
source:
git:
uri: "https://github.com/openshift/ruby-hello-world"
ref: "master"
httpProxy: http://proxy.example.com
httpsProxy: https://proxy.example.com
noProxy: somedomain.com, otherdomain.com
For Pipeline strategy builds, given the current restrictions with the Git plugin for Jenkins, any Git operations through the Git plugin do not leverage the HTTP or HTTPS proxy defined in the
BuildConfig
2.3.4.2. Source Clone Secrets Copia collegamentoCollegamento copiato negli appunti!
Builder pods require access to any Git repositories defined as source for a build. Source clone secrets are used to provide the builder pod with access it would not normally have access to, such as private repositories or repositories with self-signed or untrusted SSL certificates.
The following source clone secret configurations are supported:
- .gitconfig File
- Basic Authentication
- SSH Key Authentication
- Trusted Certificate Authorities
You can also use combinations of these configurations to meet your specific needs.
2.3.4.2.1. Automatically adding a source clone secret to a build configuration Copia collegamentoCollegamento copiato negli appunti!
When a
BuildConfig
To use this functionality, a secret containing the Git repository credentials must exist in the namespace in which the
BuildConfig
build.openshift.io/source-secret-match-uri-
BuildConfig
BuildConfig
Prerequisites
A URI pattern must consist of:
-
A valid scheme: ,
*://,git://,http://orhttps://ssh:// -
A host: *` or a valid hostname or IP address optionally preceded by
*. -
A path: or
/*followed by any characters optionally including/characters*
In all of the above, a
*
URI patterns must match Git source URIs which are conformant to RFC3986. Do not include a username (or password) component in a URI pattern.
For example, if you use
ssh://git@bitbucket.atlassian.com:7999/ATLASSIAN jira.git
ssh://bitbucket.atlassian.com:7999/*
ssh://git@bitbucket.atlassian.com:7999/*
$ oc annotate secret mysecret \
'build.openshift.io/source-secret-match-uri-1=ssh://bitbucket.atlassian.com:7999/*'
Procedure
If multiple secrets match the Git URI of a particular
BuildConfig
The following fragment shows two partial source clone secrets, the first matching any server in the domain
mycorp.com
mydev1.mycorp.com
mydev2.mycorp.com
kind: Secret
apiVersion: v1
metadata:
name: matches-all-corporate-servers-https-only
annotations:
build.openshift.io/source-secret-match-uri-1: https://*.mycorp.com/*
data:
...
---
kind: Secret
apiVersion: v1
metadata:
name: override-for-my-dev-servers-https-only
annotations:
build.openshift.io/source-secret-match-uri-1: https://mydev1.mycorp.com/*
build.openshift.io/source-secret-match-uri-2: https://mydev2.mycorp.com/*
data:
...
Add a
annotation to a pre-existing secret using:build.openshift.io/source-secret-match-uri-$ oc annotate secret mysecret \ 'build.openshift.io/source-secret-match-uri-1=https://*.mycorp.com/*'
2.3.4.2.2. Manually adding a source clone secret Copia collegamentoCollegamento copiato negli appunti!
Source clone secrets can be added manually to a build configuration by adding a
sourceSecret
source
BuildConfig
basicsecret
apiVersion: "build.openshift.io/v1"
kind: "BuildConfig"
metadata:
name: "sample-build"
spec:
output:
to:
kind: "ImageStreamTag"
name: "sample-image:latest"
source:
git:
uri: "https://github.com/user/app.git"
sourceSecret:
name: "basicsecret"
strategy:
sourceStrategy:
from:
kind: "ImageStreamTag"
name: "python-33-centos7:latest"
Procedure
You can also use the
oc set build-secret
To set the source clone secret on an existing build configuration, enter the following command:
$ oc set build-secret --source bc/sample-build basicsecret
2.3.4.2.3. Creating a secret from a .gitconfig file Copia collegamentoCollegamento copiato negli appunti!
If the cloning of your application is dependent on a
.gitconfig
BuildConfig
Procedure
-
To create a secret from a file:
.gitconfig
$ oc create secret generic <secret_name> --from-file=<path/to/.gitconfig>
SSL verification can be turned off if
sslVerify=false
http
.gitconfig
[http]
sslVerify=false
2.3.4.2.4. Creating a secret from a .gitconfig file for secured Git Copia collegamentoCollegamento copiato negli appunti!
If your Git server is secured with two-way SSL and user name with password, you must add the certificate files to your source build and add references to the certificate files in the
.gitconfig
Prerequisites
- You must have Git credentials.
Procedure
Add the certificate files to your source build and add references to the certificate files in the
.gitconfig
-
Add the ,
client.crt, andcacert.crtfiles to theclient.keyfolder in the application source code./var/run/secrets/openshift.io/source/ In the
file for the server, add the.gitconfigsection shown in the following example:[http]# cat .gitconfigExample output
[user] name = <name> email = <email> [http] sslVerify = false sslCert = /var/run/secrets/openshift.io/source/client.crt sslKey = /var/run/secrets/openshift.io/source/client.key sslCaInfo = /var/run/secrets/openshift.io/source/cacert.crtCreate the secret:
$ oc create secret generic <secret_name> \ --from-literal=username=<user_name> \1 --from-literal=password=<password> \2 --from-file=.gitconfig=.gitconfig \ --from-file=client.crt=/var/run/secrets/openshift.io/source/client.crt \ --from-file=cacert.crt=/var/run/secrets/openshift.io/source/cacert.crt \ --from-file=client.key=/var/run/secrets/openshift.io/source/client.key
To avoid having to enter your password again, be sure to specify the source-to-image (S2I) image in your builds. However, if you cannot clone the repository, you must still specify your user name and password to promote the build.
2.3.4.2.5. Creating a secret from source code basic authentication Copia collegamentoCollegamento copiato negli appunti!
Basic authentication requires either a combination of
--username
--password
Prerequisites
- User name and password to access the private repository.
Procedure
Create the secret first before using the
and--usernameto access the private repository:--password$ oc create secret generic <secret_name> \ --from-literal=username=<user_name> \ --from-literal=password=<password> \ --type=kubernetes.io/basic-authCreate a basic authentication secret with a token:
$ oc create secret generic <secret_name> \ --from-literal=password=<token> \ --type=kubernetes.io/basic-auth
2.3.4.2.6. Creating a secret from source code SSH key authentication Copia collegamentoCollegamento copiato negli appunti!
SSH key based authentication requires a private SSH key.
The repository keys are usually located in the
$HOME/.ssh/
id_dsa.pub
id_ecdsa.pub
id_ed25519.pub
id_rsa.pub
Procedure
Generate SSH key credentials:
$ ssh-keygen -t ed25519 -C "your_email@example.com"NoteCreating a passphrase for the SSH key prevents OpenShift Container Platform from building. When prompted for a passphrase, leave it blank.
Two files are created: the public key and a corresponding private key (one of
,id_dsa,id_ecdsa, orid_ed25519). With both of these in place, consult your source control management (SCM) system’s manual on how to upload the public key. The private key is used to access your private repository.id_rsaBefore using the SSH key to access the private repository, create the secret:
$ oc create secret generic <secret_name> \ --from-file=ssh-privatekey=<path/to/ssh/private/key> \ --from-file=<path/to/known_hosts> \1 --type=kubernetes.io/ssh-auth- 1
- Optional: Adding this field enables strict server host key check.
WarningSkipping the
file while creating the secret makes the build vulnerable to a potential man-in-the-middle (MITM) attack.known_hostsNoteEnsure that the
file includes an entry for the host of your source code.known_hosts
2.3.4.2.7. Creating a secret from source code trusted certificate authorities Copia collegamentoCollegamento copiato negli appunti!
The set of Transport Layer Security (TLS) certificate authorities (CA) that are trusted during a Git clone operation are built into the OpenShift Container Platform infrastructure images. If your Git server uses a self-signed certificate or one signed by an authority not trusted by the image, you can create a secret that contains the certificate or disable TLS verification.
If you create a secret for the CA certificate, OpenShift Container Platform uses it to access your Git server during the Git clone operation. Using this method is significantly more secure than disabling Git SSL verification, which accepts any TLS certificate that is presented.
Procedure
Create a secret with a CA certificate file.
If your CA uses Intermediate Certificate Authorities, combine the certificates for all CAs in a
file. Enter the following command:ca.crt$ cat intermediateCA.crt intermediateCA.crt rootCA.crt > ca.crtCreate the secret:
$ oc create secret generic mycert --from-file=ca.crt=</path/to/file>1 - 1
- You must use the key name
ca.crt.
2.3.4.2.8. Source secret combinations Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs.
2.3.4.2.8.1. Creating a SSH-based authentication secret with a .gitconfig file Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs, such as a SSH-based authentication secret with a
.gitconfig
Prerequisites
- SSH authentication
- .gitconfig file
Procedure
To create a SSH-based authentication secret with a
file, run:.gitconfig$ oc create secret generic <secret_name> \ --from-file=ssh-privatekey=<path/to/ssh/private/key> \ --from-file=<path/to/.gitconfig> \ --type=kubernetes.io/ssh-auth
2.3.4.2.8.2. Creating a secret that combines a .gitconfig file and CA certificate Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs, such as a secret that combines a
.gitconfig
Prerequisites
- .gitconfig file
- CA certificate
Procedure
To create a secret that combines a
file and CA certificate, run:.gitconfig$ oc create secret generic <secret_name> \ --from-file=ca.crt=<path/to/certificate> \ --from-file=<path/to/.gitconfig>
2.3.4.2.8.3. Creating a basic authentication secret with a CA certificate Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs, such as a secret that combines a basic authentication and certificate authority (CA) certificate.
Prerequisites
- Basic authentication credentials
- CA certificate
Procedure
Create a basic authentication secret with a CA certificate, run:
$ oc create secret generic <secret_name> \ --from-literal=username=<user_name> \ --from-literal=password=<password> \ --from-file=ca-cert=</path/to/file> \ --type=kubernetes.io/basic-auth
2.3.4.2.8.4. Creating a basic authentication secret with a .gitconfig file Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs, such as a secret that combines a basic authentication and
.gitconfig
Prerequisites
- Basic authentication credentials
-
file
.gitconfig
Procedure
To create a basic authentication secret with a
file, run:.gitconfig$ oc create secret generic <secret_name> \ --from-literal=username=<user_name> \ --from-literal=password=<password> \ --from-file=</path/to/.gitconfig> \ --type=kubernetes.io/basic-auth
2.3.4.2.8.5. Creating a basic authentication secret with a .gitconfig file and CA certificate Copia collegamentoCollegamento copiato negli appunti!
You can combine the different methods for creating source clone secrets for your specific needs, such as a secret that combines a basic authentication,
.gitconfig
Prerequisites
- Basic authentication credentials
-
file
.gitconfig - CA certificate
Procedure
To create a basic authentication secret with a
file and CA certificate, run:.gitconfig$ oc create secret generic <secret_name> \ --from-literal=username=<user_name> \ --from-literal=password=<password> \ --from-file=</path/to/.gitconfig> \ --from-file=ca-cert=</path/to/file> \ --type=kubernetes.io/basic-auth
2.3.5. Binary (local) source Copia collegamentoCollegamento copiato negli appunti!
Streaming content from a local file system to the builder is called a
Binary
BuildConfig.spec.source.type
Binary
This source type is unique in that it is leveraged solely based on your use of the
oc start-build
Binary type builds require content to be streamed from the local file system, so automatically triggering a binary type build, like an image change trigger, is not possible. This is because the binary files cannot be provided. Similarly, you cannot launch binary type builds from the web console.
To utilize binary builds, invoke
oc start-build
-
: The contents of the file you specify are sent as a binary stream to the builder. You can also specify a URL to a file. Then, the builder stores the data in a file with the same name at the top of the build context.
--from-file -
and
--from-dir: The contents are archived and sent as a binary stream to the builder. Then, the builder extracts the contents of the archive within the build context directory. With--from-repo, you can also specify a URL to an archive, which is extracted.--from-dir -
: The archive you specify is sent to the builder, where it is extracted within the build context directory. This option behaves the same as
--from-archive; an archive is created on your host first, whenever the argument to these options is a directory.--from-dir
In each of the previously listed cases:
-
If your already has a
BuildConfigsource type defined, it is effectively ignored and replaced by what the client sends.Binary -
If your has a
BuildConfigsource type defined, it is dynamically disabled, sinceGitandBinaryare mutually exclusive, and the data in the binary stream provided to the builder takes precedence.Git
Instead of a file name, you can pass a URL with HTTP or HTTPS schema to
--from-file
--from-archive
--from-file
Content-Disposition
When using
oc new-build --binary=true
BuildConfig
Binary
BuildConfig
oc start-build
--from
The Dockerfile and
contextDir
Dockerfile can be used with any binary build source. If Dockerfile is used and the binary stream is an archive, its contents serve as a replacement Dockerfile to any Dockerfile in the archive. If Dockerfile is used with the
--from-file
In the case of the binary stream encapsulating extracted archive content, the value of the
contextDir
2.3.6. Input secrets and config maps Copia collegamentoCollegamento copiato negli appunti!
To prevent the contents of input secrets and config maps from appearing in build output container images, use build volumes in your Docker build and source-to-image build strategies.
In some scenarios, build operations require credentials or other configuration data to access dependent resources, but it is undesirable for that information to be placed in source control. You can define input secrets and input config maps for this purpose.
For example, when building a Java application with Maven, you can set up a private mirror of Maven Central or JCenter that is accessed by private keys. To download libraries from that private mirror, you have to supply the following:
-
A file configured with the mirror’s URL and connection settings.
settings.xml -
A private key referenced in the settings file, such as .
~/.ssh/id_rsa
For security reasons, you do not want to expose your credentials in the application image.
This example describes a Java application, but you can use the same approach for adding SSL certificates into the
/etc/ssl/certs
2.3.6.1. What is a secret? Copia collegamentoCollegamento copiato negli appunti!
The
Secret
dockercfg
YAML Secret Object Definition
apiVersion: v1
kind: Secret
metadata:
name: test-secret
namespace: my-namespace
type: Opaque
data:
username: <username>
password: <password>
stringData:
hostname: myapp.mydomain.com
- 1
- Indicates the structure of the secret’s key names and values.
- 2
- The allowable format for the keys in the
datafield must meet the guidelines in theDNS_SUBDOMAINvalue in the Kubernetes identifiers glossary. - 3
- The value associated with keys in the
datamap must be base64 encoded. - 4
- Entries in the
stringDatamap are converted to base64 and the entry are then moved to thedatamap automatically. This field is write-only. The value is only be returned by thedatafield. - 5
- The value associated with keys in the
stringDatamap is made up of plain text strings.
2.3.6.1.1. Properties of secrets Copia collegamentoCollegamento copiato negli appunti!
Key properties include:
- Secret data can be referenced independently from its definition.
- Secret data volumes are backed by temporary file-storage facilities (tmpfs) and never come to rest on a node.
- Secret data can be shared within a namespace.
2.3.6.1.2. Types of Secrets Copia collegamentoCollegamento copiato negli appunti!
The value in the
type
opaque
Specify one of the following types to trigger minimal server-side validation to ensure the presence of specific key names in the secret data:
-
. Uses a service account token.
kubernetes.io/service-account-token -
. Uses the
kubernetes.io/dockercfgfile for required Docker credentials..dockercfg -
. Uses the
kubernetes.io/dockerconfigjsonfile for required Docker credentials..docker/config.json -
. Use with basic authentication.
kubernetes.io/basic-auth -
. Use with SSH key authentication.
kubernetes.io/ssh-auth -
. Use with TLS certificate authorities.
kubernetes.io/tls
Specify
type= Opaque
opaque
key:value
You can specify other arbitrary types, such as
example.com/my-secret-type
2.3.6.1.3. Updates to secrets Copia collegamentoCollegamento copiato negli appunti!
When you modify the value of a secret, the value used by an already running pod does not dynamically change. To change a secret, you must delete the original pod and create a new pod, in some cases with an identical
PodSpec
Updating a secret follows the same workflow as deploying a new container image. You can use the
kubectl rolling-update
The
resourceVersion
Currently, it is not possible to check the resource version of a secret object that was used when a pod was created. It is planned that pods report this information, so that a controller could restart ones using an old
resourceVersion
2.3.6.2. Creating secrets Copia collegamentoCollegamento copiato negli appunti!
You must create a secret before creating the pods that depend on that secret.
When creating secrets:
- Create a secret object with secret data.
- Update the pod service account to allow the reference to the secret.
-
Create a pod, which consumes the secret as an environment variable or as a file using a volume.
secret
Procedure
Use the create command to create a secret object from a JSON or YAML file:
$ oc create -f <filename>For example, you can create a secret from your local
file:.docker/config.json$ oc create secret generic dockerhub \ --from-file=.dockerconfigjson=<path/to/.docker/config.json> \ --type=kubernetes.io/dockerconfigjsonThis command generates a JSON specification of the secret named
and creates the object.dockerhubYAML Opaque Secret Object Definition
apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque1 data: username: <username> password: <password>- 1
- Specifies an opaque secret.
Docker Configuration JSON File Secret Object Definition
apiVersion: v1 kind: Secret metadata: name: aregistrykey namespace: myapps type: kubernetes.io/dockerconfigjson1 data: .dockerconfigjson:bm5ubm5ubm5ubm5ubm5ubm5ubm5ubmdnZ2dnZ2dnZ2dnZ2dnZ2dnZ2cgYXV0aCBrZXlzCg==2
2.3.6.3. Using secrets Copia collegamentoCollegamento copiato negli appunti!
After creating secrets, you can create a pod to reference your secret, get logs, and delete the pod.
Procedure
Create the pod to reference your secret:
$ oc create -f <your_yaml_file>.yamlGet the logs:
$ oc logs secret-example-podDelete the pod:
$ oc delete pod secret-example-pod
2.3.6.4. Adding input secrets and config maps Copia collegamentoCollegamento copiato negli appunti!
To provide credentials and other configuration data to a build without placing them in source control, you can define input secrets and input config maps.
In some scenarios, build operations require credentials or other configuration data to access dependent resources. To make that information available without placing it in source control, you can define input secrets and input config maps.
Procedure
To add an input secret, config maps, or both to an existing
BuildConfig
Create the
object, if it does not exist:ConfigMap$ oc create configmap settings-mvn \ --from-file=settings.xml=<path/to/settings.xml>This creates a new config map named
, which contains the plain text content of thesettings-mvnfile.settings.xmlTipYou can alternatively apply the following YAML to create the config map:
apiVersion: core/v1 kind: ConfigMap metadata: name: settings-mvn data: settings.xml: | <settings> … # Insert maven settings here </settings>Create the
object, if it does not exist:Secret$ oc create secret generic secret-mvn \ --from-file=ssh-privatekey=<path/to/.ssh/id_rsa> --type=kubernetes.io/ssh-authThis creates a new secret named
, which contains the base64 encoded content of thesecret-mvnprivate key.id_rsaTipYou can alternatively apply the following YAML to create the input secret:
apiVersion: core/v1 kind: Secret metadata: name: secret-mvn type: kubernetes.io/ssh-auth data: ssh-privatekey: | # Insert ssh private key, base64 encodedAdd the config map and secret to the
section in the existingsourceobject:BuildConfigsource: git: uri: https://github.com/wildfly/quickstart.git contextDir: helloworld configMaps: - configMap: name: settings-mvn secrets: - secret: name: secret-mvn
To include the secret and config map in a new
BuildConfig
$ oc new-build \
openshift/wildfly-101-centos7~https://github.com/wildfly/quickstart.git \
--context-dir helloworld --build-secret “secret-mvn” \
--build-config-map "settings-mvn"
During the build, the
settings.xml
id_rsa
WORKDIR
Dockerfile
destinationDir
source:
git:
uri: https://github.com/wildfly/quickstart.git
contextDir: helloworld
configMaps:
- configMap:
name: settings-mvn
destinationDir: ".m2"
secrets:
- secret:
name: secret-mvn
destinationDir: ".ssh"
You can also specify the destination directory when creating a new
BuildConfig
$ oc new-build \
openshift/wildfly-101-centos7~https://github.com/wildfly/quickstart.git \
--context-dir helloworld --build-secret “secret-mvn:.ssh” \
--build-config-map "settings-mvn:.m2"
In both cases, the
settings.xml
./.m2
id_rsa
./.ssh
2.3.6.5. Source-to-image strategy Copia collegamentoCollegamento copiato negli appunti!
When using a
Source
destinationDir
destinationDir
The same rule is used when a
destinationDir
destinationDir
destinationDir
Input secrets are added as world-writable, have
0666
assemble
Input config maps are not truncated after the
assemble
2.3.6.6. Docker strategy Copia collegamentoCollegamento copiato negli appunti!
When using a docker strategy, you can add all defined input secrets into your container image using the ADD and COPY instructions in your Dockerfile.
If you do not specify the
destinationDir
destinationDir
Example of a Dockerfile referencing secret and config map data
FROM centos/ruby-22-centos7
USER root
COPY ./secret-dir /secrets
COPY ./config /
# Create a shell script that will output secrets and ConfigMaps when the image is run
RUN echo '#!/bin/sh' > /input_report.sh
RUN echo '(test -f /secrets/secret1 && echo -n "secret1=" && cat /secrets/secret1)' >> /input_report.sh
RUN echo '(test -f /config && echo -n "relative-configMap=" && cat /config)' >> /input_report.sh
RUN chmod 755 /input_report.sh
CMD ["/bin/sh", "-c", "/input_report.sh"]
Users normally remove their input secrets from the final application image so that the secrets are not present in the container running from that image. However, the secrets still exist in the image itself in the layer where they were added. This removal is part of the Dockerfile itself.
To prevent the contents of input secrets and config maps from appearing in the build output container images and avoid this removal process altogether, use build volumes in your Docker build strategy instead.
2.3.6.7. Custom strategy Copia collegamentoCollegamento copiato negli appunti!
When using a Custom strategy, all the defined input secrets and config maps are available in the builder container in the
/var/run/secrets/openshift.io/build
There is no technical difference between existing strategy secrets and the input secrets. However, your builder image can distinguish between them and use them differently, based on your build use case.
The input secrets are always mounted into the
/var/run/secrets/openshift.io/build
$BUILD
If a pull secret for the registry exists in both the namespace and the node, builds default to using the pull secret in the namespace.
2.3.7. External artifacts Copia collegamentoCollegamento copiato negli appunti!
It is not recommended to store binary files in a source repository. Therefore, you must define a build which pulls additional files, such as Java
.jar
For a Source build strategy, you must put appropriate shell commands into the
assemble
.s2i/bin/assemble File
#!/bin/sh
APP_VERSION=1.0
wget http://repository.example.com/app/app-$APP_VERSION.jar -O app.jar
.s2i/bin/run File
#!/bin/sh
exec java -jar app.jar
For a Docker build strategy, you must modify the Dockerfile and invoke shell commands with the RUN instruction:
Excerpt of Dockerfile
FROM jboss/base-jdk:8
ENV APP_VERSION 1.0
RUN wget http://repository.example.com/app/app-$APP_VERSION.jar -O app.jar
EXPOSE 8080
CMD [ "java", "-jar", "app.jar" ]
In practice, you may want to use an environment variable for the file location so that the specific file to be downloaded can be customized using an environment variable defined on the
BuildConfig
assemble
You can choose between different methods of defining environment variables:
-
Using the file] (only for a Source build strategy)
.s2i/environment -
Setting in
BuildConfig -
Providing explicitly using (only for builds that are triggered manually)
oc start-build --env
2.3.8. Using docker credentials for private registries Copia collegamentoCollegamento copiato negli appunti!
You can supply builds with a .
docker/config.json
You can supply credentials for multiple repositories within the same registry, each with credentials specific to that registry path.
For the OpenShift Container Platform container image registry, this is not required because secrets are generated automatically for you by OpenShift Container Platform.
The
.docker/config.json
auths:
index.docker.io/v1/:
auth: "YWRfbGzhcGU6R2labnRib21ifTE="
email: "user@example.com"
docker.io/my-namespace/my-user/my-image:
auth: "GzhYWRGU6R2fbclabnRgbkSp=""
email: "user@example.com"
docker.io/my-namespace:
auth: "GzhYWRGU6R2deesfrRgbkSp=""
email: "user@example.com"
You can define multiple container image registries or define multiple repositories in the same registry. Alternatively, you can also add authentication entries to this file by running the
docker login
Kubernetes provides
Secret
Prerequisites
-
You must have a file.
.docker/config.json
Procedure
Create the secret from your local
file:.docker/config.json$ oc create secret generic dockerhub \ --from-file=.dockerconfigjson=<path/to/.docker/config.json> \ --type=kubernetes.io/dockerconfigjsonThis generates a JSON specification of the secret named
and creates the object.dockerhubAdd a
field into thepushSecretsection of theoutputand set it to the name of theBuildConfigthat you created, which in the previous example issecret:dockerhubspec: output: to: kind: "DockerImage" name: "private.registry.com/org/private-image:latest" pushSecret: name: "dockerhub"You can use the
command to set the push secret on the build configuration:oc set build-secret$ oc set build-secret --push bc/sample-build dockerhubYou can also link the push secret to the service account used by the build instead of specifying the
field. By default, builds use thepushSecretservice account. The push secret is automatically added to the build if the secret contains a credential that matches the repository hosting the build’s output image.builder$ oc secrets link builder dockerhubPull the builder container image from a private container image registry by specifying the
field, which is part of the build strategy definition:pullSecretstrategy: sourceStrategy: from: kind: "DockerImage" name: "docker.io/user/private_repository" pullSecret: name: "dockerhub"You can use the
command to set the pull secret on the build configuration:oc set build-secret$ oc set build-secret --pull bc/sample-build dockerhubNoteThis example uses
in a Source build, but it is also applicable in Docker and Custom builds.pullSecretYou can also link the pull secret to the service account used by the build instead of specifying the
field. By default, builds use thepullSecretservice account. The pull secret is automatically added to the build if the secret contains a credential that matches the repository hosting the build’s input image. To link the pull secret to the service account used by the build instead of specifying thebuilderfield, run:pullSecret$ oc secrets link builder dockerhubNoteYou must specify a
image in thefromspec to take advantage of this feature. Docker strategy builds generated byBuildConfigoroc new-buildmay not do this in some situations.oc new-app
2.3.9. Build environments Copia collegamentoCollegamento copiato negli appunti!
As with pod environment variables, build environment variables can be defined in terms of references to other resources or variables using the Downward API. There are some exceptions, which are noted.
You can also manage environment variables defined in the
BuildConfig
oc set env
Referencing container resources using
valueFrom
2.3.9.1. Using build fields as environment variables Copia collegamentoCollegamento copiato negli appunti!
You can inject information about the build object by setting the
fieldPath
JsonPath
Jenkins Pipeline strategy does not support
valueFrom
Procedure
Set the
environment variable source to thefieldPathof the field from which you are interested in obtaining the value:JsonPathenv: - name: FIELDREF_ENV valueFrom: fieldRef: fieldPath: metadata.name
2.3.9.2. Using secrets as environment variables Copia collegamentoCollegamento copiato negli appunti!
You can make key values from secrets available as environment variables using the
valueFrom
This method shows the secrets as plain text in the output of the build pod console. To avoid this, use input secrets and config maps instead.
Procedure
To use a secret as an environment variable, set the
syntax:valueFromapiVersion: build.openshift.io/v1 kind: BuildConfig metadata: name: secret-example-bc spec: strategy: sourceStrategy: env: - name: MYVAL valueFrom: secretKeyRef: key: myval name: mysecret
2.3.10. Service serving certificate secrets Copia collegamentoCollegamento copiato negli appunti!
Service serving certificate secrets are intended to support complex middleware applications that need out-of-the-box certificates. It has the same settings as the server certificates generated by the administrator tooling for nodes and masters.
Procedure
To secure communication to your service, have the cluster generate a signed serving certificate/key pair into a secret in your namespace.
Set the
annotation on your service with the value set to the name you want to use for your secret.service.beta.openshift.io/serving-cert-secret-nameThen, your
can mount that secret. When it is available, your pod runs. The certificate is good for the internal service DNS name,PodSpec.<service.name>.<service.namespace>.svcThe certificate and key are in PEM format, stored in
andtls.crtrespectively. The certificate/key pair is automatically replaced when it gets close to expiration. View the expiration date in thetls.keyannotation on the secret, which is in RFC3339 format.service.beta.openshift.io/expiry
In most cases, the service DNS name
<service.name>.<service.namespace>.svc
<service.name>.<service.namespace>.svc
Other pods can trust cluster-created certificates, which are only signed for internal DNS names, by using the certificate authority (CA) bundle in the
/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt
The signature algorithm for this feature is
x509.SHA256WithRSA
2.3.11. Secrets restrictions Copia collegamentoCollegamento copiato negli appunti!
To use a secret, a pod needs to reference the secret. A secret can be used with a pod in three ways:
- To populate environment variables for containers.
- As files in a volume mounted on one or more of its containers.
- By kubelet when pulling images for the pod.
Volume type secrets write data into the container as a file using the volume mechanism.
imagePullSecrets
When a template contains a secret definition, the only way for the template to use the provided secret is to ensure that the secret volume sources are validated and that the specified object reference actually points to an object of type
Secret
Secret API objects reside in a namespace. They can only be referenced by pods in that same namespace.
Individual secrets are limited to 1MB in size. This is to discourage the creation of large secrets that would exhaust apiserver and kubelet memory. However, creation of a number of smaller secrets could also exhaust memory.
2.4. Managing build output Copia collegamentoCollegamento copiato negli appunti!
Use the following sections for an overview of and instructions for managing build output.
2.4.1. Build output Copia collegamentoCollegamento copiato negli appunti!
Builds that use the docker or source-to-image (S2I) strategy result in the creation of a new container image. The image is then pushed to the container image registry specified in the
output
Build
If the output kind is
ImageStreamTag
DockerImage
Output to an ImageStreamTag
spec:
output:
to:
kind: "ImageStreamTag"
name: "sample-image:latest"
Output to a docker Push Specification
spec:
output:
to:
kind: "DockerImage"
name: "my-registry.mycompany.com:5000/myimages/myimage:tag"
2.4.2. Output image environment variables Copia collegamentoCollegamento copiato negli appunti!
docker and source-to-image (S2I) strategy builds set the following environment variables on output images:
| Variable | Description |
|---|---|
|
| Name of the build |
|
| Namespace of the build |
|
| The source URL of the build |
|
| The Git reference used in the build |
|
| Source commit used in the build |
Additionally, any user-defined environment variable, for example those configured with S2I] or docker strategy options, will also be part of the output image environment variable list.
2.4.3. Output image labels Copia collegamentoCollegamento copiato negli appunti!
docker and source-to-image (S2I)` builds set the following labels on output images:
| Label | Description |
|---|---|
|
| Author of the source commit used in the build |
|
| Date of the source commit used in the build |
|
| Hash of the source commit used in the build |
|
| Message of the source commit used in the build |
|
| Branch or reference specified in the source |
|
| Source URL for the build |
You can also use the
BuildConfig.spec.output.imageLabels
Custom Labels to be Applied to Built Images
spec:
output:
to:
kind: "ImageStreamTag"
name: "my-image:latest"
imageLabels:
- name: "vendor"
value: "MyCompany"
- name: "authoritative-source-url"
value: "registry.mycompany.com"
2.5. Using build strategies Copia collegamentoCollegamento copiato negli appunti!
The following sections define the primary supported build strategies, and how to use them.
2.5.1. Docker build Copia collegamentoCollegamento copiato negli appunti!
OpenShift Container Platform uses Buildah to build a container image from a Dockerfile. For more information on building container images with Dockerfiles, see the Dockerfile reference documentation.
If you set Docker build arguments by using the
buildArgs
2.5.1.1. Replacing Dockerfile FROM image Copia collegamentoCollegamento copiato negli appunti!
You can replace the
FROM
from
BuildConfig
FROM
Procedure
To replace the
FROM
from
BuildConfig
strategy:
dockerStrategy:
from:
kind: "ImageStreamTag"
name: "debian:latest"
2.5.1.2. Using Dockerfile path Copia collegamentoCollegamento copiato negli appunti!
By default, docker builds use a Dockerfile located at the root of the context specified in the
BuildConfig.spec.source.contextDir
The
dockerfilePath
BuildConfig.spec.source.contextDir
MyDockerfile
dockerfiles/app1/Dockerfile
Procedure
To use the
dockerfilePath
strategy:
dockerStrategy:
dockerfilePath: dockerfiles/app1/Dockerfile
2.5.1.3. Using docker environment variables Copia collegamentoCollegamento copiato negli appunti!
To make environment variables available to the docker build process and resulting image, you can add environment variables to the
dockerStrategy
The environment variables defined there are inserted as a single
ENV
FROM
Procedure
The variables are defined during build and stay in the output image, therefore they will be present in any container that runs that image as well.
For example, defining a custom HTTP proxy to be used during build and runtime:
dockerStrategy:
...
env:
- name: "HTTP_PROXY"
value: "http://myproxy.net:5187/"
You can also manage environment variables defined in the build configuration with the
oc set env
2.5.1.4. Adding docker build arguments Copia collegamentoCollegamento copiato negli appunti!
You can set docker build arguments using the
buildArgs
See Understand how ARG and FROM interact in the Dockerfile reference documentation.
Procedure
To set docker build arguments, add entries to the
buildArgs
dockerStrategy
BuildConfig
dockerStrategy:
...
buildArgs:
- name: "foo"
value: "bar"
Only the
name
value
valueFrom
2.5.1.5. Squashing layers with docker builds Copia collegamentoCollegamento copiato negli appunti!
Docker builds normally create a layer representing each instruction in a Dockerfile. Setting the
imageOptimizationPolicy
SkipLayers
Procedure
Set the
toimageOptimizationPolicy:SkipLayersstrategy: dockerStrategy: imageOptimizationPolicy: SkipLayers
2.5.1.6. Using build volumes Copia collegamentoCollegamento copiato negli appunti!
You can mount build volumes to give running builds access to information that you don’t want to persist in the output container image.
Build volumes provide sensitive information, such as repository credentials, that the build environment or configuration only needs at build time. Build volumes are different from build inputs, whose data can persist in the output container image.
The mount points of build volumes, from which the running build reads data, are functionally similar to pod volume mounts.
Prerequisites
Procedure
In the
definition of thedockerStrategyobject, add any build volumes to theBuildConfigarray. For example:volumesspec: dockerStrategy: volumes: - name: secret-mvn1 mounts: - destinationPath: /opt/app-root/src/.ssh2 source: type: Secret3 secret: secretName: my-secret4 - name: settings-mvn5 mounts: - destinationPath: /opt/app-root/src/.m26 source: type: ConfigMap7 configMap: name: my-config8 - name: my-csi-volume9 mounts: - destinationPath: /opt/app-root/src/some_path10 source: type: CSI11 csi: driver: csi.sharedresource.openshift.io12 readOnly: true13 volumeAttributes:14 attribute: value- 1 5 9
- Required. A unique name.
- 2 6 10
- Required. The absolute path of the mount point. It must not contain
..or:and doesn’t collide with the destination path generated by the builder. The/opt/app-root/srcis the default home directory for many Red Hat S2I-enabled images. - 3 7 11
- Required. The type of source,
ConfigMap,Secret, orCSI. - 4 8
- Required. The name of the source.
- 12
- Required. The driver that provides the ephemeral CSI volume.
- 13
- Required. This value must be set to
true. Provides a read-only volume. - 14
- Optional. The volume attributes of the ephemeral CSI volume. Consult the CSI driver’s documentation for supported attribute keys and values.
The Shared Resource CSI Driver is supported as a Technology Preview feature.
2.5.2. Source-to-image build Copia collegamentoCollegamento copiato negli appunti!
Source-to-image (S2I) is a tool for building reproducible container images. It produces ready-to-run images by injecting application source into a container image and assembling a new image. The new image incorporates the base image, the builder, and built source and is ready to use with the
buildah run
2.5.2.1. Performing source-to-image incremental builds Copia collegamentoCollegamento copiato negli appunti!
Source-to-image (S2I) can perform incremental builds, which means it reuses artifacts from previously-built images.
Procedure
To create an incremental build, create a with the following modification to the strategy definition:
strategy: sourceStrategy: from: kind: "ImageStreamTag" name: "incremental-image:latest"1 incremental: true2 - 1
- Specify an image that supports incremental builds. Consult the documentation of the builder image to determine if it supports this behavior.
- 2
- This flag controls whether an incremental build is attempted. If the builder image does not support incremental builds, the build will still succeed, but you will get a log message stating the incremental build was not successful because of a missing
save-artifactsscript.
2.5.2.2. Overriding source-to-image builder image scripts Copia collegamentoCollegamento copiato negli appunti!
You can override the
assemble
run
save-artifacts
Procedure
To override the
assemble
run
save-artifacts
-
Provide an ,
assemble, orrunscript in thesave-artifactsdirectory of your application source repository..s2i/bin Provide a URL of a directory containing the scripts as part of the strategy definition. For example:
strategy: sourceStrategy: from: kind: "ImageStreamTag" name: "builder-image:latest" scripts: "http://somehost.com/scripts_directory"1 - 1
- This path will have
run,assemble, andsave-artifactsappended to it. If any or all scripts are found they will be used in place of the same named scripts provided in the image.
Files located at the
scripts
.s2i/bin
2.5.2.3. Source-to-image environment variables Copia collegamentoCollegamento copiato negli appunti!
There are two ways to make environment variables available to the source build process and resulting image. Environment files and BuildConfig environment values. Variables provided will be present during the build process and in the output image.
2.5.2.3.1. Using source-to-image environment files Copia collegamentoCollegamento copiato negli appunti!
Source build enables you to set environment values, one per line, inside your application, by specifying them in a
.s2i/environment
If you provide a
.s2i/environment
assemble
Procedure
For example, to disable assets compilation for your Rails application during the build:
-
Add in the
DISABLE_ASSET_COMPILATION=truefile..s2i/environment
In addition to builds, the specified environment variables are also available in the running application itself. For example, to cause the Rails application to start in
development
production
-
Add to the
RAILS_ENV=developmentfile..s2i/environment
The complete list of supported environment variables is available in the using images section for each image.
2.5.2.3.2. Using source-to-image build configuration environment Copia collegamentoCollegamento copiato negli appunti!
You can add environment variables to the
sourceStrategy
assemble
run
Procedure
For example, to disable assets compilation for your Rails application:
sourceStrategy: ... env: - name: "DISABLE_ASSET_COMPILATION" value: "true"
2.5.2.4. Ignoring source-to-image source files Copia collegamentoCollegamento copiato negli appunti!
Source-to-image (S2I) supports a
.s2iignore
.s2iignore
assemble
2.5.2.5. Creating images from source code with source-to-image Copia collegamentoCollegamento copiato negli appunti!
Source-to-image (S2I) is a framework that makes it easy to write images that take application source code as an input and produce a new image that runs the assembled application as output.
The main advantage of using S2I for building reproducible container images is the ease of use for developers. As a builder image author, you must understand two basic concepts in order for your images to provide the best S2I performance, the build process and S2I scripts.
2.5.2.5.1. Understanding the source-to-image build process Copia collegamentoCollegamento copiato negli appunti!
The build process consists of the following three fundamental elements, which are combined into a final container image:
- Sources
- Source-to-image (S2I) scripts
- Builder image
S2I generates a Dockerfile with the builder image as the first
FROM
2.5.2.5.2. How to write source-to-image scripts Copia collegamentoCollegamento copiato negli appunti!
You can write source-to-image (S2I) scripts in any programming language, as long as the scripts are executable inside the builder image. S2I supports multiple options providing
assemble
run
save-artifacts
- A script specified in the build configuration.
-
A script found in the application source directory.
.s2i/bin -
A script found at the default image URL with the label.
io.openshift.s2i.scripts-url
Both the
io.openshift.s2i.scripts-url
-
: absolute path inside the image to a directory where the S2I scripts are located.
image:///path_to_scripts_dir -
: relative or absolute path to a directory on the host where the S2I scripts are located.
file:///path_to_scripts_dir -
: URL to a directory where the S2I scripts are located.
http(s)://path_to_scripts_dir
| Script | Description |
|---|---|
|
| The
|
|
| The
|
|
| The
These dependencies are gathered into a
|
|
| The
|
|
| The
Note The suggested location to put the test application built by your
|
Example S2I scripts
The following example S2I scripts are written in Bash. Each example assumes its
tar
/tmp/s2i
assemble script:
#!/bin/bash
# restore build artifacts
if [ "$(ls /tmp/s2i/artifacts/ 2>/dev/null)" ]; then
mv /tmp/s2i/artifacts/* $HOME/.
fi
# move the application source
mv /tmp/s2i/src $HOME/src
# build application artifacts
pushd ${HOME}
make all
# install the artifacts
make install
popd
run script:
#!/bin/bash
# run the application
/opt/application/run.sh
save-artifacts script:
#!/bin/bash
pushd ${HOME}
if [ -d deps ]; then
# all deps contents to tar stream
tar cf - deps
fi
popd
usage script:
#!/bin/bash
# inform the user how to use the image
cat <<EOF
This is a S2I sample builder image, to use it, install
https://github.com/openshift/source-to-image
EOF
2.5.2.6. Using build volumes Copia collegamentoCollegamento copiato negli appunti!
You can mount build volumes to give running builds access to information that you don’t want to persist in the output container image.
Build volumes provide sensitive information, such as repository credentials, that the build environment or configuration only needs at build time. Build volumes are different from build inputs, whose data can persist in the output container image.
The mount points of build volumes, from which the running build reads data, are functionally similar to pod volume mounts.
Prerequisites
Procedure
In the
definition of thesourceStrategyobject, add any build volumes to theBuildConfigarray. For example:volumesspec: sourceStrategy: volumes: - name: secret-mvn1 mounts: - destinationPath: /opt/app-root/src/.ssh2 source: type: Secret3 secret: secretName: my-secret4 - name: settings-mvn5 mounts: - destinationPath: /opt/app-root/src/.m26 source: type: ConfigMap7 configMap: name: my-config8 - name: my-csi-volume9 mounts: - destinationPath: /opt/app-root/src/some_path10 source: type: CSI11 csi: driver: csi.sharedresource.openshift.io12 readOnly: true13 volumeAttributes:14 attribute: value
- 1 5 9
- Required. A unique name.
- 2 6 10
- Required. The absolute path of the mount point. It must not contain
..or:and doesn’t collide with the destination path generated by the builder. The/opt/app-root/srcis the default home directory for many Red Hat S2I-enabled images. - 3 7 11
- Required. The type of source,
ConfigMap,Secret, orCSI. - 4 8
- Required. The name of the source.
- 12
- Required. The driver that provides the ephemeral CSI volume.
- 13
- Required. This value must be set to
true. Provides a read-only volume. - 14
- Optional. The volume attributes of the ephemeral CSI volume. Consult the CSI driver’s documentation for supported attribute keys and values.
The Shared Resource CSI Driver is supported as a Technology Preview feature.
2.5.3. Custom build Copia collegamentoCollegamento copiato negli appunti!
The custom build strategy allows developers to define a specific builder image responsible for the entire build process. Using your own builder image allows you to customize your build process.
A custom builder image is a plain container image embedded with build process logic, for example for building RPMs or base images.
Custom builds run with a high level of privilege and are not available to users by default. Only users who can be trusted with cluster administration permissions should be granted access to run custom builds.
2.5.3.1. Using FROM image for custom builds Copia collegamentoCollegamento copiato negli appunti!
You can use the
customStrategy.from
Procedure
Set the
section:customStrategy.fromstrategy: customStrategy: from: kind: "DockerImage" name: "openshift/sti-image-builder"
2.5.3.2. Using secrets in custom builds Copia collegamentoCollegamento copiato negli appunti!
In addition to secrets for source and images that can be added to all build types, custom strategies allow adding an arbitrary list of secrets to the builder pod.
Procedure
To mount each secret at a specific location, edit the
andsecretSourcefields of themountPathYAML file:strategystrategy: customStrategy: secrets: - secretSource:1 name: "secret1" mountPath: "/tmp/secret1"2 - secretSource: name: "secret2" mountPath: "/tmp/secret2"
2.5.3.3. Using environment variables for custom builds Copia collegamentoCollegamento copiato negli appunti!
To make environment variables available to the custom build process, you can add environment variables to the
customStrategy
The environment variables defined there are passed to the pod that runs the custom build.
Procedure
Define a custom HTTP proxy to be used during build:
customStrategy: ... env: - name: "HTTP_PROXY" value: "http://myproxy.net:5187/"To manage environment variables defined in the build configuration, enter the following command:
$ oc set env <enter_variables>
2.5.3.4. Using custom builder images Copia collegamentoCollegamento copiato negli appunti!
OpenShift Container Platform’s custom build strategy enables you to define a specific builder image responsible for the entire build process. When you need a build to produce individual artifacts such as packages, JARs, WARs, installable ZIPs, or base images, use a custom builder image using the custom build strategy.
A custom builder image is a plain container image embedded with build process logic, which is used for building artifacts such as RPMs or base container images.
Additionally, the custom builder allows implementing any extended build process, such as a CI/CD flow that runs unit or integration tests.
2.5.3.4.1. Custom builder image Copia collegamentoCollegamento copiato negli appunti!
Upon invocation, a custom builder image receives the following environment variables with the information needed to proceed with the build:
| Variable Name | Description |
|---|---|
|
| The entire serialized JSON of the
|
|
| The URL of a Git repository with source to be built. |
|
| Uses the same value as
|
|
| Specifies the subdirectory of the Git repository to be used when building. Only present if defined. |
|
| The Git reference to be built. |
|
| The version of the OpenShift Container Platform master that created this build object. |
|
| The container image registry to push the image to. |
|
| The container image tag name for the image being built. |
|
| The path to the container registry credentials for running a
|
2.5.3.4.2. Custom builder workflow Copia collegamentoCollegamento copiato negli appunti!
Although custom builder image authors have flexibility in defining the build process, your builder image must adhere to the following required steps necessary for running a build inside of OpenShift Container Platform:
-
The object definition contains all the necessary information about input parameters for the build.
Build - Run the build process.
- If your build produces an image, push it to the output location of the build if it is defined. Other output locations can be passed with environment variables.
2.5.4. Pipeline build Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
The Pipeline build strategy allows developers to define a Jenkins pipeline for use by the Jenkins pipeline plugin. The build can be started, monitored, and managed by OpenShift Container Platform in the same way as any other build type.
Pipeline workflows are defined in a
jenkinsfile
2.5.4.1. Understanding OpenShift Container Platform pipelines Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
Pipelines give you control over building, deploying, and promoting your applications on OpenShift Container Platform. Using a combination of the Jenkins Pipeline build strategy,
jenkinsfiles
OpenShift Container Platform Jenkins Sync Plugin
The OpenShift Container Platform Jenkins Sync Plugin keeps the build configuration and build objects in sync with Jenkins jobs and builds, and provides the following:
- Dynamic job and run creation in Jenkins.
- Dynamic creation of agent pod templates from image streams, image stream tags, or config maps.
- Injection of environment variables.
- Pipeline visualization in the OpenShift Container Platform web console.
- Integration with the Jenkins Git plugin, which passes commit information from OpenShift Container Platform builds to the Jenkins Git plugin.
- Synchronization of secrets into Jenkins credential entries.
OpenShift Container Platform Jenkins Client Plugin
The OpenShift Container Platform Jenkins Client Plugin is a Jenkins plugin which aims to provide a readable, concise, comprehensive, and fluent Jenkins Pipeline syntax for rich interactions with an OpenShift Container Platform API Server. The plugin uses the OpenShift Container Platform command line tool,
oc
The Jenkins Client Plugin must be installed on your Jenkins master so the OpenShift Container Platform DSL will be available to use within the
jenkinsfile
For OpenShift Container Platform Pipelines within your project, you will must use the Jenkins Pipeline Build Strategy. This strategy defaults to using a
jenkinsfile
-
An inline field within your build configuration.
jenkinsfile -
A field within your build configuration that references the location of the
jenkinsfilePathto use relative to the sourcejenkinsfile.contextDir
The optional
jenkinsfilePath
contextDir
contextDir
jenkinsfilePath
jenkinsfile
2.5.4.2. Providing the Jenkins file for pipeline builds Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
The
jenkinsfile
You can supply the
jenkinsfile
- A file located within your source code repository.
-
Embedded as part of your build configuration using the field.
jenkinsfile
When using the first option, the
jenkinsfile
-
A file named at the root of your repository.
jenkinsfile -
A file named at the root of the source
jenkinsfileof your repository.contextDir -
A file name specified via the field of the
jenkinsfilePathsection of your BuildConfig, which is relative to the sourceJenkinsPipelineStrategyif supplied, otherwise it defaults to the root of the repository.contextDir
The
jenkinsfile
Procedure
To provide the Jenkins file, you can either:
- Embed the Jenkins file in the build configuration.
- Include in the build configuration a reference to the Git repository that contains the Jenkins file.
Embedded Definition
kind: "BuildConfig"
apiVersion: "v1"
metadata:
name: "sample-pipeline"
spec:
strategy:
jenkinsPipelineStrategy:
jenkinsfile: |-
node('agent') {
stage 'build'
openshiftBuild(buildConfig: 'ruby-sample-build', showBuildLogs: 'true')
stage 'deploy'
openshiftDeploy(deploymentConfig: 'frontend')
}
Reference to Git Repository
kind: "BuildConfig"
apiVersion: "v1"
metadata:
name: "sample-pipeline"
spec:
source:
git:
uri: "https://github.com/openshift/ruby-hello-world"
strategy:
jenkinsPipelineStrategy:
jenkinsfilePath: some/repo/dir/filename
- 1
- The optional
jenkinsfilePathfield specifies the name of the file to use, relative to the sourcecontextDir. IfcontextDiris omitted, it defaults to the root of the repository. IfjenkinsfilePathis omitted, it defaults tojenkinsfile.
2.5.4.3. Using environment variables for pipeline builds Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
To make environment variables available to the Pipeline build process, you can add environment variables to the
jenkinsPipelineStrategy
Once defined, the environment variables will be set as parameters for any Jenkins job associated with the build configuration.
Procedure
To define environment variables to be used during build, edit the YAML file:
jenkinsPipelineStrategy: ... env: - name: "FOO" value: "BAR"
You can also manage environment variables defined in the build configuration with the
oc set env
2.5.4.3.1. Mapping between BuildConfig environment variables and Jenkins job parameters Copia collegamentoCollegamento copiato negli appunti!
When a Jenkins job is created or updated based on changes to a Pipeline strategy build configuration, any environment variables in the build configuration are mapped to Jenkins job parameters definitions, where the default values for the Jenkins job parameters definitions are the current values of the associated environment variables.
After the Jenkins job’s initial creation, you can still add additional parameters to the job from the Jenkins console. The parameter names differ from the names of the environment variables in the build configuration. The parameters are honored when builds are started for those Jenkins jobs.
How you start builds for the Jenkins job dictates how the parameters are set.
-
If you start with , the values of the environment variables in the build configuration are the parameters set for the corresponding job instance. Any changes you make to the parameters' default values from the Jenkins console are ignored. The build configuration values take precedence.
oc start-build If you start with
, the values for the environment variables specified in theoc start-build -eoption take precedence.-e- If you specify an environment variable not listed in the build configuration, they will be added as a Jenkins job parameter definitions.
-
Any changes you make from the Jenkins console to the parameters corresponding to the environment variables are ignored. The build configuration and what you specify with takes precedence.
oc start-build -e
- If you start the Jenkins job with the Jenkins console, then you can control the setting of the parameters with the Jenkins console as part of starting a build for the job.
It is recommended that you specify in the build configuration all possible environment variables to be associated with job parameters. Doing so reduces disk I/O and improves performance during Jenkins processing.
2.5.4.4. Pipeline build tutorial Copia collegamentoCollegamento copiato negli appunti!
The Pipeline build strategy is deprecated in OpenShift Container Platform 4. Equivalent and improved functionality is present in the OpenShift Container Platform Pipelines based on Tekton.
Jenkins images on OpenShift Container Platform are fully supported and users should follow Jenkins user documentation for defining their
jenkinsfile
This example demonstrates how to create an OpenShift Container Platform Pipeline that will build, deploy, and verify a
Node.js/MongoDB
nodejs-mongodb.json
Procedure
Create the Jenkins master:
$ oc project <project_name>Select the project that you want to use or create a new project with
.oc new-project <project_name>$ oc new-app jenkins-ephemeral1 If you want to use persistent storage, use
instead.jenkins-persistentCreate a file named
with the following content:nodejs-sample-pipeline.yamlNoteThis creates a
object that employs the Jenkins pipeline strategy to build, deploy, and scale theBuildConfigexample application.Node.js/MongoDBkind: "BuildConfig" apiVersion: "v1" metadata: name: "nodejs-sample-pipeline" spec: strategy: jenkinsPipelineStrategy: jenkinsfile: <pipeline content from below> type: JenkinsPipelineAfter you create a
object with aBuildConfig, tell the pipeline what to do by using an inlinejenkinsPipelineStrategy:jenkinsfileNoteThis example does not set up a Git repository for the application.
The following
content is written in Groovy using the OpenShift Container Platform DSL. For this example, include inline content in thejenkinsfileobject using the YAML Literal Style, though including aBuildConfigin your source repository is the preferred method.jenkinsfiledef templatePath = 'https://raw.githubusercontent.com/openshift/nodejs-ex/master/openshift/templates/nodejs-mongodb.json'1 def templateName = 'nodejs-mongodb-example'2 pipeline { agent { node { label 'nodejs'3 } } options { timeout(time: 20, unit: 'MINUTES')4 } stages { stage('preamble') { steps { script { openshift.withCluster() { openshift.withProject() { echo "Using project: ${openshift.project()}" } } } } } stage('cleanup') { steps { script { openshift.withCluster() { openshift.withProject() { openshift.selector("all", [ template : templateName ]).delete()5 if (openshift.selector("secrets", templateName).exists()) {6 openshift.selector("secrets", templateName).delete() } } } } } } stage('create') { steps { script { openshift.withCluster() { openshift.withProject() { openshift.newApp(templatePath)7 } } } } } stage('build') { steps { script { openshift.withCluster() { openshift.withProject() { def builds = openshift.selector("bc", templateName).related('builds') timeout(5) {8 builds.untilEach(1) { return (it.object().status.phase == "Complete") } } } } } } } stage('deploy') { steps { script { openshift.withCluster() { openshift.withProject() { def rm = openshift.selector("dc", templateName).rollout() timeout(5) {9 openshift.selector("dc", templateName).related('pods').untilEach(1) { return (it.object().status.phase == "Running") } } } } } } } stage('tag') { steps { script { openshift.withCluster() { openshift.withProject() { openshift.tag("${templateName}:latest", "${templateName}-staging:latest")10 } } } } } } }- 1
- Path of the template to use.
- 1 2
- Name of the template that will be created.
- 3
- Spin up a
node.jsagent pod on which to run this build. - 4
- Set a timeout of 20 minutes for this pipeline.
- 5
- Delete everything with this template label.
- 6
- Delete any secrets with this template label.
- 7
- Create a new application from the
templatePath. - 8
- Wait up to five minutes for the build to complete.
- 9
- Wait up to five minutes for the deployment to complete.
- 10
- If everything else succeeded, tag the
$ {templateName}:latestimage as$ {templateName}-staging:latest. A pipeline build configuration for the staging environment can watch for the$ {templateName}-staging:latestimage to change and then deploy it to the staging environment.
NoteThe previous example was written using the declarative pipeline style, but the older scripted pipeline style is also supported.
Create the Pipeline
in your OpenShift Container Platform cluster:BuildConfig$ oc create -f nodejs-sample-pipeline.yamlIf you do not want to create your own file, you can use the sample from the Origin repository by running:
$ oc create -f https://raw.githubusercontent.com/openshift/origin/master/examples/jenkins/pipeline/nodejs-sample-pipeline.yaml
Start the Pipeline:
$ oc start-build nodejs-sample-pipelineNoteAlternatively, you can start your pipeline with the OpenShift Container Platform web console by navigating to the Builds
Pipeline section and clicking Start Pipeline, or by visiting the Jenkins Console, navigating to the Pipeline that you created, and clicking Build Now. Once the pipeline is started, you should see the following actions performed within your project:
- A job instance is created on the Jenkins server.
- An agent pod is launched, if your pipeline requires one.
The pipeline runs on the agent pod, or the master if no agent is required.
-
Any previously created resources with the label will be deleted.
template=nodejs-mongodb-example -
A new application, and all of its associated resources, will be created from the template.
nodejs-mongodb-example A build will be started using the
nodejs-mongodb-example.BuildConfig- The pipeline will wait until the build has completed to trigger the next stage.
A deployment will be started using the
deployment configuration.nodejs-mongodb-example- The pipeline will wait until the deployment has completed to trigger the next stage.
-
If the build and deploy are successful, the image will be tagged as
nodejs-mongodb-example:latest.nodejs-mongodb-example:stage
-
Any previously created resources with the
The agent pod is deleted, if one was required for the pipeline.
NoteThe best way to visualize the pipeline execution is by viewing it in the OpenShift Container Platform web console. You can view your pipelines by logging in to the web console and navigating to Builds
Pipelines.
2.5.5. Adding secrets with web console Copia collegamentoCollegamento copiato negli appunti!
You can add a secret to your build configuration so that it can access a private repository.
Procedure
To add a secret to your build configuration so that it can access a private repository from the OpenShift Container Platform web console:
- Create a new OpenShift Container Platform project.
- Create a secret that contains credentials for accessing a private source code repository.
- Create a build configuration.
-
On the build configuration editor page or in the page of the web console, set the Source Secret.
create app from builder image - Click Save.
2.5.6. Enabling pulling and pushing Copia collegamentoCollegamento copiato negli appunti!
You can enable pulling to a private registry by setting the pull secret and pushing by setting the push secret in the build configuration.
Procedure
To enable pulling to a private registry:
- Set the pull secret in the build configuration.
To enable pushing:
- Set the push secret in the build configuration.
2.6. Custom image builds with Buildah Copia collegamentoCollegamento copiato negli appunti!
With OpenShift Container Platform 4.11, a docker socket will not be present on the host nodes. This means the mount docker socket option of a custom build is not guaranteed to provide an accessible docker socket for use within a custom build image.
If you require this capability in order to build and push images, add the Buildah tool your custom build image and use it to build and push the image within your custom build logic. The following is an example of how to run custom builds with Buildah.
Using the custom build strategy requires permissions that normal users do not have by default because it allows the user to execute arbitrary code inside a privileged container running on the cluster. This level of access can be used to compromise the cluster and therefore should be granted only to users who are trusted with administrative privileges on the cluster.
2.6.1. Prerequisites Copia collegamentoCollegamento copiato negli appunti!
- Review how to grant custom build permissions.
2.6.2. Creating custom build artifacts Copia collegamentoCollegamento copiato negli appunti!
You must create the image you want to use as your custom build image.
Procedure
Starting with an empty directory, create a file named
with the following content:DockerfileFROM registry.redhat.io/rhel8/buildah # In this example, `/tmp/build` contains the inputs that build when this # custom builder image is run. Normally the custom builder image fetches # this content from some location at build time, by using git clone as an example. ADD dockerfile.sample /tmp/input/Dockerfile ADD build.sh /usr/bin RUN chmod a+x /usr/bin/build.sh # /usr/bin/build.sh contains the actual custom build logic that will be run when # this custom builder image is run. ENTRYPOINT ["/usr/bin/build.sh"]In the same directory, create a file named
. This file is included in the custom build image and defines the image that is produced by the custom build:dockerfile.sampleFROM registry.access.redhat.com/ubi8/ubi RUN touch /tmp/buildIn the same directory, create a file named
. This file contains the logic that is run when the custom build runs:build.sh#!/bin/sh # Note that in this case the build inputs are part of the custom builder image, but normally this # is retrieved from an external source. cd /tmp/input # OUTPUT_REGISTRY and OUTPUT_IMAGE are env variables provided by the custom # build framework TAG="${OUTPUT_REGISTRY}/${OUTPUT_IMAGE}" # performs the build of the new image defined by dockerfile.sample buildah --storage-driver vfs bud --isolation chroot -t ${TAG} . # buildah requires a slight modification to the push secret provided by the service # account to use it for pushing the image cp /var/run/secrets/openshift.io/push/.dockercfg /tmp (echo "{ \"auths\": " ; cat /var/run/secrets/openshift.io/push/.dockercfg ; echo "}") > /tmp/.dockercfg # push the new image to the target for the build buildah --storage-driver vfs push --tls-verify=false --authfile /tmp/.dockercfg ${TAG}
2.6.3. Build custom builder image Copia collegamentoCollegamento copiato negli appunti!
You can use OpenShift Container Platform to build and push custom builder images to use in a custom strategy.
Prerequisites
- Define all the inputs that will go into creating your new custom builder image.
Procedure
Define a
object that will build your custom builder image:BuildConfig$ oc new-build --binary --strategy=docker --name custom-builder-imageFrom the directory in which you created your custom build image, run the build:
$ oc start-build custom-builder-image --from-dir . -FAfter the build completes, your new custom builder image is available in your project in an image stream tag that is named
.custom-builder-image:latest
2.6.4. Use custom builder image Copia collegamentoCollegamento copiato negli appunti!
You can define a
BuildConfig
Prerequisites
- Define all the required inputs for new custom builder image.
- Build your custom builder image.
Procedure
Create a file named
. This file defines thebuildconfig.yamlobject that is created in your project and executed:BuildConfigkind: BuildConfig apiVersion: build.openshift.io/v1 metadata: name: sample-custom-build labels: name: sample-custom-build annotations: template.alpha.openshift.io/wait-for-ready: 'true' spec: strategy: type: Custom customStrategy: forcePull: true from: kind: ImageStreamTag name: custom-builder-image:latest namespace: <yourproject>1 output: to: kind: ImageStreamTag name: sample-custom:latest- 1
- Specify your project name.
Create the
:BuildConfig$ oc create -f buildconfig.yamlCreate a file named
. This file defines the image stream to which the build will push the image:imagestream.yamlkind: ImageStream apiVersion: image.openshift.io/v1 metadata: name: sample-custom spec: {}Create the imagestream:
$ oc create -f imagestream.yamlRun your custom build:
$ oc start-build sample-custom-build -FWhen the build runs, it launches a pod running the custom builder image that was built earlier. The pod runs the
logic that is defined as the entrypoint for the custom builder image. Thebuild.shlogic invokes Buildah to build thebuild.shthat was embedded in the custom builder image, and then uses Buildah to push the new image to thedockerfile.sample.sample-custom image stream
2.7. Performing and configuring basic builds Copia collegamentoCollegamento copiato negli appunti!
The following sections provide instructions for basic build operations, including starting and canceling builds, editing
BuildConfigs
BuildConfigs
2.7.1. Starting a build Copia collegamentoCollegamento copiato negli appunti!
You can manually start a new build from an existing build configuration in your current project.
Procedure
To manually start a build, enter the following command:
$ oc start-build <buildconfig_name>
2.7.1.1. Re-running a build Copia collegamentoCollegamento copiato negli appunti!
You can manually re-run a build using the
--from-build
Procedure
To manually re-run a build, enter the following command:
$ oc start-build --from-build=<build_name>
2.7.1.2. Streaming build logs Copia collegamentoCollegamento copiato negli appunti!
You can specify the
--follow
stdout
Procedure
To manually stream a build’s logs in
, enter the following command:stdout$ oc start-build <buildconfig_name> --follow
2.7.1.3. Setting environment variables when starting a build Copia collegamentoCollegamento copiato negli appunti!
You can specify the
--env
Procedure
To specify a desired environment variable, enter the following command:
$ oc start-build <buildconfig_name> --env=<key>=<value>
2.7.1.4. Starting a build with source Copia collegamentoCollegamento copiato negli appunti!
Rather than relying on a Git source pull or a Dockerfile for a build, you can also start a build by directly pushing your source, which could be the contents of a Git or SVN working directory, a set of pre-built binary artifacts you want to deploy, or a single file. This can be done by specifying one of the following options for the
start-build
| Option | Description |
|---|---|
|
| Specifies a directory that will be archived and used as a binary input for the build. |
|
| Specifies a single file that will be the only file in the build source. The file is placed in the root of an empty directory with the same file name as the original file provided. |
|
| Specifies a path to a local repository to use as the binary input for a build. Add the
|
When passing any of these options directly to the build, the contents are streamed to the build and override the current build source settings.
Builds triggered from binary input will not preserve the source on the server, so rebuilds triggered by base image changes will use the source specified in the build configuration.
Procedure
Start a build from a source using the following command to send the contents of a local Git repository as an archive from the tag
:v2$ oc start-build hello-world --from-repo=../hello-world --commit=v2
2.7.2. Canceling a build Copia collegamentoCollegamento copiato negli appunti!
You can cancel a build using the web console, or with the following CLI command.
Procedure
To manually cancel a build, enter the following command:
$ oc cancel-build <build_name>
2.7.2.1. Canceling multiple builds Copia collegamentoCollegamento copiato negli appunti!
You can cancel multiple builds with the following CLI command.
Procedure
To manually cancel multiple builds, enter the following command:
$ oc cancel-build <build1_name> <build2_name> <build3_name>
2.7.2.2. Canceling all builds Copia collegamentoCollegamento copiato negli appunti!
You can cancel all builds from the build configuration with the following CLI command.
Procedure
To cancel all builds, enter the following command:
$ oc cancel-build bc/<buildconfig_name>
2.7.2.3. Canceling all builds in a given state Copia collegamentoCollegamento copiato negli appunti!
You can cancel all builds in a given state, such as
new
pending
Procedure
To cancel all in a given state, enter the following command:
$ oc cancel-build bc/<buildconfig_name>
2.7.3. Editing a BuildConfig Copia collegamentoCollegamento copiato negli appunti!
To edit your build configurations, you use the Edit BuildConfig option in the Builds view of the Developer perspective.
You can use either of the following views to edit a
BuildConfig
-
The Form view enables you to edit your using the standard form fields and checkboxes.
BuildConfig -
The YAML view enables you to edit your with full control over the operations.
BuildConfig
You can switch between the Form view and YAML view without losing any data. The data in the Form view is transferred to the YAML view and vice versa.
Procedure
-
In the Builds view of the Developer perspective, click the menu
to see the Edit BuildConfig option.
- Click Edit BuildConfig to see the Form view option.
In the Git section, enter the Git repository URL for the codebase you want to use to create an application. The URL is then validated.
Optional: Click Show Advanced Git Options to add details such as:
- Git Reference to specify a branch, tag, or commit that contains code you want to use to build the application.
- Context Dir to specify the subdirectory that contains code you want to use to build the application.
- Source Secret to create a Secret Name with credentials for pulling your source code from a private repository.
In the Build from section, select the option that you would like to build from. You can use the following options:
- Image Stream tag references an image for a given image stream and tag. Enter the project, image stream, and tag of the location you would like to build from and push to.
- Image Stream image references an image for a given image stream and image name. Enter the image stream image you would like to build from. Also enter the project, image stream, and tag to push to.
- Docker image: The Docker image is referenced through a Docker image repository. You will also need to enter the project, image stream, and tag to refer to where you would like to push to.
- Optional: In the Environment Variables section, add the environment variables associated with the project by using the Name and Value fields. To add more environment variables, use Add Value, or Add from ConfigMap and Secret .
Optional: To further customize your application, use the following advanced options:
- Trigger
- Triggers a new image build when the builder image changes. Add more triggers by clicking Add Trigger and selecting the Type and Secret.
- Secrets
- Adds secrets for your application. Add more secrets by clicking Add secret and selecting the Secret and Mount point.
- Policy
- Click Run policy to select the build run policy. The selected policy determines the order in which builds created from the build configuration must run.
- Hooks
- Select Run build hooks after image is built to run commands at the end of the build and verify the image. Add Hook type, Command, and Arguments to append to the command.
-
Click Save to save the .
BuildConfig
2.7.4. Deleting a BuildConfig Copia collegamentoCollegamento copiato negli appunti!
You can delete a
BuildConfig
Procedure
To delete a
, enter the following command:BuildConfig$ oc delete bc <BuildConfigName>This also deletes all builds that were instantiated from this
.BuildConfigTo delete a
and keep the builds instatiated from theBuildConfig, specify theBuildConfigflag when you enter the following command:--cascade=false$ oc delete --cascade=false bc <BuildConfigName>
2.7.5. Viewing build details Copia collegamentoCollegamento copiato negli appunti!
You can view build details with the web console or by using the
oc describe
This displays information including:
- The build source.
- The build strategy.
- The output destination.
- Digest of the image in the destination registry.
- How the build was created.
If the build uses the
Docker
Source
oc describe
Procedure
To view build details, enter the following command:
$ oc describe build <build_name>
2.7.6. Accessing build logs Copia collegamentoCollegamento copiato negli appunti!
You can access build logs using the web console or the CLI.
Procedure
To stream the logs using the build directly, enter the following command:
$ oc describe build <build_name>
2.7.6.1. Accessing BuildConfig logs Copia collegamentoCollegamento copiato negli appunti!
You can access
BuildConfig
Procedure
To stream the logs of the latest build for a
, enter the following command:BuildConfig$ oc logs -f bc/<buildconfig_name>
2.7.6.2. Accessing BuildConfig logs for a given version build Copia collegamentoCollegamento copiato negli appunti!
You can access logs for a given version build for a
BuildConfig
Procedure
To stream the logs for a given version build for a
, enter the following command:BuildConfig$ oc logs --version=<number> bc/<buildconfig_name>
2.7.6.3. Enabling log verbosity Copia collegamentoCollegamento copiato negli appunti!
You can enable a more verbose output by passing the
BUILD_LOGLEVEL
sourceStrategy
dockerStrategy
BuildConfig
An administrator can set the default build verbosity for the entire OpenShift Container Platform instance by configuring
env/BUILD_LOGLEVEL
BUILD_LOGLEVEL
BuildConfig
--build-loglevel
oc start-build
Available log levels for source builds are as follows:
| Level 0 | Produces output from containers running the
|
| Level 1 | Produces basic information about the executed process. |
| Level 2 | Produces very detailed information about the executed process. |
| Level 3 | Produces very detailed information about the executed process, and a listing of the archive contents. |
| Level 4 | Currently produces the same information as level 3. |
| Level 5 | Produces everything mentioned on previous levels and additionally provides docker push messages. |
Procedure
To enable more verbose output, pass the
environment variable as part of theBUILD_LOGLEVELorsourceStrategyin adockerStrategy:BuildConfigsourceStrategy: ... env: - name: "BUILD_LOGLEVEL" value: "2"1 - 1
- Adjust this value to the desired log level.
2.8. Triggering and modifying builds Copia collegamentoCollegamento copiato negli appunti!
The following sections outline how to trigger builds and modify builds using build hooks.
2.8.1. Build triggers Copia collegamentoCollegamento copiato negli appunti!
When defining a
BuildConfig
BuildConfig
- Webhook
- Image change
- Configuration change
2.8.1.1. Webhook triggers Copia collegamentoCollegamento copiato negli appunti!
Webhook triggers allow you to trigger a new build by sending a request to the OpenShift Container Platform API endpoint. You can define these triggers using GitHub, GitLab, Bitbucket, or Generic webhooks.
Currently, OpenShift Container Platform webhooks only support the analogous versions of the push event for each of the Git-based Source Code Management (SCM) systems. All other event types are ignored.
When the push events are processed, the OpenShift Container Platform control plane host confirms if the branch reference inside the event matches the branch reference in the corresponding
BuildConfig
oc new-app
oc new-build
For all webhooks, you must define a secret with a key named
WebHookSecretKey
For example here is a GitHub webhook with a reference to a secret named
mysecret
type: "GitHub"
github:
secretReference:
name: "mysecret"
The secret is then defined as follows. Note that the value of the secret is base64 encoded as is required for any
data
Secret
- kind: Secret
apiVersion: v1
metadata:
name: mysecret
creationTimestamp:
data:
WebHookSecretKey: c2VjcmV0dmFsdWUx
2.8.1.1.1. Using GitHub webhooks Copia collegamentoCollegamento copiato negli appunti!
GitHub webhooks handle the call made by GitHub when a repository is updated. When defining the trigger, you must specify a secret, which is part of the URL you supply to GitHub when configuring the webhook.
Example GitHub webhook definition:
type: "GitHub"
github:
secretReference:
name: "mysecret"
The secret used in the webhook trigger configuration is not the same as
secret
X-Hub-Signature
The payload URL is returned as the GitHub Webhook URL by the
oc describe
Example output
https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/github
Prerequisites
-
Create a from a GitHub repository.
BuildConfig
Procedure
To configure a GitHub Webhook:
After creating a
from a GitHub repository, run:BuildConfig$ oc describe bc/<name-of-your-BuildConfig>This generates a webhook GitHub URL that looks like:
Example output
<https://api.starter-us-east-1.openshift.com:443/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/github- Cut and paste this URL into GitHub, from the GitHub web console.
-
In your GitHub repository, select Add Webhook from Settings
Webhooks. - Paste the URL output into the Payload URL field.
-
Change the Content Type from GitHub’s default to
application/x-www-form-urlencoded.application/json Click Add webhook.
You should see a message from GitHub stating that your webhook was successfully configured.
Now, when you push a change to your GitHub repository, a new build automatically starts, and upon a successful build a new deployment starts.
NoteGogs supports the same webhook payload format as GitHub. Therefore, if you are using a Gogs server, you can define a GitHub webhook trigger on your
and trigger it by your Gogs server as well.BuildConfig
Given a file containing a valid JSON payload, such as
, you can manually trigger the webhook withpayload.json:curl$ curl -H "X-GitHub-Event: push" -H "Content-Type: application/json" -k -X POST --data-binary @payload.json https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/githubThe
argument is only necessary if your API server does not have a properly signed certificate.-k
The build will only be triggered if the
ref
ref
source.git
BuildConfig
2.8.1.1.2. Using GitLab webhooks Copia collegamentoCollegamento copiato negli appunti!
GitLab webhooks handle the call made by GitLab when a repository is updated. As with the GitHub triggers, you must specify a secret. The following example is a trigger definition YAML within the
BuildConfig
type: "GitLab"
gitlab:
secretReference:
name: "mysecret"
The payload URL is returned as the GitLab Webhook URL by the
oc describe
Example output
https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/gitlab
Procedure
To configure a GitLab Webhook:
Describe the
to get the webhook URL:BuildConfig$ oc describe bc <name>-
Copy the webhook URL, replacing with your secret value.
<secret> - Follow the GitLab setup instructions to paste the webhook URL into your GitLab repository settings.
Given a file containing a valid JSON payload, such as
, you can manually trigger the webhook withpayload.json:curl$ curl -H "X-GitLab-Event: Push Hook" -H "Content-Type: application/json" -k -X POST --data-binary @payload.json https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/gitlabThe
argument is only necessary if your API server does not have a properly signed certificate.-k
2.8.1.1.3. Using Bitbucket webhooks Copia collegamentoCollegamento copiato negli appunti!
Bitbucket webhooks handle the call made by Bitbucket when a repository is updated. Similar to the previous triggers, you must specify a secret. The following example is a trigger definition YAML within the
BuildConfig
type: "Bitbucket"
bitbucket:
secretReference:
name: "mysecret"
The payload URL is returned as the Bitbucket Webhook URL by the
oc describe
Example output
https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/bitbucket
Procedure
To configure a Bitbucket Webhook:
Describe the 'BuildConfig' to get the webhook URL:
$ oc describe bc <name>-
Copy the webhook URL, replacing with your secret value.
<secret> - Follow the Bitbucket setup instructions to paste the webhook URL into your Bitbucket repository settings.
Given a file containing a valid JSON payload, such as
, you can manually trigger the webhook withpayload.json:curl$ curl -H "X-Event-Key: repo:push" -H "Content-Type: application/json" -k -X POST --data-binary @payload.json https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/bitbucketThe
argument is only necessary if your API server does not have a properly signed certificate.-k
2.8.1.1.4. Using generic webhooks Copia collegamentoCollegamento copiato negli appunti!
Generic webhooks are invoked from any system capable of making a web request. As with the other webhooks, you must specify a secret, which is part of the URL that the caller must use to trigger the build. The secret ensures the uniqueness of the URL, preventing others from triggering the build. The following is an example trigger definition YAML within the
BuildConfig
type: "Generic"
generic:
secretReference:
name: "mysecret"
allowEnv: true
- 1
- Set to
trueto allow a generic webhook to pass in environment variables.
Procedure
To set up the caller, supply the calling system with the URL of the generic webhook endpoint for your build:
Example output
https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/genericThe caller must invoke the webhook as a
operation.POSTTo invoke the webhook manually you can use
:curl$ curl -X POST -k https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/genericThe HTTP verb must be set to
. The insecurePOSTflag is specified to ignore certificate validation. This second flag is not necessary if your cluster has properly signed certificates.-kThe endpoint can accept an optional payload with the following format:
git: uri: "<url to git repository>" ref: "<optional git reference>" commit: "<commit hash identifying a specific git commit>" author: name: "<author name>" email: "<author e-mail>" committer: name: "<committer name>" email: "<committer e-mail>" message: "<commit message>" env:1 - name: "<variable name>" value: "<variable value>"- 1
- Similar to the
BuildConfigenvironment variables, the environment variables defined here are made available to your build. If these variables collide with theBuildConfigenvironment variables, these variables take precedence. By default, environment variables passed by webhook are ignored. Set theallowEnvfield totrueon the webhook definition to enable this behavior.
To pass this payload using
, define it in a file namedcurland run:payload_file.yaml$ curl -H "Content-Type: application/yaml" --data-binary @payload_file.yaml -X POST -k https://<openshift_api_host:port>/apis/build.openshift.io/v1/namespaces/<namespace>/buildconfigs/<name>/webhooks/<secret>/genericThe arguments are the same as the previous example with the addition of a header and a payload. The
argument sets the-Hheader toContent-Typeorapplication/yamldepending on your payload format. Theapplication/jsonargument is used to send a binary payload with newlines intact with the--data-binaryrequest.POST
OpenShift Container Platform permits builds to be triggered by the generic webhook even if an invalid request payload is presented, for example, invalid content type, unparsable or invalid content, and so on. This behavior is maintained for backwards compatibility. If an invalid request payload is presented, OpenShift Container Platform returns a warning in JSON format as part of its
HTTP 200 OK
2.8.1.1.5. Displaying webhook URLs Copia collegamentoCollegamento copiato negli appunti!
You can use the following command to display webhook URLs associated with a build configuration. If the command does not display any webhook URLs, then no webhook trigger is defined for that build configuration.
Procedure
-
To display any webhook URLs associated with a , run:
BuildConfig
$ oc describe bc <name>
2.8.1.2. Using image change triggers Copia collegamentoCollegamento copiato negli appunti!
As a developer, you can configure your build to run automatically every time a base image changes.
You can use image change triggers to automatically invoke your build when a new version of an upstream image is available. For example, if a build is based on a RHEL image, you can trigger that build to run any time the RHEL image changes. As a result, the application image is always running on the latest RHEL base image.
Image streams that point to container images in v1 container registries only trigger a build once when the image stream tag becomes available and not on subsequent image updates. This is due to the lack of uniquely identifiable images in v1 container registries.
Procedure
Define an
that points to the upstream image you want to use as a trigger:ImageStreamkind: "ImageStream" apiVersion: "v1" metadata: name: "ruby-20-centos7"This defines the image stream that is tied to a container image repository located at
. The<system-registry>/<namespace>/ruby-20-centos7is defined as a service with the name<system-registry>running in OpenShift Container Platform.docker-registryIf an image stream is the base image for the build, set the
field in the build strategy to point to thefrom:ImageStreamstrategy: sourceStrategy: from: kind: "ImageStreamTag" name: "ruby-20-centos7:latest"In this case, the
definition is consuming thesourceStrategytag of the image stream namedlatestlocated within this namespace.ruby-20-centos7Define a build with one or more triggers that point to
:ImageStreamstype: "ImageChange"1 imageChange: {} type: "ImageChange"2 imageChange: from: kind: "ImageStreamTag" name: "custom-image:latest"- 1
- An image change trigger that monitors the
ImageStreamandTagas defined by the build strategy’sfromfield. TheimageChangeobject here must be empty. - 2
- An image change trigger that monitors an arbitrary image stream. The
imageChangepart, in this case, must include afromfield that references theImageStreamTagto monitor.
When using an image change trigger for the strategy image stream, the generated build is supplied with an immutable docker tag that points to the latest image corresponding to that tag. This new image reference is used by the strategy when it executes for the build.
For other image change triggers that do not reference the strategy image stream, a new build is started, but the build strategy is not updated with a unique image reference.
Since this example has an image change trigger for the strategy, the resulting build is:
strategy:
sourceStrategy:
from:
kind: "DockerImage"
name: "172.30.17.3:5001/mynamespace/ruby-20-centos7:<immutableid>"
This ensures that the triggered build uses the new image that was just pushed to the repository, and the build can be re-run any time with the same inputs.
You can pause an image change trigger to allow multiple changes on the referenced image stream before a build is started. You can also set the
paused
ImageChangeTrigger
BuildConfig
type: "ImageChange"
imageChange:
from:
kind: "ImageStreamTag"
name: "custom-image:latest"
paused: true
In addition to setting the image field for all
Strategy
OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE
If a build is triggered due to a webhook trigger or manual request, the build that is created uses the
<immutableid>
ImageStream
Strategy
2.8.1.3. Identifying the image change trigger of a build Copia collegamentoCollegamento copiato negli appunti!
As a developer, if you have image change triggers, you can identify which image change initiated the last build. This can be useful for debugging or troubleshooting builds.
Example BuildConfig
apiVersion: build.openshift.io/v1
kind: BuildConfig
metadata:
name: bc-ict-example
namespace: bc-ict-example-namespace
spec:
# ...
triggers:
- imageChange:
from:
kind: ImageStreamTag
name: input:latest
namespace: bc-ict-example-namespace
- imageChange:
from:
kind: ImageStreamTag
name: input2:latest
namespace: bc-ict-example-namespace
type: ImageChange
status:
imageChangeTriggers:
- from:
name: input:latest
namespace: bc-ict-example-namespace
lastTriggerTime: "2021-06-30T13:47:53Z"
lastTriggeredImageID: image-registry.openshift-image-registry.svc:5000/bc-ict-example-namespace/input@sha256:0f88ffbeb9d25525720bfa3524cb1bf0908b7f791057cf1acfae917b11266a69
- from:
name: input2:latest
namespace: bc-ict-example-namespace
lastTriggeredImageID: image-registry.openshift-image-registry.svc:5000/bc-ict-example-namespace/input2@sha256:0f88ffbeb9d25525720bfa3524cb2ce0908b7f791057cf1acfae917b11266a69
lastVersion: 1
This example omits elements that are not related to image change triggers.
Prerequisites
- You have configured multiple image change triggers. These triggers have triggered one or more builds.
Procedure
In
to identify thebuildConfig.status.imageChangeTriggersthat has the latest timestamp.lastTriggerTimeThis
ImageChangeTriggerStatusThen you use the `name` and `namespace` from that build to find the corresponding image change trigger in `buildConfig.spec.triggers`.-
Under , compare timestamps to identify the latest
imageChangeTriggers
Image change triggers
In your build configuration,
buildConfig.spec.triggers
BuildTriggerPolicy
Each
BuildTriggerPolicy
type
type
BuildTriggerPolicy
For image change triggers, the value of
type
ImageChange
imageChange
ImageChangeTrigger
-
: This field, which is not shown in the example, is deprecated in OpenShift Container Platform 4.8 and will be ignored in a future release. It contains the resolved image reference for the
lastTriggeredImageIDwhen the last build was triggered from thisImageStreamTag.BuildConfig -
: You can use this field, which is not shown in the example, to temporarily disable this particular image change trigger.
paused -
: You use this field to reference the
fromthat drives this image change trigger. Its type is the core Kubernetes type,ImageStreamTag.OwnerReference
The
from
kind: For image change triggers, the only supported value is ImageStreamTag. namespace
ImageStreamTag
name
ImageStreamTag
Image change trigger status
In your build configuration,
buildConfig.status.imageChangeTriggers
ImageChangeTriggerStatus
ImageChangeTriggerStatus
from
lastTriggeredImageID
lastTriggerTime
The
ImageChangeTriggerStatus
lastTriggerTime
name
namespace
buildConfig.spec.triggers
The
lastTriggerTime
ImageChangeTriggerStatus
ImageChangeTriggerStatus
name
namespace
buildConfig.spec.triggers
2.8.1.4. Configuration change triggers Copia collegamentoCollegamento copiato negli appunti!
A configuration change trigger allows a build to be automatically invoked as soon as a new
BuildConfig
The following is an example trigger definition YAML within the
BuildConfig
type: "ConfigChange"
Configuration change triggers currently only work when creating a new
BuildConfig
BuildConfig
2.8.1.4.1. Setting triggers manually Copia collegamentoCollegamento copiato negli appunti!
Triggers can be added to and removed from build configurations with
oc set triggers
Procedure
To set a GitHub webhook trigger on a build configuration, use:
$ oc set triggers bc <name> --from-githubTo set an imagechange trigger, use:
$ oc set triggers bc <name> --from-image='<image>'To remove a trigger, add
:--remove$ oc set triggers bc <name> --from-bitbucket --remove
When a webhook trigger already exists, adding it again regenerates the webhook secret.
For more information, consult the help documentation with by running:
$ oc set triggers --help
2.8.2. Build hooks Copia collegamentoCollegamento copiato negli appunti!
Build hooks allow behavior to be injected into the build process.
The
postCommit
BuildConfig
The current working directory is set to the image’s
WORKDIR
The hook fails if the script or command returns a non-zero exit code or if starting the temporary container fails. When the hook fails it marks the build as failed and the image is not pushed to a registry. The reason for failing can be inspected by looking at the build logs.
Build hooks can be used to run unit tests to verify the image before the build is marked complete and the image is made available in a registry. If all tests pass and the test runner returns with exit code
0
The
postCommit
2.8.2.1. Configuring post commit build hooks Copia collegamentoCollegamento copiato negli appunti!
There are different ways to configure the post build hook. All forms in the following examples are equivalent and run
bundle exec rake test --verbose
Procedure
Shell script:
postCommit: script: "bundle exec rake test --verbose"The
value is a shell script to be run withscript. Use this when a shell script is appropriate to execute the build hook. For example, for running unit tests as above. To control the image entry point, or if the image does not have/bin/sh -ic, use/bin/shand/orcommand.argsNoteThe additional
flag was introduced to improve the experience working with CentOS and RHEL images, and may be removed in a future release.-iCommand as the image entry point:
postCommit: command: ["/bin/bash", "-c", "bundle exec rake test --verbose"]In this form,
is the command to run, which overrides the image entry point in the exec form, as documented in the Dockerfile reference. This is needed if the image does not havecommand, or if you do not want to use a shell. In all other cases, using/bin/shmight be more convenient.scriptCommand with arguments:
postCommit: command: ["bundle", "exec", "rake", "test"] args: ["--verbose"]This form is equivalent to appending the arguments to
.command
Providing both
script
command
2.8.2.2. Using the CLI to set post commit build hooks Copia collegamentoCollegamento copiato negli appunti!
The
oc set build-hook
Procedure
To set a command as the post-commit build hook:
$ oc set build-hook bc/mybc \ --post-commit \ --command \ -- bundle exec rake test --verboseTo set a script as the post-commit build hook:
$ oc set build-hook bc/mybc --post-commit --script="bundle exec rake test --verbose"
2.9. Performing advanced builds Copia collegamentoCollegamento copiato negli appunti!
The following sections provide instructions for advanced build operations including setting build resources and maximum duration, assigning builds to nodes, chaining builds, build pruning, and build run policies.
2.9.1. Setting build resources Copia collegamentoCollegamento copiato negli appunti!
By default, builds are completed by pods using unbound resources, such as memory and CPU. These resources can be limited.
Procedure
You can limit resource use in two ways:
- Limit resource use by specifying resource limits in the default container limits of a project.
Limit resource use by specifying resource limits as part of the build configuration. ** In the following example, each of the
,resources, andcpuparameters are optional:memoryapiVersion: "v1" kind: "BuildConfig" metadata: name: "sample-build" spec: resources: limits: cpu: "100m"1 memory: "256Mi"2 However, if a quota has been defined for your project, one of the following two items is required:
A
section set with an explicitresources:requestsresources: requests:1 cpu: "100m" memory: "256Mi"- 1
- The
requestsobject contains the list of resources that correspond to the list of resources in the quota.
A limit range defined in your project, where the defaults from the
object apply to pods created during the build process.LimitRangeOtherwise, build pod creation will fail, citing a failure to satisfy quota.
2.9.2. Setting maximum duration Copia collegamentoCollegamento copiato negli appunti!
When defining a
BuildConfig
completionDeadlineSeconds
The maximum duration is counted from the time when a build pod gets scheduled in the system, and defines how long it can be active, including the time needed to pull the builder image. After reaching the specified timeout, the build is terminated by OpenShift Container Platform.
Procedure
To set maximum duration, specify
in yourcompletionDeadlineSeconds. The following example shows the part of aBuildConfigspecifyingBuildConfigfield for 30 minutes:completionDeadlineSecondsspec: completionDeadlineSeconds: 1800
This setting is not supported with the Pipeline Strategy option.
2.9.3. Assigning builds to specific nodes Copia collegamentoCollegamento copiato negli appunti!
Builds can be targeted to run on specific nodes by specifying labels in the
nodeSelector
nodeSelector
Node
The
nodeSelector
nodeSelector
nodeSelector:{}
If the specified
NodeSelector
Pending
Procedure
Assign builds to run on specific nodes by assigning labels in the
field of thenodeSelector, for example:BuildConfigapiVersion: "v1" kind: "BuildConfig" metadata: name: "sample-build" spec: nodeSelector:1 key1: value1 key2: value2- 1
- Builds associated with this build configuration will run only on nodes with the
key1=value2andkey2=value2labels.
2.9.4. Chained builds Copia collegamentoCollegamento copiato negli appunti!
For compiled languages such as Go, C, C++, and Java, including the dependencies necessary for compilation in the application image might increase the size of the image or introduce vulnerabilities that can be exploited.
To avoid these problems, two builds can be chained together. One build that produces the compiled artifact, and a second build that places that artifact in a separate image that runs the artifact.
In the following example, a source-to-image (S2I) build is combined with a docker build to compile an artifact that is then placed in a separate runtime image.
Although this example chains a S2I build and a docker build, the first build can use any strategy that produces an image containing the desired artifacts, and the second build can use any strategy that can consume input content from an image.
The first build takes the application source and produces an image containing a
WAR
artifact-image
assemble
/wildfly/standalone/deployments/ROOT.war
apiVersion: build.openshift.io/v1
kind: BuildConfig
metadata:
name: artifact-build
spec:
output:
to:
kind: ImageStreamTag
name: artifact-image:latest
source:
git:
uri: https://github.com/openshift/openshift-jee-sample.git
ref: "master"
strategy:
sourceStrategy:
from:
kind: ImageStreamTag
name: wildfly:10.1
namespace: openshift
The second build uses image source with a path to the WAR file inside the output image from the first build. An inline
dockerfile
WAR
apiVersion: build.openshift.io/v1
kind: BuildConfig
metadata:
name: image-build
spec:
output:
to:
kind: ImageStreamTag
name: image-build:latest
source:
dockerfile: |-
FROM jee-runtime:latest
COPY ROOT.war /deployments/ROOT.war
images:
- from:
kind: ImageStreamTag
name: artifact-image:latest
paths:
- sourcePath: /wildfly/standalone/deployments/ROOT.war
destinationDir: "."
strategy:
dockerStrategy:
from:
kind: ImageStreamTag
name: jee-runtime:latest
triggers:
- imageChange: {}
type: ImageChange
- 1
fromspecifies that the docker build should include the output of the image from theartifact-imageimage stream, which was the target of the previous build.- 2
pathsspecifies which paths from the target image to include in the current docker build.- 3
- The runtime image is used as the source image for the docker build.
The result of this setup is that the output image of the second build does not have to contain any of the build tools that are needed to create the
WAR
2.9.5. Pruning builds Copia collegamentoCollegamento copiato negli appunti!
By default, builds that have completed their lifecycle are persisted indefinitely. You can limit the number of previous builds that are retained.
Procedure
Limit the number of previous builds that are retained by supplying a positive integer value for
orsuccessfulBuildsHistoryLimitin yourfailedBuildsHistoryLimit, for example:BuildConfigapiVersion: "v1" kind: "BuildConfig" metadata: name: "sample-build" spec: successfulBuildsHistoryLimit: 21 failedBuildsHistoryLimit: 22 Trigger build pruning by one of the following actions:
- Updating a build configuration.
- Waiting for a build to complete its lifecycle.
Builds are sorted by their creation timestamp with the oldest builds being pruned first.
Administrators can manually prune builds using the 'oc adm' object pruning command.
2.9.6. Build run policy Copia collegamentoCollegamento copiato negli appunti!
The build run policy describes the order in which the builds created from the build configuration should run. This can be done by changing the value of the
runPolicy
spec
Build
It is also possible to change the
runPolicy
-
Changing to
ParallelorSerialand triggering a new build from this configuration causes the new build to wait until all parallel builds complete as the serial build can only run alone.SerialLatestOnly -
Changing to
Serialand triggering a new build causes cancellation of all existing builds in queue, except the currently running build and the most recently created build. The newest build runs next.SerialLatestOnly
2.10. Using Red Hat subscriptions in builds Copia collegamentoCollegamento copiato negli appunti!
Use the following sections to run entitled builds on OpenShift Container Platform.
2.10.1. Creating an image stream tag for the Red Hat Universal Base Image Copia collegamentoCollegamento copiato negli appunti!
To use Red Hat subscriptions within a build, you create an image stream tag to reference the Universal Base Image (UBI).
To make the UBI available in every project in the cluster, you add the image stream tag to the
openshift
The benefit of using image stream tags this way is that doing so grants access to the UBI based on the
registry.redhat.io
registry.redhat.io
Procedure
To create an
in theImageStreamTagnamespace, so it is available to developers in all projects, enter:openshift$ oc tag --source=docker registry.redhat.io/ubi8/ubi:latest ubi:latest -n openshiftTipYou can alternatively apply the following YAML to create an
in theImageStreamTagnamespace:openshiftapiVersion: image.openshift.io/v1 kind: ImageStream metadata: name: ubi namespace: openshift spec: tags: - from: kind: DockerImage name: registry.redhat.io/ubi8/ubi:latest name: latest referencePolicy: type: SourceTo create an
in a single project, enter:ImageStreamTag$ oc tag --source=docker registry.redhat.io/ubi8/ubi:latest ubi:latestTipYou can alternatively apply the following YAML to create an
in a single project:ImageStreamTagapiVersion: image.openshift.io/v1 kind: ImageStream metadata: name: ubi spec: tags: - from: kind: DockerImage name: registry.redhat.io/ubi8/ubi:latest name: latest referencePolicy: type: Source
2.10.2. Adding subscription entitlements as a build secret Copia collegamentoCollegamento copiato negli appunti!
Builds that use Red Hat subscriptions to install content must include the entitlement keys as a build secret.
Prerequisites
You must have access to Red Hat entitlements through your subscription. The entitlement secret is automatically created by the Insights Operator.
When you perform an Entitlement Build using Red Hat Enterprise Linux (RHEL) 7, you must have the following instructions in your Dockerfile before you run any
yum
RUN rm /etc/rhsm-host
Procedure
Add the etc-pki-entitlement secret as a build volume in the build configuration’s Docker strategy:
strategy: dockerStrategy: from: kind: ImageStreamTag name: ubi:latest volumes: - name: etc-pki-entitlement mounts: - destinationPath: /etc/pki/entitlement source: type: Secret secret: secretName: etc-pki-entitlement
2.10.3. Running builds with Subscription Manager Copia collegamentoCollegamento copiato negli appunti!
2.10.3.1. Docker builds using Subscription Manager Copia collegamentoCollegamento copiato negli appunti!
Docker strategy builds can use the Subscription Manager to install subscription content.
Prerequisites
The entitlement keys must be added as build strategy volumes.
Procedure
Use the following as an example Dockerfile to install content with the Subscription Manager:
FROM registry.redhat.io/ubi8/ubi:latest
RUN dnf search kernel-devel --showduplicates && \
dnf install -y kernel-devel
2.10.4. Running builds with Red Hat Satellite subscriptions Copia collegamentoCollegamento copiato negli appunti!
2.10.4.1. Adding Red Hat Satellite configurations to builds Copia collegamentoCollegamento copiato negli appunti!
Builds that use Red Hat Satellite to install content must provide appropriate configurations to obtain content from Satellite repositories.
Prerequisites
You must provide or create a
-compatible repository configuration file that downloads content from your Satellite instance.yumSample repository configuration
[test-<name>] name=test-<number> baseurl = https://satellite.../content/dist/rhel/server/7/7Server/x86_64/os enabled=1 gpgcheck=0 sslverify=0 sslclientkey = /etc/pki/entitlement/...-key.pem sslclientcert = /etc/pki/entitlement/....pem
Procedure
Create a
containing the Satellite repository configuration file:ConfigMap$ oc create configmap yum-repos-d --from-file /path/to/satellite.repoAdd the Satellite repository configuration and entitlement key as a build volumes:
strategy: dockerStrategy: from: kind: ImageStreamTag name: ubi:latest volumes: - name: yum-repos-d mounts: - destinationPath: /etc/yum.repos.d source: type: ConfigMap configMap: name: yum-repos-d - name: etc-pki-entitlement mounts: - destinationPath: /etc/pki/entitlement source: type: Secret secret: secretName: etc-pki-entitlement
2.10.4.2. Docker builds using Red Hat Satellite subscriptions Copia collegamentoCollegamento copiato negli appunti!
Docker strategy builds can use Red Hat Satellite repositories to install subscription content.
Prerequisites
- You have added the entitlement keys and Satellite repository configurations as build volumes.
Procedure
Use the following as an example Dockerfile to install content with Satellite:
FROM registry.redhat.io/ubi8/ubi:latest
RUN dnf search kernel-devel --showduplicates && \
dnf install -y kernel-devel
2.11. Securing builds by strategy Copia collegamentoCollegamento copiato negli appunti!
Builds in OpenShift Container Platform are run in privileged containers. Depending on the build strategy used, if you have privileges, you can run builds to escalate their permissions on the cluster and host nodes. And as a security measure, it limits who can run builds and the strategy that is used for those builds. Custom builds are inherently less safe than source builds, because they can execute any code within a privileged container, and are disabled by default. Grant docker build permissions with caution, because a vulnerability in the Dockerfile processing logic could result in a privileges being granted on the host node.
By default, all users that can create builds are granted permission to use the docker and Source-to-image (S2I) build strategies. Users with cluster administrator privileges can enable the custom build strategy, as referenced in the restricting build strategies to a user globally section.
You can control who can build and which build strategies they can use by using an authorization policy. Each build strategy has a corresponding build subresource. A user must have permission to create a build and permission to create on the build strategy subresource to create builds using that strategy. Default roles are provided that grant the create permission on the build strategy subresource.
| Strategy | Subresource | Role |
|---|---|---|
| Docker | builds/docker | system:build-strategy-docker |
| Source-to-Image | builds/source | system:build-strategy-source |
| Custom | builds/custom | system:build-strategy-custom |
| JenkinsPipeline | builds/jenkinspipeline | system:build-strategy-jenkinspipeline |
2.11.1. Disabling access to a build strategy globally Copia collegamentoCollegamento copiato negli appunti!
To prevent access to a particular build strategy globally, log in as a user with cluster administrator privileges, remove the corresponding role from the
system:authenticated
rbac.authorization.kubernetes.io/autoupdate: "false"
Procedure
Apply the
annotation:rbac.authorization.kubernetes.io/autoupdate$ oc edit clusterrolebinding system:build-strategy-docker-bindingExample output
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "false"1 creationTimestamp: 2018-08-10T01:24:14Z name: system:build-strategy-docker-binding resourceVersion: "225" selfLink: /apis/rbac.authorization.k8s.io/v1/clusterrolebindings/system%3Abuild-strategy-docker-binding uid: 17b1f3d4-9c3c-11e8-be62-0800277d20bf roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: system:build-strategy-docker subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:authenticated- 1
- Change the
rbac.authorization.kubernetes.io/autoupdateannotation’s value to"false".
Remove the role:
$ oc adm policy remove-cluster-role-from-group system:build-strategy-docker system:authenticatedEnsure the build strategy subresources are also removed from these roles:
$ oc edit clusterrole admin$ oc edit clusterrole editFor each role, specify the subresources that correspond to the resource of the strategy to disable.
Disable the docker Build Strategy for admin:
kind: ClusterRole metadata: name: admin ... - apiGroups: - "" - build.openshift.io resources: - buildconfigs - buildconfigs/webhooks - builds/custom1 - builds/source verbs: - create - delete - deletecollection - get - list - patch - update - watch ...- 1
- Add
builds/customandbuilds/sourceto disable docker builds globally for users with the admin role.
2.11.2. Restricting build strategies to users globally Copia collegamentoCollegamento copiato negli appunti!
You can allow a set of specific users to create builds with a particular strategy.
Prerequisites
- Disable global access to the build strategy.
Procedure
Assign the role that corresponds to the build strategy to a specific user. For example, to add the
cluster role to the usersystem:build-strategy-docker:devuser$ oc adm policy add-cluster-role-to-user system:build-strategy-docker devuserWarningGranting a user access at the cluster level to the
subresource means that the user can create builds with the docker strategy in any project in which they can create builds.builds/docker
2.11.3. Restricting build strategies to a user within a project Copia collegamentoCollegamento copiato negli appunti!
Similar to granting the build strategy role to a user globally, you can allow a set of specific users within a project to create builds with a particular strategy.
Prerequisites
- Disable global access to the build strategy.
Procedure
Assign the role that corresponds to the build strategy to a specific user within a project. For example, to add the
role within the projectsystem:build-strategy-dockerto the userdevproject:devuser$ oc adm policy add-role-to-user system:build-strategy-docker devuser -n devproject
2.12. Build configuration resources Copia collegamentoCollegamento copiato negli appunti!
Use the following procedure to configure build settings.
2.12.1. Build controller configuration parameters Copia collegamentoCollegamento copiato negli appunti!
The
build.config.openshift.io/cluster
| Parameter | Description |
|---|---|
|
| Holds cluster-wide information on how to handle builds. The canonical, and only valid name is
|
|
| Controls the default information for builds.
You can override values by setting the
Values that are not set here are inherited from DefaultProxy.
|
|
|
|
|
| Controls override settings for builds.
|
|
|
|
2.12.2. Configuring build settings Copia collegamentoCollegamento copiato negli appunti!
You can configure build settings by editing the
build.config.openshift.io/cluster
Procedure
Edit the
resource:build.config.openshift.io/cluster$ oc edit build.config.openshift.io/clusterThe following is an example
resource:build.config.openshift.io/clusterapiVersion: config.openshift.io/v1 kind: Build1 metadata: annotations: release.openshift.io/create-only: "true" creationTimestamp: "2019-05-17T13:44:26Z" generation: 2 name: cluster resourceVersion: "107233" selfLink: /apis/config.openshift.io/v1/builds/cluster uid: e2e9cc14-78a9-11e9-b92b-06d6c7da38dc spec: buildDefaults:2 defaultProxy:3 httpProxy: http://proxy.com httpsProxy: https://proxy.com noProxy: internal.com env:4 - name: envkey value: envvalue gitProxy:5 httpProxy: http://gitproxy.com httpsProxy: https://gitproxy.com noProxy: internalgit.com imageLabels:6 - name: labelkey value: labelvalue resources:7 limits: cpu: 100m memory: 50Mi requests: cpu: 10m memory: 10Mi buildOverrides:8 imageLabels:9 - name: labelkey value: labelvalue nodeSelector:10 selectorkey: selectorvalue tolerations:11 - effect: NoSchedule key: node-role.kubernetes.io/builds operator: Exists- 1
Build: Holds cluster-wide information on how to handle builds. The canonical, and only valid name iscluster.- 2
buildDefaults: Controls the default information for builds.- 3
defaultProxy: Contains the default proxy settings for all build operations, including image pull or push and source download.- 4
env: A set of default environment variables that are applied to the build if the specified variables do not exist on the build.- 5
gitProxy: Contains the proxy settings for Git operations only. If set, this overrides any Proxy settings for all Git commands, such asgit clone.- 6
imageLabels: A list of labels that are applied to the resulting image. You can override a default label by providing a label with the same name in theBuildConfig.- 7
resources: Defines resource requirements to execute the build.- 8
buildOverrides: Controls override settings for builds.- 9
imageLabels: A list of labels that are applied to the resulting image. If you provided a label in theBuildConfigwith the same name as one in this table, your label will be overwritten.- 10
nodeSelector: A selector which must be true for the build pod to fit on a node.- 11
tolerations: A list of tolerations that overrides any existing tolerations set on a build pod.
2.13. Troubleshooting builds Copia collegamentoCollegamento copiato negli appunti!
Use the following to troubleshoot build issues.
2.13.1. Resolving denial for access to resources Copia collegamentoCollegamento copiato negli appunti!
If your request for access to resources is denied:
- Issue
- A build fails with:
requested access to the resource is denied
- Resolution
- You have exceeded one of the image quotas set on your project. Check your current quota and verify the limits applied and storage in use:
$ oc describe quota
2.13.2. Service certificate generation failure Copia collegamentoCollegamento copiato negli appunti!
If your request for access to resources is denied:
- Issue
-
If a service certificate generation fails with (service’s
service.beta.openshift.io/serving-cert-generation-errorannotation contains):
Example output
secret/ssl-key references serviceUID 62ad25ca-d703-11e6-9d6f-0e9c0057b608, which does not match 77b6dd80-d716-11e6-9d6f-0e9c0057b60
- Resolution
-
The service that generated the certificate no longer exists, or has a different
serviceUID. You must force certificates regeneration by removing the old secret, and clearing the following annotations on the service:service.beta.openshift.io/serving-cert-generation-errorandservice.beta.openshift.io/serving-cert-generation-error-num:
$ oc delete secret <secret_name>
$ oc annotate service <service_name> service.beta.openshift.io/serving-cert-generation-error-
$ oc annotate service <service_name> service.beta.openshift.io/serving-cert-generation-error-num-
The command removing annotation has a
-
2.14. Setting up additional trusted certificate authorities for builds Copia collegamentoCollegamento copiato negli appunti!
Use the following sections to set up additional certificate authorities (CA) to be trusted by builds when pulling images from an image registry.
The procedure requires a cluster administrator to create a
ConfigMap
ConfigMap
-
The must be created in the
ConfigMapnamespace.openshift-config - is the key in the
domainandConfigMapis the PEM-encoded certificate.value-
Each CA must be associated with a domain. The domain format is .
hostname[..port]
-
Each CA must be associated with a domain. The domain format is
-
The name must be set in the
ConfigMapcluster scoped configuration resource’simage.config.openshift.io/clusterfield.spec.additionalTrustedCA
2.14.1. Adding certificate authorities to the cluster Copia collegamentoCollegamento copiato negli appunti!
You can add certificate authorities (CA) to the cluster for use when pushing and pulling images with the following procedure.
Prerequisites
-
You must have access to the public certificates of the registry, usually a file located in the
hostname/ca.crtdirectory./etc/docker/certs.d/
Procedure
Create a
in theConfigMapnamespace containing the trusted certificates for the registries that use self-signed certificates. For each CA file, ensure the key in theopenshift-configis the hostname of the registry in theConfigMapformat:hostname[..port]$ oc create configmap registry-cas -n openshift-config \ --from-file=myregistry.corp.com..5000=/etc/docker/certs.d/myregistry.corp.com:5000/ca.crt \ --from-file=otherregistry.com=/etc/docker/certs.d/otherregistry.com/ca.crtUpdate the cluster image configuration:
$ oc patch image.config.openshift.io/cluster --patch '{"spec":{"additionalTrustedCA":{"name":"registry-cas"}}}' --type=merge