Установка и использование Jenkins на Ubuntu 12.04

Jenkins – это открытый инструмент непрерывной интеграции. Запущенный в 2004 году, изначально он назывался Hudson, но в результате ссоры в 2011 проект разделился надвое и продолжил свое существование под новым названием, Jenkins. Данный инструмент может быть использован для разработки и развертывания программ и веб-сайтов с различными конечными точками, а также для проведения модульных и поведенческих тестов программного обеспечения. Это руководство продемонстрирует, как установить и настроить Jenkins, а также как создать свой первый проект. Кроме базовой настройки руководство охватывает планирование сборки и установку плагинов.

Требования

  • Предварительно настроенный VPS (войдите в систему как root);
  • Данное руководство было выполнено на Ubuntu 13.04 x64, но действительно для Ubuntu 12.04 и выше;
  • Предполагается, что ci.company.net указывает на бокс, в который будет установлен Jenkins.

Установка Jenkins

Прежде чем приступить к установке Jenkins, нужно добавить ключ и список исходных кодов. Итак, добавьте ключ:

wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | apt-key add -

А затем создайте список исходных кодов для Jenkins:

echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list

Теперь нужно просто обновить кэш apt, а затем перейти к установке Jenkins.

apt-get update

Обратите внимание: Jenkins имеет большой список зависимостей, установка которых может занять некоторое время.

apt-get install jenkins

Настройка Jenkins

Теперь Jenkins установлен и запущен, перейдите на ci.company.net:8080. Появится приветственная страница Jenkins.

На данный момент установка является небезопасной, любой желающий пользователь может свободно получить к ней доступ. Это нужно исправить. Перейдите к Manage Jenkins (в левом меню) и кликните Setup Security.

Затем включите безопасность, отметив галочкой соответственную строку.

Настройте использование пользовательской базы данных Jenkins и отключите возможность регистрироваться.

Перейдите к Matrix-based security. Убедитесь в том, что анонимные пользователи имеют только права на чтение (в столбце View).

В нижней части страницы нажмите кнопку save.

После загрузки страницы появится форма регистрации, ее нужно проигнорировать; снова перейдите к ci.company.net:8080.

Появится форма регистрации с заголовком Sign Up.

Зарегистрируйтесь как пользователь с именем hudson (или с любым другим именем на ваше усмотрение; имейте в виду, Jenkins предполагает использование нижнего регистра в именах пользователей), чтобы стать администратором этой установки Jenkins.

Создание нового проекта (Job)

Теперь, когда все установлено и запущено, можно приступить к созданию нового проекта (или job). Кликните по ссылке New Job.

Создайте проект (выберите free-style project) по имени uptime.

Нажмие Ok, перейдите на новую страницу, в выпадающем меню Add build step выберите Execute shell:

В поле Command введите uptime.

Нажмите кнопку save в конце страницы. На следующей странице нажмите кнопку Build Now.

Вскоре после этого появится история сборки (build history), ГД можно просмотреть процесс сборки.

Нажмите на синюю сферу для вывода на консоль.

Планирование проекта

Jenkins позволяет запускать проекты по требованию или в определенное время. Теперь пора настроить расписание сборки. Сначала нажмите на ссылку back to project, чтобы снова просмотреть проект.

Вернувшись к просмотру проекта, кликните кнопку Configure.

Она откроет страницу настройки. Теперь найдите раздел Build Triggers и выберите Build periodically.

Теперь это поле ввода принимает синтаксис crontab; следовательно, настройка @hourly будет запускать его каждый час, а * * * * *  будет запускать его каждую минуту. В данном руководстве будет использоваться настройка 0 */6 * * *, которая запускает проект каждые 6 часов. Когда проект будет сохранен, планировщик начнет работу в назначенное время.

С планировщиком Jenkins поставляются несколько дополнений. Чтобы получить о них больше информации, нажмите синюю кнопку с вопросительным знаком справа от поля ввода.

Установка плагинов

Jenkins имеет большое количество различных плагинов, начиная инструментами сборки и заканчивая FTP and SSH. В данном руководстве устанавливается плагин, который отслеживает дисковое пространство, используемое для сборки и проектов. Этот плагин поможет найти «пожирателей пространства». Для начала нужно открыть Manage Jenkins.

Найдите плагин Disk Usage Plugin и выберите его.

После этого нажмите кнопку Install without restart в конце страницы.

Подождите, пока плагин установится.

Это довольно простой плагин, не нуждающийся в конфигурации, но есть и такие плагины, (например, плагин SSH), которые требуют некоторой настройки перед началом работы.

Итоги

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

Tags: , , , ,

3 комментария

  • wasd says:

    ci.company.net:8080 не загрузился, зашел через localhost:8080.
    Спасибо за статью, только картинок не хватает

  • Денис says:

    Да, картинки точно не помешают.

  • Kuanysh says:

    Подскажите пожалуйста, хотел обновить плагин, но в итоге получил ошибку, что делать, как делать?:
    hudson.util.HudsonFailedToLoad: org.jvnet.hudson.reactor.ReactorException: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
    at hudson.WebAppMain$3.run(WebAppMain.java:237)
    Caused by: org.jvnet.hudson.reactor.ReactorException: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
    at org.jvnet.hudson.reactor.Reactor.execute(Reactor.java:269)
    at jenkins.InitReactorRunner.run(InitReactorRunner.java:44)
    at jenkins.model.Jenkins.executeReactor(Jenkins.java:924)
    at jenkins.model.Jenkins.(Jenkins.java:816)
    at hudson.model.Hudson.(Hudson.java:83)
    at hudson.model.Hudson.(Hudson.java:79)
    at hudson.WebAppMain$3.run(WebAppMain.java:225)
    Caused by: java.io.IOException: Unable to read /var/lib/jenkins/config.xml
    at hudson.XmlFile.unmarshal(XmlFile.java:165)
    at jenkins.model.Jenkins$17.run(Jenkins.java:2687)
    at org.jvnet.hudson.reactor.TaskGraphBuilder$TaskImpl.run(TaskGraphBuilder.java:169)
    at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:282)
    at jenkins.model.Jenkins$8.runTask(Jenkins.java:913)
    at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:210)
    at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:117)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: jenkins.util.xstream.CriticalXStreamException: only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86 : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    —- Debugging information —-
    message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    cause-exception : java.lang.IndexOutOfBoundsException
    cause-message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    class : hudson.security.ProjectMatrixAuthorizationStrategy
    required-type : hudson.security.ProjectMatrixAuthorizationStrategy
    converter-type : hudson.util.XStream2$AssociatedConverterImpl
    path : /hudson/authorizationStrategy
    line number : 8
    ——————————- : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86 : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    —- Debugging information —-
    message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    cause-exception : java.lang.IndexOutOfBoundsException
    cause-message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    class : hudson.security.ProjectMatrixAuthorizationStrategy
    required-type : hudson.security.ProjectMatrixAuthorizationStrategy
    converter-type : hudson.util.XStream2$AssociatedConverterImpl
    path : /hudson/authorizationStrategy
    line number : 8
    ——————————-
    message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86 : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    —- Debugging information —-
    message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    cause-exception : java.lang.IndexOutOfBoundsException
    cause-message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    class : hudson.security.ProjectMatrixAuthorizationStrategy
    required-type : hudson.security.ProjectMatrixAuthorizationStrategy
    converter-type : hudson.util.XStream2$AssociatedConverterImpl
    path : /hudson/authorizationStrategy
    line number : 8
    ——————————-
    cause-exception : com.thoughtworks.xstream.converters.ConversionException
    cause-message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86 : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    class : hudson.model.Hudson
    required-type : hudson.security.ProjectMatrixAuthorizationStrategy
    converter-type : hudson.util.RobustReflectionConverter
    path : /hudson/authorizationStrategy
    line number : 8
    version : not available
    ——————————-
    at hudson.util.RobustReflectionConverter.doUnmarshal(RobustReflectionConverter.java:315)
    at hudson.util.RobustReflectionConverter.unmarshal(RobustReflectionConverter.java:229)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1189)
    at hudson.util.XStream2.unmarshal(XStream2.java:113)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1173)
    at hudson.XmlFile.unmarshal(XmlFile.java:163)
    … 9 more
    Caused by: com.thoughtworks.xstream.converters.ConversionException: only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86 : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    —- Debugging information —-
    message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    cause-exception : java.lang.IndexOutOfBoundsException
    cause-message : only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    class : hudson.security.ProjectMatrixAuthorizationStrategy
    required-type : hudson.security.ProjectMatrixAuthorizationStrategy
    converter-type : hudson.util.XStream2$AssociatedConverterImpl
    path : /hudson/authorizationStrategy
    line number : 8
    ——————————-
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at hudson.util.RobustReflectionConverter.unmarshalField(RobustReflectionConverter.java:352)
    at hudson.util.RobustReflectionConverter.doUnmarshal(RobustReflectionConverter.java:290)
    … 20 more
    Caused by: java.lang.IndexOutOfBoundsException: only START_TAG can have attributes END_TAG seen …ategy class=”hudson.security.ProjectMatrixAuthorizationStrategy”/>… @8:86
    at org.xmlpull.mxp1.MXParser.getAttributeValue(MXParser.java:927)
    at com.thoughtworks.xstream.io.xml.XppReader.getAttribute(XppReader.java:139)
    at com.thoughtworks.xstream.io.ReaderWrapper.getAttribute(ReaderWrapper.java:52)
    at hudson.util.RobustReflectionConverter.instantiateNewInstance(RobustReflectionConverter.java:386)
    at hudson.util.RobustReflectionConverter.unmarshal(RobustReflectionConverter.java:228)
    at hudson.security.ProjectMatrixAuthorizationStrategy$ConverterImpl.unmarshal(ProjectMatrixAuthorizationStrategy.java:120)
    at hudson.util.XStream2$AssociatedConverterImpl.unmarshal(XStream2.java:362)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    … 24 more

Добавить комментарий