TravisCI + CodeDeployでデプロイする

TravisCI + CodeDeployのフロー

【High Level】
– Merge Pull Request on master
– Travis Builds project automatically / run tests
– Travis uploads zipped project up to S3
– Travis then tells AWS Code Deploy to deploy to EC2 instance

【Index】
1. Pre-Setup
2. Policy For Server
3. Policy For Travis CI
4. Creating Travis User in IAM
5. Role for EC2 Instance
6. Role for Code Deploy Application
7. Create EC2 Instance
8. Create EC2 Tag
9. Create S3 Bucket
10. Setup Code Deploy
11. Project Setup
12. Setting Up Travis User Credentials on Travis
13. Code Deploy Agent Setup

### 1. IAMでEC2のPolicy作成
Policies -> Create Policy
Name: CodeDeployDemo-EC2-Permissions
Description: CodeDeployDemo-EC2-Permissions

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}

-> このポリシーによって、EC2がS3からデータを持ってこれる

### 2. IAMでTravisCI、CodeDeployの為のPolicy作成
1.TravisがS3にアップロード
Travis-Deploy-To-S3

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

2.CodeDeployがEC2にデプロイ
Travis-Code-Deploy-Policy
※AccIdHEREはAWSの数字のID
※NameOfTheCodeDeployApplicationNameHEREはCodeDeployのapplication name
※ServerRegionHEREはap-northeast-1

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "codedeploy:RegisterApplicationRevision",
                "codedeploy:GetApplicationRevision"
            ],
            "Resource": [
                "arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:application:NameOfTheCodeDeployApplicationNameHERE"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "codedeploy:CreateDeployment",
                "codedeploy:GetDeployment"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "codedeploy:GetDeploymentConfig"
            ],
            "Resource": [
                "arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.OneAtATime",
                "arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.HalfAtATime",
                "arn:aws:codedeploy:ServerRegionHERE:AccIdHERE:deploymentconfig:CodeDeployDefault.AllAtOnce"
            ]
        }
    ]
}

### 3. IAMでTravisユーザ作成
UserName: Travis
access type: Programmatic access
Set permissions: 上記で作成したTravis-Deploy-To-S3、Travis-Code-Deploy-Policy
->作成後、accesskey、secretkeyを保存

### 4. EC2のロール作成
Create role -> AWS service EC2
Permissions:CodeDeployDemo-EC2-Permissions
Role Name: CodeDeploy_EC2_DEPLOY_INSTANCE

### 5. CodeDeployアプリの為のロール作成
Create role -> CodeDeploy
Permissions: AWSCodeDeployRole
Role Name: CodeDeployServiceRole

### 6. EC2 launch
Amazon Linux 2 AMI (HVM), SSD Volume Type 64x t2.nano 8GiB GP2
Auto-assign Public IP: enable
IAM role: CodeDeploy_EC2_DEPLOY_INSTANCE
Tag: Name travisci

### 7. S3バケット作成
create bucket -> demo-travis-s3

### 8. CodeDeploy作成
Create application -> application nameはIAMのTravis-Code-Deploy-Policyで設定したname
platform: EC2/On-premises

Create Deployment Group -> Deployment Group Name : TravisCodeDeployDemoDeploymentGroup(何でもOK)
Envrionment Configuration -> Amazon EC2 -> 6で作成したtagを選択(Name travisci)
CodeDeployDefault.AllAtOnce

### 9. travis.yml

language: php
php:
  - 7.3

services:
  - mysql

before_script:
  - cp .env.travis .env
  - mysql -e 'create database test;'
  - composer self-update
  - composer install
  - chmod -R 777 storage

script: 
  - ./vendor/bin/phpunit

deploy:
  - provider: s3
    access_key_id: $AWS_ACCESS_KEY
    secret_access_key: $AWS_SECRET_KEY
    local_dir: dpl_cd_upload
    skip_cleanup: true
    on: &2
      repo: hoge/hogehoge
    bucket: demo-travis-s3
    region: ap-northeast-1
  - provider: codedeploy
    access_key_id: $AWS_ACCESS_KEY
    secret_access_key: $AWS_SECRET_KEY
    bucket: demo-travis-s3
    key: latest.zip
    bundle_type: zip
    application: travisci
    deployment_group: TravisCodeDeployDemoDeploymentGroup
    region: ap-northeast-1
    on: *2

script:
  - zip -r latest *
  - mkdir -p dpl_cd_upload
  - mv latest.zip dpl_cd_upload/latest.zip

### 10.Travis側でcrudentialの登録
Environment Variables
– AWS_ACCESS_KEY, AWS_SECRET_KEYを入力

### 11. EC2にCodeDeployインストール
$ sudo yum update
$ sudo yum install ruby
$ sudo yum install aws-cli
$ aws s3 cp s3://aws-codedeploy-ap-northeast-1/latest/install . –region ap-northeast-1
$ chmod +x ./install
$ sudo ./install auto
$ sudo service codedeploy-agent status
$ sudo yum info codedeploy-agent

### 12. appspec.yml

version: 0.0
os: linux
files:
  - source: ./
    destination: /home/test/travisci

### 13. git push & deploy
$ git push -u origin master

### 14. travisci
-> passed
-> Done. Your build exited with 0.

### 15. EC2で動作確認
$ cd /home/test/travisci
$ ls
README.md artisan composer.lock database phpunit.xml routes tests
app bootstrap composer.phar package-lock.json public server.php vendor
appspec.yml composer.json config package.json resources storage webpack.mix.js

– 所感
circleCIはデプロイのjob実装に一日かかりましたが、Travisは多少IAMの設定に時間がかかりましたが、デプロイは一発で上手くいきました。
Gitpullではなく、CodeDeployでデプロイできるので、AWSとはTravisの方が相性が良さそう。
ただ、unitテストはmasterへのpushではなく、ブランチのリポジトリへのpushのタイミングの方が良さそう。

TravisCIにDBのテストを追加する

.travis.yml

language: php
php:
  - 7.3

services:
  - mysql

before_script:
  - cp .env.travis .env
  - mysql -e 'create database test;'
  - composer self-update
  - composer install
  - chmod -R 777 storage

script: 
  - ./vendor/bin/phpunit

notifications:
  emails:
    - hoge@gmail.com

config.database.php

'testing' => [
            'driver' => 'mysql',
            'host' => env('DB_TEST_HOST', 'localhost'),
            'database' => env('DB_TEST_DATABASE', 'test'),
            'username' => env('DB_TEST_USERNAME', 'homestead'),
            'password' => env('DB_TEST_PASSWORD', 'secret'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
        ],

.env.travis

APP_ENV=testing
APP_KEY=base64:****

DB_CONNECTION=testing
DB_TEST_USERNAME=root
DB_TEST_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_DRIVER=sync

Laravel 7.x : Travis CIでUnitテストを実行する

Travis CI: Travis側(Ubuntu)でテストが行われる
Jenkins: テスト環境の構築が必要

### TravisCIの機能
– 自動でソースコードをcheckoutして、予め指定しておいたビルドやテスト処理を実行
– テスト結果をTravis CIのサイト上や各種API、メールで開発者に通知
– テストが問題なければ、予め指定しておいたホスティングサービスにデプロイする
– ビルドやテスト処理は「.travis.yml」に記述する

### 前準備(ローカル環境)
– Vagrant Amazon Linux 2
– Laravel 7.3.0, MySQL 8.0.18

### TravisCI側の操作
– Approve & Install Travis CI
— Only select repositories: publicを選択
— approve & install

### .travis.yml作成
– Laravelのルートディレクトリに.travis.ymlを作成

language: php
php:
  - 7.3

before_script:
  - composer self-update
  - composer install
  - chmod -R 777 storage
  - php artisan key:generate

script: 
  - ./vendor/bin/phpunit

notifications:
  emails:
    - hoge@gmail.com
1) Tests\Feature\ExampleTest::testBasicTest
RuntimeException: No application encryption key has been specified.

APP_KEYが必要のようなので、before_scriptでAPP_KEYを読み込むようにします。
.env.travis

APP_ENV=testing
APP_KEY=base64:*****
before_script:
  - cp .env.travis .env
  - composer self-update
  - composer install
  - chmod -R 777 storage

0.23s$ ./vendor/bin/phpunit
PHPUnit 8.5.2 by Sebastian Bergmann and contributors.
.. 2 / 2 (100%)
Time: 165 ms, Memory: 20.00 MB
OK (2 tests, 2 assertions)
The command “./vendor/bin/phpunit” exited with 0.

割とすぐ上手くいきました。仕組みとしては、CircleCIと似ていますが、Dockerじゃないとこが異なりますね。

.travis.yml2

language: ruby
rvm: 1.9.3

env:
  global:
    - RAILS_ENV=document
    - secure: "hogehoge"

branches:
  except: /^(feature|try).*$/

branches:
  only:
    - master
    - develop

before_install:
  - eval `ssh-agent -s`
  - chmod 600 ~/.ssh/config
  - openssl aes-256-cbc -K $encrypted_XXX_key -iv $encrypted_xxx_iv -in .travis/travis_key.enc -out travis_key -d
  - cp travis_key ~/.ssh/
  - chmod 600 ~/.ssh/travis_key
  - ssh-add ~/.ssh/travis_key

after_success: .travis/after_success.sh
after_failure: .travis/after_failure.sh 

なるほどー

.travis.yml

TravisCI flow
1. git clone the repository(where .travis.yml is located) from Github
the option –depth=50 is attached to git clone
2. Move to the cloned repository
3. Get committed code by git checkout
Environment variables written in .travis.yml apply here
4. If you use cache, get cache
5. Specify the version of Ruby to use
6. The one defined in before_install is executed
if you use a cache, it will be added here
7. The one defined in install is executed
8. The one defined in before_script is executed
9. What is defined in script is executed
If the exit code is 0 it is judged as success, otherwise it is judged as failure
10. The one defined in after_success or after_failure is executed.
11. The one defined in after_script is executed

ふむ、工程ごとに分かれたスクリプトを実行するのね。

Travis CI push to S3

Precondition
– an account of GitHub
– a repository in GitHub
– an account of Travis CI
– Travis CI CLI installed (gem install travis)
– AWS account
– making an access ID and Secret Key with updated authority of S3 with IAM
– hosting buckets of S3 as static site

Create IAM User

GitHub

As an access key and a secret key are to be replaced later, is it OK?

language: php
php:
- 5.5
script: echo "do nothing"
deploy:
  provider: s3
  access_key_id:
    secure: "accesskey id"
  secret_access_key:
    secure: "secret access key"
  bucket: travisci-s3
  region: ap-northeast-1
  endpoint: s3.amazonaws.com
  on:
    branch: master

TravisCI View config and Job log

View config – make it too simple

language: php
php:
- 5.5
script: phpunit test.php

Job log

Worker information

Cookbooks Version
7c2c6a6 https://github.com/travis-ci/travis-cookbooks/tree/7c2c6a6
git version
git version 2.15.1
bash version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
gcc version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
docker version
Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:38 2017
 OS/Arch:      linux/amd64
Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:20 2017
 OS/Arch:      linux/amd64
 Experimental: false
clang version
clang version 5.0.0 (tags/RELEASE_500/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/clang-5.0.0/bin
jq version
jq-1.5
bats version
Bats 0.4.0
shellcheck version
0.4.6
shfmt version
v2.0.0
ccache version
ccache version 3.1.9
Copyright (C) 2002-2007 Andrew Tridgell
Copyright (C) 2009-2011 Joel Rosdahl
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
cmake version
cmake version 3.9.2
CMake suite maintained and supported by Kitware (kitware.com/cmake).
heroku version
heroku-cli/6.14.39-addc925 (linux-x64) node-v9.2.0
imagemagick version
Version: ImageMagick 6.7.7-10 2017-07-31 Q16 http://www.imagemagick.org
md5deep version
4.2
mercurial version
Mercurial Distributed SCM (version 4.2.2)
(see https://mercurial-scm.org for more information)
Copyright (C) 2005-2017 Matt Mackall and others
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
mysql version
mysql  Ver 14.14 Distrib 5.6.33, for debian-linux-gnu (x86_64) using  EditLine wrapper
openssl version
OpenSSL 1.0.1f 6 Jan 2014
packer version
Packer v1.0.2
Your version of Packer is out of date! The latest version
is 1.1.2. You can update by downloading from www.packer.io
postgresql client version
psql (PostgreSQL) 9.6.6
ragel version
Ragel State Machine Compiler version 6.8 Feb 2013
Copyright (c) 2001-2009 by Adrian Thurston
subversion version
svn, version 1.8.8 (r1568071)
   compiled Aug 10 2017, 17:20:39 on x86_64-pc-linux-gnu
Copyright (C) 2013 The Apache Software Foundation.
This software consists of contributions made by many people;
see the NOTICE file for more information.
Subversion is open source software, see http://subversion.apache.org/
The following repository access (RA) modules are available:
* ra_svn : Module for accessing a repository using the svn network protocol.
  - with Cyrus SASL authentication
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme
* ra_serf : Module for accessing a repository via WebDAV protocol using serf.
  - using serf 1.3.3
  - handles 'http' scheme
  - handles 'https' scheme
sudo version
Sudo version 1.8.9p5
Configure options: --prefix=/usr -v --with-all-insults --with-pam --with-fqdn --with-logging=syslog --with-logfac=authpriv --with-env-editor --with-editor=/usr/bin/editor --with-timeout=15 --with-password-timeout=0 --with-passprompt=[sudo] password for %p:  --without-lecture --with-tty-tickets --disable-root-mailer --enable-admin-flag --with-sendmail=/usr/sbin/sendmail --with-timedir=/var/lib/sudo --mandir=/usr/share/man --libexecdir=/usr/lib/sudo --with-sssd --with-sssd-lib=/usr/lib/x86_64-linux-gnu --with-selinux
Sudoers policy plugin version 1.8.9p5
Sudoers file grammar version 43
Sudoers path: /etc/sudoers
Authentication methods: 'pam'
Syslog facility if syslog is being used for logging: authpriv
Syslog priority to use when user authenticates successfully: notice
Syslog priority to use when user authenticates unsuccessfully: alert
Send mail if the user is not in sudoers
Use a separate timestamp for each user/tty combo
Lecture user the first time they run sudo
Root may run sudo
Allow some information gathering to give useful error messages
Require fully-qualified hostnames in the sudoers file
Visudo will honor the EDITOR environment variable
Set the LOGNAME and USER environment variables
Length at which to wrap log file lines (0 for no wrap): 80
Authentication timestamp timeout: 15.0 minutes
Password prompt timeout: 0.0 minutes
Number of tries to enter a password: 3
Umask to use or 0777 to use user's: 022
Path to mail program: /usr/sbin/sendmail
Flags for mail program: -t
Address to send mail to: root
Subject line for mail messages: *** SECURITY information for %h ***
Incorrect password message: Sorry, try again.
Path to authentication timestamp dir: /var/lib/sudo
Default password prompt: [sudo] password for %p: 
Default user to run commands as: root
Value to override user's $PATH with: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
Path to the editor for use by visudo: /usr/bin/editor
When to require a password for 'list' pseudocommand: any
When to require a password for 'verify' pseudocommand: all
File descriptors >= 3 will be closed before executing a command
Environment variables to check for sanity:
	TZ
	TERM
	LINGUAS
	LC_*
	LANGUAGE
	LANG
	COLORTERM
Environment variables to remove:
	RUBYOPT
	RUBYLIB
	PYTHONUSERBASE
	PYTHONINSPECT
	PYTHONPATH
	PYTHONHOME
	TMPPREFIX
	ZDOTDIR
	READNULLCMD
	NULLCMD
	FPATH
	PERL5DB
	PERL5OPT
	PERL5LIB
	PERLLIB
	PERLIO_DEBUG 
	JAVA_TOOL_OPTIONS
	SHELLOPTS
	GLOBIGNORE
	PS4
	BASH_ENV
	ENV
	TERMCAP
	TERMPATH
	TERMINFO_DIRS
	TERMINFO
	_RLD*
	LD_*
	PATH_LOCALE
	NLSPATH
	HOSTALIASES
	RES_OPTIONS
	LOCALDOMAIN
	CDPATH
	IFS
Environment variables to preserve:
	JAVA_HOME
	TRAVIS
	CI
	DEBIAN_FRONTEND
	XAUTHORIZATION
	XAUTHORITY
	PS2
	PS1
	PATH
	LS_COLORS
	KRB5CCNAME
	HOSTNAME
	HOME
	DISPLAY
	COLORS
Locale to use while parsing sudoers: C
Directory in which to store input/output logs: /var/log/sudo-io
File in which to store the input/output log: %{seq}
Add an entry to the utmp/utmpx file when allocating a pty
PAM service name to use
PAM service name to use for login shells
Create a new PAM session for the command to run in
Maximum I/O log sequence number: 0
Local IP address and netmask pairs:
	10.240.0.28/255.255.255.255
	172.17.0.1/255.255.0.0
Sudoers I/O plugin version 1.8.9p5
gzip version
gzip 1.6
Copyright (C) 2007, 2010, 2011 Free Software Foundation, Inc.
Copyright (C) 1993 Jean-loup Gailly.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.
Written by Jean-loup Gailly.
zip version
Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license.
This is Zip 3.0 (July 5th 2008), by Info-ZIP.
Currently maintained by E. Gordon.  Please send bug reports to
the authors using the web page at www.info-zip.org; see README for details.
Latest sources and executables are at ftp://ftp.info-zip.org/pub/infozip,
as of above date; see http://www.info-zip.org/ for other sites.
Compiled with gcc 4.8.2 for Unix (Linux ELF) on Oct 21 2013.
Zip special compilation options:
	USE_EF_UT_TIME       (store Universal Time)
	BZIP2_SUPPORT        (bzip2 library version 1.0.6, 6-Sept-2010)
	    bzip2 code and library copyright (c) Julian R Seward
	    (See the bzip2 license for terms of use)
	SYMLINK_SUPPORT      (symbolic links supported)
	LARGE_FILE_SUPPORT   (can read and write large files on file system)
	ZIP64_SUPPORT        (use Zip64 to store large files in archives)
	UNICODE_SUPPORT      (store and read UTF-8 Unicode paths)
	STORE_UNIX_UIDs_GIDs (store UID/GID sizes/values using new extra field)
	UIDGID_NOT_16BIT     (old Unix 16-bit UID/GID extra field not used)
	[encryption, version 2.91 of 05 Jan 2007] (modified for Zip 3)
Encryption notice:
	The encryption code of this program is not copyrighted and is
	put in the public domain.  It was originally written in Europe
	and, to the best of our knowledge, can be freely distributed
	in both source and object forms from any country, including
	the USA under License Exception TSU of the U.S. Export
	Administration Regulations (section 740.13(e)) of 6 June 2002.
Zip environment options:
             ZIP:  [none]
          ZIPOPT:  [none]
vim version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Nov 24 2016 16:43:18)
Included patches: 1-52
Extra patches: 8.0.0056
Modified by pkg-vim-maintainers@lists.alioth.debian.org
Compiled by buildd@
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +syntax
+arabic          +file_in_path    +mouse_sgr       +tag_binary
+autocmd         +find_in_path    -mouse_sysmouse  +tag_old_static
-balloon_eval    +float           +mouse_urxvt     -tag_any_white
-browse          +folding         +mouse_xterm     -tcl
++builtin_terms  -footer          +multi_byte      +terminfo
+byte_offset     +fork()          +multi_lang      +termresponse
+cindent         +gettext         -mzscheme        +textobjects
-clientserver    -hangul_input    +netbeans_intg   +title
-clipboard       +iconv           +path_extra      -toolbar
+cmdline_compl   +insert_expand   -perl            +user_commands
+cmdline_hist    +jumplist        +persistent_undo +vertsplit
+cmdline_info    +keymap          +postscript      +virtualedit
+comments        +langmap         +printer         +visual
+conceal         +libcall         +profile         +visualextra
+cryptv          +linebreak       +python          +viminfo
+cscope          +lispindent      -python3         +vreplace
+cursorbind      +listcmds        +quickfix        +wildignore
+cursorshape     +localmap        +reltime         +wildmenu
+dialog_con      -lua             +rightleft       +windows
+diff            +menu            -ruby            +writebackup
+digraphs        +mksession       +scrollbind      -X11
-dnd             +modify_fname    +signs           -xfontset
-ebcdic          +mouse           +smartindent     -xim
+emacs_tags      -mouseshape      -sniff           -xsmp
+eval            +mouse_dec       +startuptime     -xterm_clipboard
+ex_extra        +mouse_gpm       +statusline      -xterm_save
+extra_search    -mouse_jsbterm   -sun_workshop    -xpm
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H     -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1      
Linking: gcc   -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,--as-needed -o vim        -lm -ltinfo -lnsl  -lselinux  -lacl -lattr -lgpm -ldl    -L/usr/lib/python2.7/config-x86_64-linux-gnu -lpython2.7 -lpthread -ldl -lutil -lm -Xlinker -export-dynamic -Wl,-O1 -Wl,-Bsymbolic-functions      
iptables version
iptables v1.4.21
curl version
curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3
wget version
GNU Wget 1.15 built on linux-gnu.
rsync version
rsync  version 3.1.0  protocol version 31
gimme version
v1.2.0
nvm version
0.33.6
perlbrew version
/home/travis/perl5/perlbrew/bin/perlbrew  - App::perlbrew/0.80
phpenv version
rbenv 1.1.1-25-g6aa70b6
rvm version
rvm 1.29.3 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [https://rvm.io]
default ruby version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
CouchDB version
couchdb 1.6.1
ElasticSearch version
5.5.0
Installed Firefox version
firefox 56.0.2
MongoDB version
MongoDB 3.4.10
PhantomJS version
2.1.1
Pre-installed PostgreSQL versions
9.2.24
9.3.20
9.4.15
9.5.10
9.6.6
RabbitMQ Version
3.6.14
Redis version
redis-server 4.0.6
riak version
2.2.3
Pre-installed Go versions
1.7.4
ant version
Apache Ant(TM) version 1.9.3 compiled on April 8 2014
mvn version
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/local/maven-3.5.2
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-98-generic", arch: "amd64", family: "unix"
gradle version
------------------------------------------------------------
Gradle 4.0.1
------------------------------------------------------------
Build time:   2017-07-07 14:02:41 UTC
Revision:     38e5dc0f772daecca1d2681885d3d85414eb6826
Groovy:       2.4.11
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_151 (Oracle Corporation 25.151-b12)
OS:           Linux 4.4.0-98-generic amd64
lein version
Leiningen 2.8.1 on Java 1.8.0_151 Java HotSpot(TM) 64-Bit Server VM
Pre-installed Node.js versions
v4.8.6
v6.12.0
v6.12.1
v8.9
v8.9.1
phpenv versions
  system
  5.6
* 5.6.32 (set by /home/travis/.phpenv/version)
  7.0
  7.0.25
  7.1
  7.1.11
  hhvm
  hhvm-stable
composer --version
Composer version 1.5.2 2017-09-11 16:59:25
Pre-installed Ruby versions
ruby-2.2.7
ruby-2.3.4
ruby-2.4.1
git.checkout
0.54s$ git clone --depth=50 --branch=master https://github.com/githubix/test.git githubix/test
Cloning into 'githubix/test'...
remote: Enumerating objects: 33, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (25/25), done.
remote: Total 36 (delta 2), reused 4 (delta 0), pack-reused 3
Unpacking objects: 100% (36/36), done.
$ cd githubix/test
$ git checkout -qf 7e08ab350f9bc489d90f6bfb08b4ad0a22ac5060
0.02s$ phpenv global 5.5 2>/dev/null
5.5 is not pre-installed; installing
Downloading archive: https://s3.amazonaws.com/travis-php-archives/binaries/ubuntu/14.04/x86_64/php-5.5.tar.bz2
19.87s$ curl -s -o archive.tar.bz2 $archive_url && tar xjf archive.tar.bz2 --directory /
0.01s0.02s$ phpenv global 5.5
You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug
1.22s$ composer self-update
You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug
Updating to version 1.8.0 (stable channel).
    Downloading: 100%
Use composer self-update --rollback to return to version 1.2.0
$ php --version
PHP 5.5.38 (cli) (built: Aug 16 2016 19:20:01) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
    with Xdebug v2.4.1, Copyright (c) 2002-2016, by Derick Rethans
$ composer --version
Composer version 1.8.0 2018-12-03 10:31:16
0.18s$ phpunit test.php
This is Travis ci first test2!Class 'test' could not be found in '/home/travis/build/githubix/test/test.php'.
The command "phpunit test.php" exited with 1.
Done. Your build exited with 1.

something wrong here, probably it cause by Travis.yml?

Jenkins vs TravisCI vs CircleCI

CI stands for Continuous Integration. In CI(Continuous Integration), developers frequently merge their code changes into the central repository and run automated builds and test each time.

I would like to compare popular CI tools.
– Jenkins
– TravisCI
– CircleCI

1. Jenkins
As a feature of Jenkins, it is highly scalable, it can do whatever you can customize, and build on on-premise.
Although it was a popular CI tool with abudant articles, since it is necessary to prepare a server for CI, maintenance and operation of that server becomes necessary.
– To incorporate it into the workflow including actual production, introduction needs to be done systematically.
– Failure to manage will take cost consuming.

2. TravisCI
Since it is cloud, there is no need to manage and operate the server.
Increased compatibility with Github
Abundant article
It is difficult to debug because SSH does not put it in a container
Since it is cloud, ip changes every time it builds

3. CircleCI
Since it is cloud, there is no need to manage and operate the server.
Support is strong
Abundant article
Since it is put in a container with ssh, it is easy to debug
You can start using it for free
Recently the version has gone up and it corresponds to docker and workflow
Because it is Cloud, every time it builds IP changes.

.travis.ymlの書き方

travis.ymlの公式です。必ず公式を見るようにします。
https://docs.travis-ci.com/user/customizing-the-build/

1. 言語を指定
phpを指定します。

language: php

2. 指定する言語のバージョン
5.6以上を指定します。

php:
  - 5.6
  - 7.0
  - 7.1
  - 7.2
  - 7.3
  - nightly

3. matrixで並列に回す

matrix:
  fast_finish: true
  allow_failures:
    - php: nightly

4. 実行するコードを書く

before_install:
  - travis_retry composer self-update

install:
  - travis_retry composer require --no-update satooshi/php-coveralls:^1.0
  - travis_retry composer install --no-interaction --prefer-source

before_script:
  - mkdir -p build/logs

script:
  - ./vendor/bin/parallel-lint src test
  - ./vendor/bin/phpunit --verbose --coverage-clover build/logs/clover.xml
  - ./vendor/bin/phpcs src --standard=psr2 -sp

after_success:
  - travis_retry php vendor/bin/coveralls

travis CIでvagrantからS3にデプロイ

まず、vagrantでrubyが入っているか確認します。
[vagrant@localhost deploy]$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

ruby 2.3.1ですね。travisをインストールします。
[vagrant@localhost deploy]$ gem install travis
Fetching: multipart-post-2.0.0.gem (100%)
Successfully installed multipart-post-2.0.0
Fetching: faraday-0.15.4.gem (100%)
Successfully installed faraday-0.15.4
Fetching: faraday_middleware-0.12.2.gem (100%)
Successfully installed faraday_middleware-0.12.2
Fetching: highline-1.7.10.gem (100%)
Successfully installed highline-1.7.10
Fetching: backports-3.11.4.gem (100%)
Successfully installed backports-3.11.4
Fetching: multi_json-1.13.1.gem (100%)
Successfully installed multi_json-1.13.1
Fetching: addressable-2.4.0.gem (100%)
Successfully installed addressable-2.4.0
Fetching: net-http-persistent-2.9.4.gem (100%)
Successfully installed net-http-persistent-2.9.4
Fetching: net-http-pipeline-1.0.1.gem (100%)
Successfully installed net-http-pipeline-1.0.1
Fetching: gh-0.15.1.gem (100%)
Successfully installed gh-0.15.1
Fetching: launchy-2.4.3.gem (100%)
Successfully installed launchy-2.4.3
Fetching: ethon-0.11.0.gem (100%)
Successfully installed ethon-0.11.0
Fetching: typhoeus-0.8.0.gem (100%)
Successfully installed typhoeus-0.8.0
Fetching: websocket-1.2.8.gem (100%)
Successfully installed websocket-1.2.8
Fetching: pusher-client-0.6.2.gem (100%)
Successfully installed pusher-client-0.6.2
Fetching: travis-1.8.9.gem (100%)
Successfully installed travis-1.8.9
invalid options: -SHN
(invalid options are ignored)
Parsing documentation for multipart-post-2.0.0
Installing ri documentation for multipart-post-2.0.0
Parsing documentation for faraday-0.15.4
Installing ri documentation for faraday-0.15.4
Parsing documentation for faraday_middleware-0.12.2
Installing ri documentation for faraday_middleware-0.12.2
Parsing documentation for highline-1.7.10
Installing ri documentation for highline-1.7.10
Parsing documentation for backports-3.11.4
Installing ri documentation for backports-3.11.4
Parsing documentation for multi_json-1.13.1
Installing ri documentation for multi_json-1.13.1
Parsing documentation for addressable-2.4.0
Installing ri documentation for addressable-2.4.0
Parsing documentation for net-http-persistent-2.9.4
Installing ri documentation for net-http-persistent-2.9.4
Parsing documentation for net-http-pipeline-1.0.1
Installing ri documentation for net-http-pipeline-1.0.1
Parsing documentation for gh-0.15.1
Installing ri documentation for gh-0.15.1
Parsing documentation for launchy-2.4.3
Installing ri documentation for launchy-2.4.3
Parsing documentation for ethon-0.11.0
Installing ri documentation for ethon-0.11.0
Parsing documentation for typhoeus-0.8.0
Installing ri documentation for typhoeus-0.8.0
Parsing documentation for websocket-1.2.8
Installing ri documentation for websocket-1.2.8
Parsing documentation for pusher-client-0.6.2
Installing ri documentation for pusher-client-0.6.2
Parsing documentation for travis-1.8.9
Installing ri documentation for travis-1.8.9
Done installing documentation for multipart-post, faraday, faraday_middleware, highline, backports, multi_json, addressable, net-http-persistent, net-http-pipeline, gh, launchy, ethon, typhoeus, websocket, pusher-client, travis after 18 seconds
16 gems installed

travis setupをする?
[vagrant@localhost deploy]$ travis setup s3
Shell completion not installed. Would you like to install it now? |y| y
Can’t figure out GitHub repo name. Ensure you’re in the repo directory, or specify the repo name via the -r option (e.g. travis -r /)

ん??
とりあえずtutorialを見てみよう。
https://docs.travis-ci.com/user/tutorial/

.travis.ymlをリポジトリに置くと書いてます。
>Add a .travis.yml file to your repository to tell Travis CI what to do. The following example specifies a Ruby project that should be built with Ruby 2.2 and the latest versions of JRuby.

deploy:
  provider: travis-s3
  access_key_id:
  secret_access_key:
    secure:
  endpoint:
  region: ap-northeast-1
  bucket: travisci-s3
  local-dir: /
  acl: public_read
  skip_cleanup: true
  on:
    repo: hpscript/travis-s3
  branches:
    only:
    - master

あれ、これ、githubにpushしたらaccess_keyとsecret_access_key漏れてしまうやんけ。
publicだと使えない??