Test Kitchen: введение и примеры

Автор: | 02/16/2016
 

Test Kitchentest_kitchen_ci – утилита, предназначенная для тестирования кода инфраструктуры.

С ее помощью можно проверить рецепты в разных изолированных окружениях. Например – узнать, будет ли работать рецепт на Ubuntu, CentOS и на разных провайдерах – AWS, Vagrant, Docker.

Test Kitchen обладает отличной документацией. Начинать стоит с официального HowTo, пример которого и приведен ниже с реальными примерами.

Загружаем кукбук из этого>>> поста:

$ git clone https://username@stash.domain.net/jboss6.git
$ cd jboss6/

(или любого другого, само собой).
Содержимое:

$ ls -l
total 40
-rw-r--r--  1 username  wheel    47 Jan 20 14:58 Berksfile
-rw-r--r--  1 username  wheel    54 Jan 20 14:58 README.md
drwxr-xr-x  4 username  wheel   136 Jan 20 14:58 attributes
-rw-r--r--  1 username  wheel  1029 Jan 20 14:58 chefignore
-rw-r--r--  1 username  wheel   226 Jan 20 14:58 clean
-rw-r--r--  1 username  wheel   296 Jan 20 14:58 metadata.rb
drwxr-xr-x  4 username  wheel   136 Jan 20 14:58 recipes
drwxr-xr-x  4 username  wheel   136 Jan 20 14:58 spec
drwxr-xr-x  3 username  wheel   102 Jan 20 14:58 templates
drwxr-xr-x  3 username  wheel   102 Jan 20 14:58 test

Создаем “кухню” – инициализируем текущий рецепт для работы с  Test Kitchen:

$ kitchen init --driver=kitchen-vagrant
      create  .kitchen.yml
    conflict  chefignore
Overwrite /private/tmp/test-kitchen-1/jboss6/chefignore? (enter "h" for help) [Ynaqdh] y
       force  chefignore
      append  .gitignore
      append  .gitignore
Fetching: kitchen-vagrant-0.19.0.gem (100%)
Successfully installed kitchen-vagrant-0.19.0
1 gem installed

Опцию --driver=kitchen-vagrant можно было не указывать, т.к. Test Kitchen по умолчанию будет использовать именно его.

Кроме того – был установлен пакет kitchen-vagrant, который является драйвером для работы Test Kitchen с Vagrant при создании новых боксов для тестирования рецептов.

Тут же создается файл .kitchen.yml – это и будет основной “рабочий” файл Test Kitchen:

$ cat .kitchen.yml
---
driver:
  name: vagrant

provisioner:
  name: chef_solo

platforms:
  - name: ubuntu-14.04
  - name: centos-7.1

suites:
  - name: default
    run_list:
      - recipe[jboss6::default]
    attributes:

Файл .kitchen.yml состоит из 4 основных секций:

  • driver – This is where we configure the behaviour of the Kitchen Driver – the component that is responsible for creating a machine that we’ll use to test our cookbook. Here we set up basics like credentials, ssh usernames, sudo requirements, etc. Each Driver is reponsible for requiring and using the configuration here. Under this section we have driver.name: This tells Test Kitchen that we want to use the kitchen-vagrant driver by default unless otherwise specified.
  • provisioner – This tells Test Kitchen how to run Chef, to apply the code in our cookbook to the machine under test. The default and simplest approach is to use chef-solo, but other options are available, and ultimately Test Kitchen doesn’t care how the infrastructure is built – it could theoretically be with Puppet, Ansible, or Perl for all it cares.
  • platforms – This is a list of operation systems on which we want to run our code. Note that the operating system’s version, architecture, cloud environment, etc. might be relevant to what Test Kitchen considers a Platform.
  • suites – This section defines what we want to test. It includes the Chef run-list and any node attribute setups that we want run on each Platform above. For example, we might want to test the MySQL client cookbook code seperately from the server cookbook code for maximum isolation.

Проверяем состояние:

$ kitchen list
Instance             Driver   Provisioner  Verifier  Transport  Last Action
default-ubuntu-1404  Vagrant  ChefSolo     Busser    Ssh        <Not Created>
default-centos-71    Vagrant  ChefSolo     Busser    Ssh        <Not Created>

Теперь – создаем инстанс, начнем с Ubuntu:

$ kitchen create default-ubuntu-1404
-----> Starting Kitchen (v1.4.2)
-----> Creating <default-ubuntu-1404>...
       Bringing machine 'default' up with 'virtualbox' provider...
       ==> default: Box 'opscode-ubuntu-14.04' could not be found. Attempting to find and install...
           default: Box Provider: virtualbox
...
       Vagrant instance <default-ubuntu-1404> created.
       Finished creating <default-ubuntu-1404> (5m29.17s).
-----> Kitchen is finished. (5m29.94s)
zlib(finalizer): the stream was freed prematurely.

Если проверить статус Vagrant – то можно увидеть запущенную машину:

$ vagrant global-status | grep default-ubuntu-1404
680f51b  default virtualbox running  /private/tmp/test-kitchen-1/jboss6/.kitchen/kitchen-vagrant/kitchen-jboss6-default-ubuntu-1404

Проверяем инстансы самого TK:

$ kitchen list
Instance             Driver   Provisioner  Verifier  Transport  Last Action
default-ubuntu-1404  Vagrant  ChefSolo     Busser    Ssh        Created
default-centos-71    Vagrant  ChefSolo     Busser    Ssh        <Not Created>

И запускаем тесты:

$ kitchen converge default-ubuntu-1404
-----> Starting Kitchen (v1.4.2)
-----> Converging <default-ubuntu-1404>...
...
-----> Installing Chef Omnibus (install only if missing)
...
       Chef Client finished, 28/44 resources updated in 05 minutes 34 seconds
       Finished converging <default-ubuntu-1404> (6m9.40s).
-----> Kitchen is finished. (6m10.24s)
zlib(finalizer): the stream was freed prematurely.

Проверяем состояние теперь:

$ kitchen list default-ubuntu-1404
Instance             Driver   Provisioner  Verifier  Transport  Last Action
default-ubuntu-1404  Vagrant  ChefSolo     Busser    Ssh        Converged

Обратите внимание на Action – Converged. Т.е. – машина и рецепты прошли тесты.

Можно повторить для CentOS:

$ kitchen create default-centos-71
$ kitchen converge default-centos-71

И вот тут – пример ошибки:

...
       Recipe: jboss6::default

           ================================================================================
           Error executing action `install` on resource 'apt_package[unzip]'
           ================================================================================

           Errno::ENOENT
           -------------
           No such file or directory - apt-cache

           Resource Declaration:
           ---------------------
           # In /tmp/kitchen/cookbooks/jboss6/recipes/default.rb

            15: apt_package 'unzip' do
            16:     action :install
            17: end
            18:

           Compiled Resource:
           ------------------
           # Declared in /tmp/kitchen/cookbooks/jboss6/recipes/default.rb:15:in `from_file'

           apt_package("unzip") do
             action [:install]
             retries 0
             retry_delay 2
             default_guard_interpreter :default
             package_name "unzip"
             declared_type :apt_package
             cookbook_name :jboss6
             recipe_name "default"
           end
 ----------------------
zlib(finalizer): the stream was freed prematurely.

Конечно – рецепт, написанный под Ubuntu с apt-get не сможет быть выполнен на CentOS – для этого его потребуется дополнить.

Ручная проверка

Подключаемся к интансу:

$ kitchen login default-ubuntu-1404
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.19.0-25-generic x86_64)

 * Documentation:  https://help.ubuntu.com/
Last login: Wed Jan 20 13:18:30 2016 from 10.0.2.2
vagrant@default-ubuntu-1404:~$

Проверяем:

$ which java
/usr/bin/java
$ netstat -anp | grep 8080
(No info could be read for "-p": geteuid()=900 but you should be root.)
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      -

Java установлена, JBoss запущен и работает.