Опубликовать файл как артефакт jenkins

Обновлено: 06.07.2024

This plugin makes it possible to copy artifacts to remote locations.

History and Objectives

By default, Jenkins archives artifacts generated by the build. These artifacts are stored in the JENKINS_HOME directory with all other elements such as job configuration files.
There is no separation between infrastructure elements, project elements and outputs.
It is often considered to be a bad practice and it doesn't help to manage JENKINS_HOME directory from an administrator point of view (backup issues, etc).
And for now, we can't change the 'Archived artifacts' location.

ArtifactDeployer plugin enables you to archive build artifacts to any remote locations such as to a separate file server (outside of JENKINS_HOME directory).

There are many other Jenkins plugins close to ArtifactDeployer such as CopyArtifact plugin or CopyArchiver plugin for publishing artifacts from Jenkins resources (from the current workspace, from the old builds of the same job or other jobs, . ) to remote locations with the protocol file://
There are also others plugins for managing other protocols such as ftp://, ssh:///.

But none of these plugins provides a common way to manage the deployment.

ArtifactDeployer is a complete alternative to the built-in Jenkins feature "Archiving artefacts' and it is aimed at providing an uniform deployment mechanism.

  • Copies build artifacts from the workspace to a remote location shared on the build processor node
  • Provides links to archived artefacts from the job status page
  • Deletes on demand archived artifacts when the build is removed
  • Only file deployment is supported
  • For downloading deployed artifacts, remote location must be accessible from the Jenkins master
  • Jenkins process must have the right permissions to write in the specified location

* Fix SECURITY-294 - Rips out the ability to execute a Groovy script with this plugin

* Fix deployed item ID when there is multiple ArtifactDeployer step

* Fix JENKINS-24140 - ArtifactDeployer migration breaks lazy-load on Jenkins initialization

* Fix JENKINS-16130 - Provide folder links on build results page to condense long file paths
* Fix JENKINS-14681 - Constrain the list of artifacts deployed

* Fix typo in help file.

* Additional help text

* Fix JENKINS-18135 - Conditional Build Step plugin crashes when using Artifact Deployer plugin as build step

* Fix JENKINS-16031 - Lost deployed artifacts after restart

* Fix JENKINS-15709 - ArtifactDeployer does not appear in Flexible Publish

* Fix JENKINS-15354 - Add option to fail the build if specified "Files to deploy" do not exist

* Fix JENKINS-15059 - recursive deletion of deployment pathes not working correctly

* Fix JENKINS-15058 - Setting for GroovyScript is not permanent

* Fix JENKINS-14547 - Null pointer exception when using groovy script

* Fix JENKINS-14548 - help for groovy script usage is never displayed

* Fix JENKINS-13841 - "Base folder" for deploying the artifacty from source folder to remote directory

* Fix JENKINS-13937 - ArtifactDeployer 0.16 messes the filenames for Windows filesystems

* Fix NullPointerException on artifact deletion

* Fix JENKINS-12311 - Display the Deployed Artifacts in a tree structure similar to how they are displayed under the Build Artifacts section

* Fix JENKINS-11867 - Deployed files have a different time with original files.

* Fix JENKINS-12522 - Deploy artifacts for failed builds, too

* Fix JENKINS-11640 - Can't copy on remote windows slave

* Fix partially JENKINS-9996 - Have the possibility to change the user and group ACL's on artifacts (Conserve file permissions to copy).

* Fixed NullPointerException when the remote directory value is not set (for the ArtifactDeployer publisher and for the ArtifactDeployer builder).

* Make it compatible to LTS series (1.409.x)
* Complete fix JENKINS-10360 - Added support of Matrix project

* Fix partially JENKINS-10360 - Added support of Maven project

* Fix slave execution

* Fix bug on deletion
* The deployed artifacts in the Jenkins dashboard are now sorted.

* Fix a ClassCastException (for more than one entry) on save configuration

* Integrated a pull request - Fixed a NullPointerException

* Add 'deployment artifacts' as a a build step (builder item) in addition to publishers.
Use Case: In the same job as build steps: Build your artifacts, deploy them in remote locations (as servers) and launch the integration tests.

* Add a checkbox for deleting remote artifacts when the build is deleted.

* The plugins enables users to call a Groovy script when the builds are deleted (for manual and automatic deletion).

не мог бы кто-нибудь объяснить мне идею артефакты в процессе сборки?

у меня есть каталог рабочей области, где я проверяю код для компиляции и запуска моих сценариев ant и т. д. В конце концов, в моем случае, я получаю файл jar, который готов к установке. Это считается артефактом?

где я должен сказать моему скрипту сборки, чтобы поместить файл jar? В каталоге рабочей области? Мой файл jar получает уникальное имя файла в зависимости от таких переменных, как BUILD_ID и такой, как я могу сказать Дженкинсу, какой файл jar выбрать?

изменить: Хорошо, поэтому я попытался сделать что-то вроде этого:

enter image description here

путь еще не существует в моей рабочей области, потому что сценарий сборки должен его создать, и, конечно же, .jar и .properties файлов там нет, потому что они еще не были сгенерированы. Почему же тогда это дает мне ошибку? Кажется, я что-то упускаю.

кроме того, Дженкинс удаляет артефакты после каждой сборки (не архивированные артефакты, я знаю, что могу сказать, чтобы удалить их)? В противном случае он забьет жесткий диск довольно быстро.

ваше понимание верно, артефакт в смысле Дженкинса является результатом сборки-предполагаемого результата процесса сборки.

общее правило-результат построения в build , target или

артефакт может быть любым результатом процесса сборки. Важно то, что не имеет значения, на каком клиенте он был построен, он будет перенесен из рабочей области обратно на мастер (сервер) и сохранен там со ссылкой на сборку. Преимущество заключается в том, что это версионизировано таким образом, вам нужно только настроить резервное копирование на вашем Мастере и что все артефакты доступны через веб-интерфейс, даже если все клиенты сборки находятся в автономном режиме.

можно определить обычный выражение как имя артефакта. В моем случае я сжал все файлы, которые хотел сохранить в одном файле с постоянным именем во время сборки.

кроме того, Дженкинс удаляет артефакты после каждой сборки ? (не архивные артефакты, я знаю, что могу сказать, чтобы удалить их)

нет, Hudson / Jenkins сам по себе не очищает рабочую область после сборки. В процессе сборки могут быть действия, которые стирают, перезаписывают или перемещают артефакты сборки с того места, где вы их оставили. В конфигурации задания в расширенных параметрах проекта (которые должны быть развернуты) есть опция "очистить рабочую область перед сборка", которая уничтожит рабочую область в начале новой сборки.

в Jenkins 2.60.3 есть способ удалить артефакты сборки (а не архивированные артефакты), чтобы сэкономить место на жестком диске на машине сборки. В разделе "Общие" установите флажок "отбросить старые сборки" со стратегией "вращение журнала", а затем перейдите к ее расширенным параметрам. Появятся еще два варианта, связанные с сохранением артефактов сборки для задания на основе количества дней или сборок.

в настоящее время deploy master имеет" копировать артефакты из другого проекта "шаг сборки с использованием "последней успешной сборки".

build-master

Моя Цель

Я хочу изменить этот шаг с "последней успешной сборки" на "задано параметром сборки", чтобы я мог выбрать конкретную сборку при развертывании без изменения конфигурации deploy master работу каждый раз.

что я пробовал

во-первых, я изменил на "указанный параметром сборки".

build-specific

затем я поставил флажок рядом с "этот проект параметризован" и добавил строковый параметр для BUILD_SELECTOR .

parameter

затем Я выбрал build и введите input 47 который является номером сборки из build master работа.

кроме того, я попробовал вызов api

результат

оба раза это не удалось, со следующими выходными данными:

вопрос

Как правильно настроить это, чтобы я мог указать номер сборки (или какой-либо другой идентификатор) при развертывании?

обновление с помощью решения

мое решение спасибо Ответом джерольда было Добавление параметра "селектор сборки для копирования артефакта" и использование новой переменной среды для ссылки на мой строковый параметр, который я уже добавил.

enter image description here

в Jenkins есть только одно рабочее пространство для каждого проекта/задания. Каталоги сборок содержат только информацию о сборках и их результатах.

корневые каталоги обоих указаны в Управление ДженкинсНастройка Системы → дополнительно. .

развернуть артефакт из предыдущей сборки вы должны скопировать его в другое место в build master и получить доступ к нему там из deploy master позже.

обновление:

см. встроенную справку для построитьИмя Параметра:

параметр с таким именем должен быть добавлен в разделе Параметры построения. Существует специальный тип параметра для выбора селектора сборки.

использовать построить селектор для копирования артефакта вместо строка Параметр.

добавить следующее в нисходящий проект. "Построить селектор для копирования артефакта "вместо" строкового параметра"


копировать артефакты из другого проекта

enter image description here

enter image description here

вот и все. Нажмите "построить с параметрами" и передайте номер сборки

The following plugin provides functionality available through Pipeline-compatible steps. Read more about how to integrate steps into your Pipeline in the Steps section of the Pipeline Syntax page.

For a list of other such plugins, see the Pipeline Steps Reference page.

Jenkins Core

archiveArtifacts : Archive the artifacts

Archives the build artifacts (for example, distribution zip files or jar files) so that they can be downloaded later. Archived files will be accessible from the Jenkins webpage.
Normally, Jenkins keeps artifacts for a build as long as a build log itself is kept, but if you don't need old artifacts and would rather save disk space, you can do so. Note that the Maven job type automatically archives any produced Maven artifacts. Any artifacts configured here will be archived on top of that. Automatic artifact archiving can be disabled under the advanced Maven options. The Pipeline Snippet Generator generates this example when all arguments are set to true (some arguments by default are true): You can use wildcards like 'module/dist/**/*.zip'. See the includes attribute of Ant fileset for the exact format -- except that "," (comma) is the only supported separator. The base directory is the workspace. You can only archive files that are located in your workspace.

Here are some examples of usage for pipeline:

  • How to archive multiple artifacts from a specific folder:
  • How to archive multiple artifacts with different patterns:
  • How to archive multiple nested artifacts:
Normally, a build fails if archiving returns zero artifacts. This option allows the archiving process to return nothing without failing the build. Instead, the build will simply throw a warning.

Artifact archiver uses Ant org.apache.tools.ant.DirectoryScanner which by default is case sensitive. For instance, if the job produces *.hpi files, pattern "**/*.HPI" will fail to find them.

This option can be used to disable case sensitivity. When it's unchecked, pattern "**/*.HPI" will match any *.hpi files, or pattern "**/cAsEsEnSiTiVe.jar" will match a file called caseSensitive.jar.

  • Type: boolean
  • Type: boolean
Optionally specify the 'excludes' pattern, such as "foo/bar/**/*". Use "," to set a list of patterns. A file that matches this mask will not be archived even if it matches the mask specified in 'files to archive' section.
  • Type: String
  • Type: boolean
By disabling this option all symbolic links found in the workspace will be ignored.
  • Type: boolean
  • Type: boolean

fingerprint : Record fingerprints of files to track usage

To use this feature, all of the involved projects (not just the project in which a file is produced, but also the projects in which the file is used) need to use this and record fingerprints.

See this document for more details.

Can use wildcards like module/dist/**/*.zip (see the @includes of Ant fileset for the exact format). The base directory is the workspace.

Fingerprinter uses Ant org.apache.tools.ant.DirectoryScanner which by default is case sensitive. For instance, if the job produces *.hpi files, pattern "**/*.HPI" will fail to find them.

This option can be used to disable case sensitivity. When it's unchecked, pattern "**/*.HPI" will match any *.hpi files, or pattern "**/cAsEsEnSiTiVe.jar" will match a file called caseSensitive.jar.

  • Type: boolean
  • Type: boolean
Optionally specify the 'excludes' pattern, such as "foo/bar/**/*". Use "," to set a list of patterns. A file that matches this mask will not be fingerprinted even if it matches the mask specified in 'files to fingerprint' section.

Please submit your feedback about this page through this quick form.

Alternatively, if you don't wish to complete the quick form, you can simply indicate if you found this page helpful?

See existing feedback here.

The content driving this site is licensed under the Creative Commons Attribution-ShareAlike 4.0 license.

Читайте также: