yutokyokutyo / sample_app

Rails Tutorial 研修用
2 stars 0 forks source link

研修Gistまとめ【Ops研修】 #34

Closed yutokyokutyo closed 7 years ago

yutokyokutyo commented 9 years ago

Ops研修で書いてきたGistをこのissueにまとめます。

yutokyokutyo commented 9 years ago

Ops研修(10月30日)

オーバービュー

目標


serverspec:みじーさん

負荷がかかる場合はスケールアウトする リバースプロキシでサーバー管理(nginx)(appach) セッション(memcashed) アプリケーション・サーバー(rails ruby unicorn)

これらの繋がりはTCPIP,unixドメインソケット

マグリカ:社内プライベート上(vagrantとVMの合体) 世間的にはマグリカよりもvagrant&VMの流れになってきている

http://192.168.25.37/trac/share/wiki/Maglica/Usage

  • puppet,itamae

段階

  1. 環境構築まずは自分で。。
  2. 環境構築の自動化 puppet,itamae

備考

Chapter 1: VirtualBox の導入

installするときの便利君

Debian/Ubuntu には tasksel というツールがあり、システム環境に必要なソフトウェアをタスクと呼ばれる単位で管理することができます。

各種ソフトのインストール状況を把握でき、追加インストールも容易です。apt-get や aptitude を使ってパッケージを個別にインストールしていくことも可能ですが、tasksel を使えばより簡単にサーバ環境を構築することができます。

参考記事

http://osmania.blog.so-net.ne.jp/2011-06-08

  • sudo shutdown -r now :ubuntsの再起動

Chapter 2: Vagrant の導入

Vagrant の Box

プロバイダーとboxの違いがちょっとあやふや

yutokyokutyo commented 9 years ago

Ops研修(10月31日)

Chapter 2: Vagrant の導入

vagrantの日本語ドキュメント

http://lab.raqda.com/vagrant/getting-started/index.html

yutokyokutyo commented 9 years ago

Ops研修(11月4日)

Chapter 3: Ruby をインストールしよう

http://askubuntu.com/questions/384388/how-to-select-option-in-configuration-grub-pc-menu

  • GRUb-pc の設定をno choiceして進んだ!
  • 違うosを扱う場合はディレクトリを変えないと、vagrantfileが混在してしまうので注意

詰まった点1(gcc)前にrubyをインストールしたときにも同じ罠にハマった気がする

詰まった点2(openssl)

BUILD FAILED (CentOS Linux 7 using ruby-build 20140919-2-g04fe8ab)

Inspect or clean up the working tree at /tmp/ruby-build.20140923014200.3430
Results logged to /tmp/ruby-build.20140923014200.3430.log

Last 10 log lines:
                              rake 10.1.0
                              rdoc 4.1.0
                              test-unit 2.1.3.0
installing rdoc:              /home/vagrant/.rbenv/versions/2.1.3/share/ri/2.1.0/system
installing capi-docs:         /home/vagrant/.rbenv/versions/2.1.3/share/doc/ruby
The Ruby openssl extension was not compiled. Missing the OpenSSL lib?
Configure options used:
  --prefix=/home/vagrant/.rbenv/versions/2.1.3
  LDFLAGS=-L/home/vagrant/.rbenv/versions/2.1.3/lib 
  CPPFLAGS=-I/home/vagrant/.rbenv/versions/2.1.3/include

詰まった点3(sudo)

詰まった点(rehash)

yutokyokutyo commented 9 years ago

Ops研修(11月5日)

Chapter 3: Ruby をインストールしよう

descasion

ruby-buildの利点を考えよう(ruby-buildを使わないでビルドしてみる)

手作業ビルド
ソースをコンパイルする際に必要なパッケージをyumでインストールする。
yum -y install gcc zlib-devel openssl-devel sqlite sqlite-devel
cd /usr/local/src
wget ftp://ftp.ruby-lang.org/pub/ruby/ruby-2.1.4.tar.gz
tar zxvf ruby-2.1.4.tar.gz
cd ruby-2.1.4
./configure
make
make install
まずは、configureを実行し、Makefileを生成します。 

# ./configure 

このMakefileをもとにコンパイルという作業を実行する必要があります。 

コンパイルとは、ソースコードから実行可能ファイルを生成することであり、
makeコマンドを実行します。 

# make 

Makefileに基づいてコンパイルされ、実行ファイルが生成されます。
コンパイル後は、インストールを行い、実行ファイルやドキュメントを
適切なディレクトリに配置します。 

# make install 
これでインストールが完了!!

詰まった部分

https://gist.github.com/yutokyokutyo/e1c1cc575f6c369e2423

とってきたtar玉が本物なのかな?

公式ページに記載されている

最新の安定版: Ruby 2.1.4
md5: 89b2f4a197621346f6724a3c35535b19

を見ると、md5なるものが書かれている。

参考図書

yutokyokutyo commented 9 years ago

Ops研修(11月6日)

Chapter 4: Rails Tutotorial アプリを動かす

Railsを入れるというのは表現として間違っている! 確かにRailsを動かすプロセスの一つとしてrailsを入れる場面はあるが、端的にRailsをいれるというのは違うぽよ! たくさんの経験をしないと正確な言葉は使えないので、研修のゴールとして、正確な表現ができるようになるというのはあるよお

http://blog.sanpeity.com/2012/06/github-centos.html

詰まった部分1

git clone ができない

git clone git@github.com:yutokyokutyo/sample_app.git
Initialized empty Git repository in /home/vagrant/sample_ap

詰まった部分2

それでもgit clone できない!

https://gist.github.com/yutokyokutyo/23ed5662f7ba2a9550ee

  • 自宅でvagrantを立ち上げたときに、resolv.conf の中身(namesever)が自動で書き換わり、ネットに繋がっていなかったことが原因でしたぁ
  • 自宅の
$ cat /etc/resolv.conf
; generated by /sbin/dhclient-script
nameserver 192.168.0.1
nameserver 192.168.0.1

ネットが繋がっているかを確認するには、ping や ifconfigやresolv.confを見ると良い

vb.customize ["modifyvm", :id, "--natdnshostresolver1", "off"]

詰まった部分3

新たなエラーが・・。まだまだgit clone ができない!!!

$ git clone git@github.com:yutokyokutyo/sample_app.git
Initialized empty Git repository in /home/vagrant/sample_app/.git/
The authenticity of host 'github.com (192.30.252.131)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.252.131' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
$ ssh -T git@github.com
Permission denied (publickey).

どうやらssh-agentを起動させて秘密鍵の登録をしないといけないらしい。。

eval:evalは引数の変換を一度に行って実行を行う ssh-agent:認証エージェント

ssh-agent が起動すると、 UNIX ドメインソケット(UNIX でプロセス間通信に使われる、ファイルシステムベースの通信経路)を作成し、その名前を環境変数 "SSH_AUTH_SOCK" に設定します。そして、 ssh コマンドなどが起動したときは、このソケット経由で通信を行い、秘密鍵が必要な認証の処理を ssh-agent に代行させます。

  • ssh-agentを起動しておけば、転送機能で秘密鍵の代行を送ることができる便利君。いちいちパスワードをうたなくても良いし、秘密鍵をリモート上におかなくてもおk。
  • ssh-agentはシェルを終了させると自動的に終了する.
  • ssh-add で秘密鍵を登録することができる
  • opensshの機能なのかな?
  • ここでやっている秘密鍵と公開鍵のやりとりがテリーさんの座学で教えていただいた秘密鍵公開鍵の内容と咬み合わないので明日また考えてみる。。むづかしい。。
$ eval `ssh-agent`
Agent pid 18221
ssh-agent:

$ ssh-add ~/.ssh/centos6_rsa
Enter passphrase for /home/vagrant/.ssh/centos6_rsa:
Identity added: /home/vagrant/.ssh/centos6_rsa (/home/vagrant/.ssh/centos6_rsa)
$ ssh -T git@github.com
Warning: Permanently added the RSA host key for IP address '192.30.252.128' to the list of known hosts.
Hi yutokyokutyo! You've successfully authenticated, but GitHub does not provide shell access.

つながっている!!

$ git clone git@github.com:yutokyokutyo/sample_app.git
Initialized empty Git repository in /home/vagrant/sample_app/.git/
Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.
remote: Counting objects: 974, done.
remote: Compressing objects: 100% (377/377), done.
remote: Total 974 (delta 553), reused 970 (delta 550)
Receiving objects: 100% (974/974), 144.66 KiB, done.
Resolving deltas: 100% (553/553), done.

git clone 大成功!!(´∀`)

備考

yutokyokutyo commented 9 years ago

Ops研修(11月7日)

Chapter 4: Rails Tutotorial アプリを動かす

手順

  1. git clone してリポジトリのデータをクローンする
  2. Rails Tutorialに沿ってみる
  3. libyamlをいれる(rubyのインストールに必要なだけだったかも)

http://ghe.tokyo.pb/gist/yutokyokutyo/d0b4e2b67ca07de5df06

  1. rubygemsをダウンロードして解凍し、インストールする

vm上にダウンロードするにはどうすればいいのだろう。。 一旦macにダウンロードして、vagrantのsynced folders 機能を使ってホスト・ゲスト間を 同期させればいいかなと思ったが、同期の場合は自分のmacにもrubygemsのデータが入ってきてしまう気がする。それはまずいのでは。。

あえてやってみる?

いや、共有ディレクトリにいれてから、vm上でファイルをmvしてしまい、macのデータは消せば何も問題なくいけるのでは? だから、scpとかでファイルを持ってくるといいのかもしれないなあ。

$ gem install rails
ERROR:  While executing gem ... (URI::InvalidURIError)
    the scheme http does not accept registry part: host_name:port (or bad hostname?)

またもやhostname関係のエラー?? ううむむ。。

ボスケテしました

https://gist.github.com/yutokyokutyo/c8a21f10c091a2ace6a1

下の記事を参考にして、proxyの設定をbashprofileをいじったのが原因でした。

http://blog.sanpeity.com/2012/06/github-centos.html

github に HTTPS(SSL) で接続したいので、必要ならばプロキシ設定する。
# export https_proxy=http://host_name:port

↑これが原因!

本質的な原因がまだぼんやりとしか分かっていない。後でよく考えてみる。

  • 夕会でひろやんさんにお聞きして解決!
  • .bash_profileの内容のhost_name:portの部分は自分で指定しないといけない部分であったw
  • すなわちこの設定を書いたことで、ネットワーク上のサーバーにアクセスする際に、指定したproxyサーバーを経由してアクセスしようとするが、本来なら`198.168.hoge:8080'とか書いてあるものが文字列だったため、 なにこれええってなってしまった。
  • しかも、たちが悪いのはhttpsにのみproxyの設定をしたことだった。httpでのアクセスは直接意図したサーバーに通るのに、httpsの場合だけproxyを経由していたのであった。サーセン!
  • 何を書いているのかをきちんと把握してから使うこと
  • 自分が行なった手順は覚えておくこと
    1. bundle install して、必要なモノをどんどんいれていく
    2. bundle install がnokogiriがないとかで、中断されてしまったぽいので、gem install nokogiri!

https://gist.github.com/yutokyokutyo/c736a50bf6385002d323

  1. gem install nokogiriするにはまだまだ何か必要なようで。。。
  2. libxml2のパッケージが必要。 Rails Tutorialに書いてあった!

sudo apt-get install libxslt-dev libxml2-dev libsqlite3-dev # Linuxのみ

  • devファイルを入れてなかったのでこれらをymlでインストールする必要がありそう
    1. sudo yum -y install libxml2-devel
    2. sudo yum -y install libxslt-devel
    3. gem install nokogiri -- --use-system-libraries
    4. bundle install nokogiriがインストールされた!

https://gist.github.com/yutokyokutyo/c97a15143b8ef341ab92

  • Gemfileは開発時に参照されるファイル
  • Gemfile.lock:何がインストールされたか、どのような依存関係があったかが記述される。デプロイ時に参照されるファイル。
  • bundle install --without test development で要らないグループを削除できる
  • gitリポジトリからローカルにクローンを持ってきてbundle installするとpg無いよ!ってエラーが出てしまった。これはHerokuに動かす用にgemfileの:productionに加えているをインストールしようとするため。ローカルにPostgreSQLが入ってればそれで済む話だけど、入って無いので:productionのgemを除外してインストールする。
  • でも今はproduction環境を作っているから、データベースymlを書き換えないといけない?
  • Rail Tutorialだと、以下の様に設定していた
group :development do
  gem 'sqlite3', '1.3.8'
end

bundle や gem についてはまた来週! 今回の環境はproduction環境でmysqlを使うことにする! gem install やbundle install はどう違うのだろう?

メモ

備考

yutokyokutyo commented 9 years ago

Ops研修(11月10日)

Chapter 4: Rails Tutotorial アプリを動かす

手順

1. bundle install --without production

production環境に依存するpgを--withut productionで制限

https://gist.github.com/yutokyokutyo/30c963997523e6ff43fd

2. rails server を立ち上げようとしたところ、以下のエラーが。

Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.

Javazcriptを動かすためにもexecjsを入れろとのこと

3. gem install execjs
4. sudo yum install nodejs
5. gemfileに'libv8''execjs''therubyracer'を書いてbundle install しようとしたら、makeの段階で以下のエラーがでた

g++: コマンドが見つかりませんでした

  • g++:gccの別名。cコンパイラもc+コンパイラも両機能を持ち合わせている
  • なぜ以前インストールしたgccでは駄目なのだろう?
6. yum install gcc-c++
7. bundle install

とおった!!

8. rails s をしてみるがページが表示されない
config.vm.network :forwarded_port, guest: 3000, host: 3000
config.vm.network :private_network, ip: "192.168.hoge.hoge"

に書き換えて、reload。

9. rails sしても動かない!
10. ページが表示できたが、エラーがでてている!
11. rails s でsampleappが立ち上がったぞい!!!

mysqlとsqliteの違い、比較

メモ

ボスケテ

終業時刻間際になってしまったので、ここに書くことにしました

備考

yutokyokutyo commented 9 years ago

Ops研修(11月11日)

Chapter 4: Rails Tutotorial アプリを動かす

iptables

ファイアーウォールの機能

gccを以前入れたのになんでまた、gccg++をいれたのだろう

C言語をコンパイルする際のgccの利用方法を説明するが,C++の場合 にはgccというところをg++に変更すればほぼそのまま利用可能>

わお!c++にも対応させる必要があったからだった。 でもc++はどこのタイミングで使われるのだろう。。

$ gcc -v
Using built-in specs.
Target: x86_64-redhat-linux
コンフィグオプション: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
スレッドモデル: posix
gcc version 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)

enable-languageにc++は入ってわいるものの、インストール中だとgccではc++をコンパイルすることはできなかった。(これらはディストリビューションやOSによるので、一概にはいえない)今回の場合だと、gccコマンドを叩いてコンパイルするとgccだけでいけたかもしれぬ!

ちなみにmacの場合のgcc -vは、

% gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.3.0
Thread model: posix

appleが気をきかせてgcc -vコマンドでコンパイラを表示してくれるが、Apple LLVMと書かれている!そうこれはGCCではないのだ!注意!!

XSLT

Nokogiri

rubygems

今回はいちいちrubygemsをダウンロードしてVM上にファイル一式をもってきてsetup.rbをしたが、yum install rubygems でインストールできるんかい!!

ボスケテ

execjsは場面に応じて適宜ランタイムエンジンを切り替えてくれる君だと思っているのですが、therubyracernode.jsをどのように振り分けているのかが分かりません。どんなときにtherubyracerを使い、どんなときにnode.jsを使うのでしょう?

解決した!

https://gist.github.com/yutokyokutyo/b36771bf867e201975ef

  • therubyracerは速さでは圧倒的に一番だが、その分メモリをくう。
  • その理由によりHerokuではtherubyracerは非推奨
  • 割りとtherbyracerでトラブルは起きているっぽい
  • 同じv8エンジンをつかっているし、node.jsは安定感ありそう
  • ライブラリやgem、メソッド、関数が何をしているのかが分からなかったらソースコードを一旦読んでみると良い!その習慣づけを積んでいくと良い気がする
  • 何かを選択、採用する場合には以下の面で考えると良い。
  1. 長くメンテナンスされ続けている 2. 他にはない圧倒的なメリットが何かある 3. みんなが広く使うのに面倒さが少ない
    • 印象としては、node.jsは1と3のバランスが強く、rubyracerは2のバランスが強いといった感じ

Chapter 5: Serverspec の導入

下のSurverspecのスライドを読みました

http://www.slideshare.net/mizzy/serverspec-hbstudy45

試しに勢い余って gem install serverspec rake してしまいましたが、勝手にやってしまってよかったのかどうか。。

$ gem install serverspec rake
Fetching: net-ssh-2.9.1.gem (100%)
Successfully installed net-ssh-2.9.1
Fetching: net-scp-1.2.1.gem (100%)
Successfully installed net-scp-1.2.1
Fetching: specinfra-2.4.2.gem (100%)
Successfully installed specinfra-2.4.2
Fetching: rspec-support-3.1.2.gem (100%)
Successfully installed rspec-support-3.1.2
Fetching: rspec-expectations-3.1.2.gem (100%)
Successfully installed rspec-expectations-3.1.2
Fetching: rspec-core-3.1.7.gem (100%)
Successfully installed rspec-core-3.1.7
Fetching: rspec-its-1.1.0.gem (100%)
Successfully installed rspec-its-1.1.0
Fetching: rspec-mocks-3.1.3.gem (100%)
Successfully installed rspec-mocks-3.1.3
Fetching: rspec-3.1.0.gem (100%)
Successfully installed rspec-3.1.0
Fetching: serverspec-2.3.1.gem (100%)
Successfully installed serverspec-2.3.1
Parsing documentation for net-ssh-2.9.1
Installing ri documentation for net-ssh-2.9.1
Parsing documentation for net-scp-1.2.1
Installing ri documentation for net-scp-1.2.1
Parsing documentation for specinfra-2.4.2
Installing ri documentation for specinfra-2.4.2
Parsing documentation for rspec-support-3.1.2
Installing ri documentation for rspec-support-3.1.2
Parsing documentation for rspec-expectations-3.1.2
Installing ri documentation for rspec-expectations-3.1.2
Parsing documentation for rspec-core-3.1.7
Installing ri documentation for rspec-core-3.1.7
Parsing documentation for rspec-its-1.1.0
Installing ri documentation for rspec-its-1.1.0
Parsing documentation for rspec-mocks-3.1.3
Installing ri documentation for rspec-mocks-3.1.3
Parsing documentation for rspec-3.1.0
Installing ri documentation for rspec-3.1.0
Parsing documentation for serverspec-2.3.1
Installing ri documentation for serverspec-2.3.1
Done installing documentation for net-ssh, net-scp, specinfra, rspec-support, rspec-expectations, rspec-core, rspec-its, rspec-mocks, rspec, serverspec after 9 seconds
Successfully installed rake-10.3.2
Parsing documentation for rake-10.3.2
Installing ri documentation for rake-10.3.2
Done installing documentation for rake after 1 seconds
11 gems installed

備考

http://blog.inouetakuya.info/entry/20111006/1317900802

yutokyokutyo commented 9 years ago

Ops研修(11月12日)

Chapter 4: Rails Tutotorial アプリを動かす

rubygemsをmacにダウンロードして解凍して、解凍したファイル郡をVM上にもってきて、setup.rbをしたけどもこれはyum install rubygemsで良かったのかな?

  • 良くない!
  • yum install はシステムライブラリをインストールするときのコマンド
  • yumでインストールした場合、/usr/bin/の中に置かれる。これはosやディストリビューションに依存した古いバージョンになっている
  • 一方、rubygemsはrbenvで管理しているもの(`~/.rbenv/version/の下に書かれているバージョンの中のものしか管理しない)で、gemをいれるのであればrbenvとの依存関係をつくらなければいけない。
  • 最終的にrubygemsはもう入っていたので、入れなくても良かったのであった。
  • $ sudo yum install rubygemsの結果では、rubyのバージョンが1.8.7のようになっていて古かった。

rails server だけではダメな理由

  • weblicのプロセス数を調べてみよう!
  • weblic::Railsがデフォルトで用意しているHTTPサーバーを仲介してくれる君(WebLogicサーバー)
  • ps aux | grep weblic してもなにも出てこない
  • psコマンドの見方
  • ppis::呼び出された親のプロセスid
  • rsa:プロセスの実メモリサイズ
  • TTY:端末の種類と端末番号を表示
  • START:プロセスの開始時刻
  • ps aux:
  • a:端末に紐づけたプロセスをすべて表示する
  • u:CPU使用率、メモリ使用率、開始時間などの詳細情報を表示する
  • x:端末に紐づかないプロセスもすべて表示!

vagrant 4171 0.0 7.2 286932 73464 pts/0 Sl+ 15:36 0:03 /home/vagrant/.rbenv/versions/2.1.4/bin/ruby bin/rails s

インストールする際にgemとbundleをどのように使い分けるのだろう?

  • 基本的なインストールの手順としては、rubyをインストールして、,bundlerをgemでインストールする。その後はbundleでインストールすること
  • gemでインストールしてしまうと、後々何をいれたのかが分からなくなってしまうのでGemfieで管理するべき。(共同で作業する際にも何をいれたのかどうかを共有できなくなってしまう)

Chapter 5: Serverspec の導入

続く

備考

yutokyokutyo commented 9 years ago

Ops研修(11月13日)

Chapter 5: Serverspec の導入

1. 先日、gem install でserverspecを導入したので,initしてみる

https://gist.github.com/yutokyokutyo/f402de8fb90f28e58afe

  • 途中でssh接続なのか、localなのかを選択する場面があったが、今回はもうssh接続してVm上にいるので、localを選択
  • serverspec-initで作られたファイルを見る
  • Rakefile
  • spec/defalt/sample_spec.rb
  • spec/spec_helper.rb
  • bundle install --path vnderでvender以下に置いてしまった
  • 本来ならvender/bundle以下に行くべきだった

bundle exec rake spec をするとサーキュラーエラーが生じる

rake aborted!
Circular dependency detected: TOP => spec => spec:all => spec:default => spec:all
Tasks: TOP => spec => spec:all => spec:default
(See full trace by running task with --trace)

複数のVMを使うには

config.vm.define :好きな名前 do |c|
    c.vm.box      = ""
    c.vm.box_url  = ""
    c.vm.hostname = ""
    define_virtualbox c
    c.vm.provision :shell do |shell|
      shell.path = "vagrant/build-proftpd.sh"
    end
  end

2. 第3章4章でインストールをしたものをピックアプしてテストを書いてみる

人によってはrubyがインストールされていることを確かめるために以下の手順で確かめていた!

1. /usr/local/rbenv/bin/rbenv に rbenv がインストールされていること
2. /etc/profile.d/rbenv.sh が正しく作成されていること
3. rbenv のプラグインとして ruby-build がインストールされていること
4. 目的のバージョンの Ruby が正しくインストールされていること
5. Ruby 2.1.2 が global として設定されていること

これぐらい確認しないとダメかな。。判断が難しい。

備考

yutokyokutyo commented 9 years ago

Ops研修(11月14日)

Chapter 5: Serverspec の導入

rbnevはどのファイルをみればよいのかが分からない

# rbenvがあるかどうか
 describe file('~/.rbenv/bin/rbenv') do
   it { should be_file }
 end
# rbenvがあるかどうか
describe file('/home/vagrant/.rbenv/libexec/rbenv') do
  it { should be_file }
end

bundleでインストールしたものに関してはGemfileの中にコンテキストが含まれているかどうかをみれば良いのでは?

と思い、

describe file('Gemfile') do
  it { should contain('sqlite3').from(/^group :development do/).to(/^end/) }
end

のようにテストをしてみるが、以下のエラーが出る

4) File "Gemfile" should contain "sqlite3"
     On host `default'
     Failure/Error: it { should contain('sqlite3').from(/^group :development do/).to(/^end/) }
       expected File "Gemfile" to contain "sqlite3"
       sudo -p 'Password: ' /bin/sh -c sed\ -n\ /\\\^group\\\ :development\\\ do/,/\\\^end/p\ Gemfile\ \|\ sed\ -n\ 1,/\\\^end/p\ \|\ grep\ -qs\ --\ sqlite3\ -\ \|\|\ sed\ -n\ /\\\^group\\\ :development\\\ do/,/\\\^end/p\ Gemfile\ \|\ sed\ -n\ 1,/\\\^end/p\ \|\ grep\ -qFs\ --\ sqlite3\ -
% bundle exec rake -vT                      (git)-[master]
rake spec:default  # Run serverspec tests to default

むうう。hostnameがデフォルトだよ? なぜかsudo -p が必要だよ?と言われている。。なんだろう。。

sudo -p

-p (prompt) オプションが指定されると、デフォルトのパスワードプロンプトを上書きして、カスタム化したものを使うことが可能になる。プロンプトに %u エスケープがある場合、 %u はユーザのログイン名に置き換えられる。同様に、%h はローカルホスト名に置き換えられる。

  • sudo -p bundle exec rake spec をしてテストをしてみたら、それ以降テストが全て赤くなってしまった。。

> ひろやんさんのスーパーデバッグ術により解決!!

Virtualboxでは複数のVMを管理している。そこで、VagrantでVMを管理する際に、メタファイルが用意されている。(メタファイルの中にUUIDと呼ばれる一意のIDが割り振られている)そのUUIDをVagrantとVirtualboxとを紐づけることにより、整合性を担保している。

そこで今回の地雷ポイントはVagrantのhostnameをいじったり、他にもガチャガチャと不必要な操作をしてしまったことにより、,UUIDの紐付けが正しく行なわれずに整合性がとれなくなってしまった。

Failure/Error: it { should contain('sqlite3').from(/^group :development do/).to(/^end/) }
       expected File "Gemfile" to contain "sqlite3"
       sudo -p 'Password: ' 

の部分は、sshでmacからVM上にid:vagrantでログインして中で実際に行なわれいる操作だったのでした。

gemがインストールされたかどうかのテストをGemfileに書かれていることで確かめているが、,nokogiriはgem install ででインストールしてしまったため、確かめられない。。..bundler以外はgem install するべきものではないので、Gemfileにいれなおしてもう一度bundle install することにしました。

nohup

現在のspecファイル

https://gist.github.com/yutokyokutyo/257187a7f06027fc76d0

ボスケテ

備考

yutokyokutyo commented 9 years ago

Ops研修(11月19日)

Chapter 5: Serverspec の導入

ruby-buildのディレクトリの場所を間違えていた

# rubybuildがあることを確かめる
describe file('/home/vagrant/.rbenv/plugins/ruby-build') do
  it { should be_directory }
end

rubygemsをテストする

# rubygemsがあることを確かめる
describe file('/home/vagrant/.rbenv/versions/*.*.*/lib/ruby/gems') do
  it { should be_directory }
end

ポートテスト

# ポートは3000番で動く!
describe port(3000) do
  it { should be_listening }
end

-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPTA

-p :プロトコルタイプ -j(jump):条件に合ったときのアクションを指定する -m:パケットの状態を条件として指定

iptablesのリソースタイプがあったので活用してみたところ、エラーが。。

describe iptables do
  it { should have_rule('-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT') }
end
$ sudo iptables --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
start : iptablesを起動します。
stop : iptablesを停止します。
restart : iptablesを再起動します。
status : iptablesの状態を表示します。
save : iptablesの設定を保存します
$ sudo /etc/init.d/iptables start
iptables: ファイアウォールルールを適用中:                  [  OK  ]

Rails serverの起動テストが書けない!

# Railsサーバーが起動していることを確かめる(nohup)
describe service('WEBrick::HTTPServer') do
  it { should be_enabled }
  it { should be_running }
end

serverspec上で正規表現は使えないのかな?

iptablesは起動設定をしなくてもよいのかな?

$ chkconfig --list iptables
iptables        0:off   1:off   2:on    3:on    4:on    5:on    6:off

下のリンクに一覧が載っていた

http://kajuhome.com/service_list.shtml

  • railsはサービスには入らないのかな?

iptablesの設定が上手くいっていないので明日再チャレンジ!

リョーマ氏との共有で得たこと

備考

yutokyokutyo commented 9 years ago

Ops研修(11月20日)

Chapter 5: Serverspec の導入

昨日リョーマ氏と共有して足りていなかった部分のテストを追加する

rbenv vesionコマンドでカレントディレクトリで有効な Ruby バージョンが表示されるるので、このテストもした方が強くなりそう

# Rubyがsampleappでどのバージョンで動いているのか(上とどっちの方が良いのかな)
describe command('rbenv version /home/vagrant/sample_app') do
  its(:stdout) { should match /2.1.4/ }
end

一旦テストが全て通るようになったので、まだ怪しい部分もありますが shell provision を書いてみる。足りない部分があったらserverspecのテストに戻ってリファクタリングをしていく方針で進めて行く

Chapter 6: shell provisioner の導入

【詰まった】新たにVMを作成することができない

ボスケテして解決

明日はシェルスクリプトを書くぞ!

備考

$ rbenv exec gem which bundler
/home/vagrant/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/bundler-1.7.4/lib/bundler.rb
yutokyokutyo commented 9 years ago

Ops研修(11月21日)

Chapter 5: Serverspec の導入

今日追加した処理をserverspecのテストの方にも反映させなくてはいけない

Chapter 6: shell provisioner の導入

【詰まった!】 ディレクトリがもうあるよ案件

default: fatal: destination path '/root/.rbenv' already exists and is not an empty directory.

昨日リョーマ氏に共有してもらった部分のエラーがでてきた。 前回 git clone したときにディレクトリを作成し、また vagrant provision で同じ処理(git clone)しようとしたときに、ディレクトリが重複してしまったのであった。 if文を使ってこの処理をさせないようにしなくてはならない。

CHK_DIR=/root/.rbenv

if [ -d ${CHK_DIR} ] ; then
        echo "${CHK_DIR}  is already exist..."
        # exit 1;
goto exist1
else
git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
fi
exist1:

【詰まった!】 実行ユーザーを変えなくてはいけない案件

% vagrant ssh                                                                                                                                                                                 (git)-[master]
Last login: Fri Nov 21 17:14:10 2014 from 10.0.2.2
mkdir: ディレクトリ `/home/vagrant/.rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/versions' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/versions' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/versions' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/versions' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/shims' を作成できません: 許可がありません
mkdir: ディレクトリ `/home/vagrant/.rbenv/versions' を作成できません: 許可がありません
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/shims': Permission denied
==> default: mkdir: cannot create directory `/home/vagrant/.rbenv/versions': Permission denied
==> default: ++ CHK_DIR=/home/vagrant/.rbenv
==> default: ++ '[' '!' -d /home/vagrant/.rbenv ']'
==> default: ++ su vagrant -c sudo echo 'export PATH="$HOME/.rbenv/bin:$PATH"'
==> default: usage: sudo [-D level] -h | -K | -k | -V
==> default: usage: sudo -v [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-u user
==> default:
==> default:             name|#uid]
==> default: usage: sudo -l[l] [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-U user
==> default:             name] [-u user name|#uid] [-g groupname|#gid] [command]
==> default: usage: sudo [-AbEHknPS] [-r role] [-t type] [-C fd] [-D level] [-g
==> default:             groupname|#gid] [-p prompt] [-u user name|#uid] [-g groupname|#gid]
==> default:             [VAR=value] [-i|-s] [<command>]
==> default: usage: sudo -e [-AknS] [-r role] [-t type] [-C fd] [-D level] [-g
==> default:             groupname|#gid] [-p prompt] [-u user name|#uid] file ...
$ ls -hal  /home/vagrant/.rbenv
合計 76K
drwxr-xr-x  10 root    root    4.0K 11月 21 17:58 2014 .
export PATH="/home/vagrant/.rbenv/shims:${PATH}" export RBENV_SHELL=bash source '/home/vagrant/.rbenv/libexec/../completions/rbenv.bash' rbenv rehash 2>/dev/null rbenv() { local command command="$1" if [ "$#" -gt 0 ]; then shift fi case "$command" in rehash|shell) eval "`rbenv "sh-$command" "$@"`";; *) command rbenv "$command" "$@";; esac }
[vagrant@localhost ~]$ eval "$( rbenv init - )"
[vagrant@localhost ~]$ rbenv init -
export PATH="/home/vagrant/.rbenv/shims:${PATH}"
export RBENV_SHELL=bash
source '/home/vagrant/.rbenv/libexec/../completions/rbenv.bash'
rbenv rehash 2>/dev/null
rbenv() {
  local command
  command="$1"
  if [ "$#" -gt 0 ]; then
    shift
  fi

  case "$command" in
  rehash|shell)
    eval "`rbenv "sh-$command" "$@"`";;
  *)
    command rbenv "$command" "$@";;
  esac
}

備考

ただシェルスクリプトを実行しているだけだよ!

  • シェルスクリプトが変更されたら、その変更点だけをインストールするようにしてるコマンドなの?

もうインストールされているパッケージなんかは、例えばyumとかのパッケージ管理ツールが管理している領域

  • nokogiriを入れるときにこけてしまい、gem install nokogiri -- --use-system-librariesで通るぞとエラーメッセージに書いてあったためいれていた。
  • でもこれは、`system-libraries の libxml2, libxslt が脆弱性対応をしてくれないということから patch 当ててビルドする、という方針とのこと
  • .bashrc ・・・ bashの起動時に毎回読み込まれる.
  • .bash_profile ・・・ ログイン次に読み込まれる.
  • echo 'eval "$(rbenv init -)"rbenv initコマンドを呼び出すようにします。実際は~/.rbenv/libexec/rbenv-initのシェルを呼び出している
yutokyokutyo commented 9 years ago

Ops研修(11月25日)

Chapter 5: Serverspec の導入

-[x] Rubyの最新安定版が更新されて、ruby2.1.5になっていたので、テストも書き換える。

-[] ruby をglobal設定にしないと、あらゆる環境下でRubyを使うことができなかったのでこのテストも追加する必要がある

-[] Rubygemsのテストが、ディレクトリに対してのバリデーション

Chapter 6: shell provisioner の導入

rbenvをgitcloneする際にルートユーザーでcloneしてしまったため、homeディレクトリ以下のrbenvの実行権限がrootになってしまっている

==> default: See 'git help COMMAND' for more information on a specific command.
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

vm上に入って同じコマンドを打つとパスワードを要求される

$ su vagrant -c git clone https://github.com/sstephenson/rbenv.git
パスワード:
su: パスワードが違います
原因

1: vm上で、vagrantユーザーのまま上のコマンドを打ってしまったこと($ sudo su -でrootユーザーに切り替ると上手くいきました) 2: su -c の後は``をつけなければいけなかったこと

# su vagrant -c 'git clone https://github.com/sstephenson/rbenv.git /home/vagrant/.rbenv'
fatal: Could not change back to '/root': Permission denied

3: su - で変身するユーザーの環境設定に変更をしていなかったため

# su - vagrant -c 'git clone https://github.com/sstephenson/rbenv.git /home/vagrant/.rbenv'
Initialized empty Git repository in /home/vagrant/.rbenv/.git/
remote: Counting objects: 2002, done.
remote: Total 2002 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2002/2002), 318.88 KiB | 286 KiB/s, done.
Resolving deltas: 100% (1249/1249), done.
# ls -hal
total 32K
drwx------. 5 vagrant vagrant 4.0K Nov 25 12:45 .
drwxr-xr-x. 3 root    root    4.0K Jul 16 17:42 ..
-rw-r--r--. 1 vagrant vagrant   18 Jul 18  2013 .bash_logout
-rw-r--r--. 1 vagrant vagrant   76 Jul 16 17:42 .bash_profile
-rw-r--r--. 1 vagrant vagrant  124 Jul 18  2013 .bashrc
drwxrw----  3 vagrant vagrant 4.0K Nov 25 12:39 .pki
drwxr-xr-x  9 vagrant vagrant 4.0K Nov 25 12:45 .rbenv
drwx------  2 vagrant root    4.0K Jul 16 17:42 .ssh

結果、homeディレクトリの実行ユーザーがvagrantになった!やったね!

rbenv のPAthの設定でこけていて、Rubyをインストールできない

su - vagrant -c 'echo' 'export PATH="$HOME/.rbenv/bin:$PATH"' '>> /home/vagrant/.bash_profile'
su - vagrant -c 'echo' 'eval "$(rbenv init -)"' '>> /home/vagrant/.bash_profile'
su - vagrant -c 'exec $SHELL -l'

いちいちsu -vagrant -c をする必要もないし、su -c の書き方が難しくてエラーがたくさんでてくるので以下のように書くことにしました。

su - vagrant
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> /home/vagrant/.bash_profile
echo 'eval "$(rbenv init -)"' >> /home/vagrant/.bash_profile
exec $SHELL -l

PATHは通ったがまだRubyをインストールできない

su - vagrant
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> /home/vagrant/.bash_profile
echo 'eval "$(rbenv init -)"' >> /home/vagrant/.bash_profile
su - vagrant -c 'exec $SHELL -l'

vagrant provision する度に.bash_profileの中に設定内容が追記され続けてしまう

# rbenvをcloneする
CHK_DIR=/home/vagrant/.rbenv

if [ ! -d ${CHK_DIR} ] ; then
su - vagrant -c 'git clone https://github.com/sstephenson/rbenv.git /home/vagrant/.rbenv'
fi

# rbenvの環境設定
su - vagrant
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> /home/vagrant/.bash_profile
echo 'eval "$(rbenv init -)"' >> /home/vagrant/.bash_profile
su - vagrant -c 'exec $SHELL -l'

現在では上のようにrbenvのcloneと環境設定を別々でで書いているので、ifの中にrbenvの環境設定をいれてみると解決した。

Rubyをインストールすることができた

==> default: Initialized empty Git repository in /home/vagrant/.rbenv/plugins/ruby-build/.git/
==> default: ++ su - vagrant -c 'rbenv install 2.1.5'
==> default: Downloading ruby-2.1.5.tar.gz...
==> default: -> http://dqw8nmjcqpjn7.cloudfront.net/4305cc6ceb094df55210d83548dcbeb5117d74eea25196a9b14fa268d354b100
==> default: Installing ruby-2.1.5...
==> default: Installed ruby-2.1.5 to /home/vagrant/.rbenv/versions/2.1.5

Rubyをインストールしたが、テストが落ちる。。泣

[vagrant@localhost ~]$ ruby -v
rbenv: version `system' is not installed
[vagrant@localhost ~]$ rbenv version
system (set by /home/vagrant/.rbenv/version)
Command "/home/vagrant/.rbenv/shims/ruby -v"
  stdout
    should match /ruby 2.1.5/

Rubyjemsをいれた覚えないけどもいつのまにか入っている。どのタイミングで入ったのだろう?

.gemrc を作成してrdoc.riをいれない設定を施す

bundlerをインストールする

==> default: ++ su - vagrant -c 'gem install bundler'
==> default: Successfully installed bundler-1.7.7
==> default: 1 gem installed

明日は引き続き、serverspecのテストと、gemfile,iptabels,sampleappのgitcloneのprovisioningを行なっていく

現在のshellprovisioningファイル

https://gist.github.com/yutokyokutyo/afe93d843510208bde4d

備考

% vagrant up                                                                                                                                                         (git)-[master]
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hfm4/centos6' is up to date...
==> default: A newer version of the box 'hfm4/centos6' is available! You currently
==> default: have version '1.0'. The latest is version '1.1'. Run
==> default: `vagrant box update` to update.
==> default: Clearing any previously set forwarded ports...
Vagrant cannot forward the specified ports on this VM, since they
would collide with some other application that is already listening
on these ports. The forwarded port to 3000 is already in use
on the host machine.

To fix this, modify your current projects Vagrantfile to use another
port. Example, where '1234' would be replaced by a unique host port:

  config.vm.network :forwarded_port, guest: 3000, host: 1234

Sometimes, Vagrant will attempt to auto-correct this for you. In this
case, Vagrant was unable to. This is usually because the guest machine
is in a state which doesn't allow modifying port forwarding.

http://qiita.com/betahikaru/items/d77f5891f222eba0c4fa

  • Vagrantはデフォルトだと、ホストの2222番にゲストの22番をフォワードするよう
  • 一つ目はホスト側もゲスト側も22番や2222番に関係のない数値を割り当てていたため、デフォルト設定のhost:2222,gest:22が割り当てられたのかな?
  • config.vm.network :forwarded_port, id: "ssh", guest: 22, host: 2224 のように、id: "ssh"を付け足すと、デフォルトの設定を上書きできるとのこと!

~/centos6-sampleapp

config.vm.network :forwarded_port, host: 3001, guest: 1122

[usr0600328@PMAC146S] ~/centos6-sampleapp
% vagrant up                                                                                                                                                         (git)-[master]
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hfm4/centos6' is up to date...
==> default: A newer version of the box 'hfm4/centos6' is available! You currently
==> default: have version '1.0'. The latest is version '1.1'. Run
==> default: `vagrant box update` to update.
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 1122 => 3001 (adapter 1)
    default: 22 => 2222 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/usr0600328/centos6-sampleapp
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: to force provisioning. Provisioners marked to run always will still run.

~/sampleapp_provisioning

config.vm.network :forwarded_port, id: "ssh", host: 2223, guest:22

[usr0600328@PMAC146S] ~/sampleapp_provisioning
% vagrant  up                                                                                                                                                        (git)-[master]
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hfm4/centos6' is up to date...
==> default: A newer version of the box 'hfm4/centos6' is available! You currently
==> default: have version '1.0'. The latest is version '1.1'. Run
==> default: `vagrant box update` to update.
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2223 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2223
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/usr0600328/sampleapp_provisioning
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: to force provisioning. Provisioners marked to run always will still run.

~/sampleapp_provisioning

config.vm.network :forwarded_port, host: 2223, guest:22

[usr0600328@PMAC146S] ~/sampleapp_provisioning
% vagrant up                                                                                                                                                         (git)-[master]
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hfm4/centos6' is up to date...
==> default: A newer version of the box 'hfm4/centos6' is available! You currently
==> default: have version '1.0'. The latest is version '1.1'. Run
==> default: `vagrant box update` to update.
==> default: Clearing any previously set forwarded ports...
==> default: Fixed port collision for 22 => 2222. Now on port 2200.
  1 # -*- mode: ruby -*-
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 => 2223 (adapter 1)
    default: 22 => 2200 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2200
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/usr0600328/sampleapp_provisioning
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: to force provisioning. Provisioners marked to run always will still run.
yutokyokutyo commented 9 years ago

Ops研修(11月27日)

Chapter 5: Serverspec の導入

Chapter 6: shell provisioner の導入

bundle install

bundle install --wthout production をしてインストール完了!

https://gist.github.com/yutokyokutyo/c084c32cb05e8d9293ac

iptablesの設定

if分の条件式にshellを書けるとのことなので、grepで中身があることを確認する手法、もしくは追記しないで完成型のファイルを作っておく

  • コマンドが実行されているかどうかを確かめる
  • echo $?で調べられる。0は成功1は失敗($?には直前のコマンドに対するステータスが入っている)
  • && でコマンドをつなげると、直前のコマンドが成功した場合のみ次のコマンドが実行される
  • || でコマンドをつなげると、直前のコマンドが失敗した場合のみ次のコマンドが実行される。
  • if 文は条件式に指定されたコマンドの終了ステータスを判定し分岐を行う
  • grepが成功するかどうかをみる
[vagrant@localhost sample_app]$ sudo grep 'tcp -m tcp --dport 3000 -j ACCEPT' /etc/sysconfig/iptables
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
if ! sudo grep 'tcp -m tcp --dport 3000 -j ACCEPT' /etc/sysconfig/iptables ; then
echo '-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT' >> /etc/sysconfig/iptables
service iptables restart
fi

多分これで、追記されないはず!

iptables restartでこけた

==> default: ++ service iptables restart
==> default: iptables: Setting chains to policy ACCEPT: filter
==> default: [  OK  ]
==> default: iptables: Flushing firewall rules:
==> default: [  OK  ]
==> default:
==> default: iptables: Unloading modules:
==> default: [  OK
==> default: ]
==> default: iptables: Applying firewall rules:
==> default: iptables-restore: line 14 failed
==> default: [
==> default: FAILED]

iptabelsのファイルを見てみると以下のように追記した文字列がCOMMITの下に記述されていた

# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT

sedを使って強引にファイルの中身をいい感じにした。置換便利すぎる!

if ! sudo grep 'tcp -m tcp --dport 3000 -j ACCEPT' /etc/sysconfig/iptables ; then
sed -i -e "s/COMMIT/-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT/g" /etc/sysconfig/iptables
echo 'COMMIT' >> /etc/sysconfig/iptables
service iptables restart
fi

テスト結果

==> default: + sed -i -e 's/COMMIT/-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT/g' /etc/sysconfig/iptables
==> default: + echo COMMIT
==> default: + service iptables restart
==> default: iptables: Setting chains to policy ACCEPT: filter
==> default: [  OK  ]
==> default: iptables: Flushing firewall rules:
==> default: [  OK  ]
==> default: iptables: Unloading modules:
==> default: [  OK
==> default: ]
==> default: iptables: Applying firewall rules:
==> default: [  OK
==> default: ]

オッケー牧場!

DBのmigrate

https://gist.github.com/yutokyokutyo/7eccb54dcc07f604aedf

rails server が起動しない

テストこけた

$ rails server
-bash: rails: コマンドが見つかりません 

rbenv rehash をを打ってもダメ

$ which rails
/usr/bin/which: no rails in (/home/vagrant/.rbenv/shims:/home/vagrant/.rbenv/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/sbin:/usr/sbin:/home/vagrant/bin)

本質的な解決にはなってないよ!

  • bundle でインストールしたものは/home/vagrant/sample_app/vendor/bundle/ruby/2.1.0/bin/railsにインストールされbundleが管理する
  • gem でインストールしたものは~/.rbenv/shims/railsに入る
  • whichでrailsを見つけられなかったのは、bundleでインストールしたものにPATHが通ってなかったから(gemでインストールする場所にPATHが通るようになっている)
  • つまり本質的な解決はbundlerでインストールしたものは bundle exec をつけて実行することにあったのだぁ!

rbenvのglobal設定を確認するテストがこける

1) Command "/home/vagrant/.rbenv/bin/rbenv version" stdout should match /2.1.5/
     On host `default'
     Failure/Error: its(:stdout) { should match /2.1.5/ }
       expected "system (set by /root/.rbenv/version)\n" to match /2.1.5/
       Diff:
       @@ -1,2 +1,2 @@
       -/2.1.5/
       +system (set by /root/.rbenv/version)
describe command('/home/vagrant/.rbenv/bin/rbenv version') do
  its(:stdout) { should match /2.1.5/ }
end
unknown regexp option - h (SyntaxError)
end pattern with unmatched parenthesis: /2.1.5 (set by /m
/Users/usr0600328/sampleapp_provisioning/spec/default/sample_spec.rb:69: syntax error, unexpected '.'
... /2.1.5 (set by /home/vagrant/.rbenv/version)/ }
...                               ^
/Users/usr0600328/sampleapp_provisioning/spec/default/sample_spec.rb:69: syntax error, unexpected ')', expecting '}'
...y /home/vagrant/.rbenv/version)/ }
...                               ^
/Users/usr0600328/sampleapp_provisioning/spec/default/sample_spec.rb:124: syntax error, unexpected end-of-input, expecting '}'
describe file('/home/vagrant/.rbenv/version') do
  it { should contain('2.1.5') }
end

おっくん氏レビューメモ

パッケージ集をまとめる作業とdescribeで奇麗に整理する部分の途中で今日は終わり。明日に続くのであった。 デプロイのフェイズのテストやprovisioningはしない方針にした!

現在のshellprovisioningファイル

https://gist.github.com/yutokyokutyo/df43f3202acd000187b2

備考

http://qiita.com/camelmasa/items/5ca27ab398f105f86c76

  • unboundは、変数の束縛がないよ。hoge = fuga のように紐づいてないよってこと
yutokyokutyo commented 9 years ago

Ops研修(11月28日)

Chapter 5: Serverspec の導入

Chapter 6: shell provisioner の導入

rails server のプロセスが3つもある

root     12297  0.0  0.1 163748  1952 ?        S    07:07   0:00 su - vagrant -c cd /home/vagrant/sample_app/ ; bundle exec rails server
vagrant  12298  0.0  0.1 108204  1488 ?        Ss   07:07   0:00 -bash -c cd /home/vagrant/sample_app/ ; bundle exec rails server
vagrant  12359  0.0  7.4 294992 75548 ?        Sl   07:07   0:04 /home/vagrant/.rbenv/versions/2.1.5/bin/ruby bin/rails server

myappのpermissionを確認する

  describe file('/home/vagrant/sample_app') do
    it { should be_directory }
    it { should be_mode 755 }
    it { should be_owned_by 'vagrant' }
    it { should be_grouped_into 'vagrant' }
  end

これで大丈夫かな

rails のバージョンをテストする

Failures:

  1) Rails Command "/home/vagrant/sample_app/vendor/bundle/ruby/2.1.0/bin/rails --version" stdout should match /4.0.8/
     On host `default'
     Failure/Error: its(:stdout) { should match /4.0.8/ }
       expected "" to match /4.0.8/
       Diff:
       @@ -1,2 +1,2 @@
       -/4.0.8/
       +""

       sudo -p 'Password: ' /bin/sh -c /home/vagrant/sample_app/vendor/bundle/ruby/2.1.0/bin/rails\ --version

     # ./spec/default/sample_spec.rb:74:in `block (3 levels) in <top (required)>'

serverspecのテストコード

  describe command('/home/vagrant/sample_app/vendor/bundle/ruby/2.1.0/bin/rails --version') do
    its(:stdout) { should match /4\.0\.\d/ }
  end

パッケージのバージョンはテストしなくていいかな?

should contain はdeprecatedなので使わないようにする

rubygems のテストはいる?

    describe file('/home/vagrant/.rbenv/versions/2.1.5/lib/ruby/gems') do
      it { should be_directory }
    end
    describe command('/home/vagrant/.rbenv/shims/gem -v') do
      its(:stdout) { should match /2\.2\.2/ }
    end

localserver:3000が見れない!

ボスケテで解決!

問題は2つ!

  1. ポートフォワーディングがされていない
    • もともとはフォワーディングされていたのですが、sshのフォワーディングの設定をしていたときに消してしまったが原因
  2. iptablesの設定内容に不具合があった
    • iptablesは順番が重要で、全てのポートをREJECTしてしまう文の後に、3000番ポートを許可する設定の文を書き足していたことが原因
    • -AでINPUTに対しての設定するのであれば、指定したチェーンの一番上に追記さあれるので適切な段落に書き足すこと(Append)
    • -Iの場合はチェーン内のユーザー定義の数値で指定された位置に規則を鵜入する。数値が指定されていない場合、iptables はそのコマンドをチェーンの最上部に置かれる。

失敗例

iptablesファイル

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
COMMIT

結果

$ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-Iの場合

iptablesファイル

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-I INPUT -p tcp -m tcp --dport 3000 -j ACCEPT

結果

$ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

-Aの場合

iptablesファイル

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

結果

$ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

これらのテストとprovisioningを再度見直す必要がある!

/home/vagrant/sample_app/vendor/bundle/ruby/2.1.0の2.1.0ってなんでしょう?

$ ~/.rbenv/shims/ruby -v
ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]

いいのかな?

このディレクトリは、2.1.なんちゃらだったら、2.1.0になるのだ。例えば1.8.7だったら、1.8.0になる。系の名前がそこに入るとのこと。詳しくは月曜日にしばたさんにお聞きする。

備考

yutokyokutyo commented 9 years ago

Ops研修(12月1日)

Chapter 5: Serverspec の導入

Chapter 6: shell provisioner の導入

/home/vagrant/sample_app/vendor/bundle/ruby/2.1.0の2.1.0ってなんだろう?

ボスケテで解決!

https://gist.github.com/yutokyokutyo/8b796e2ea30e9519b30d

Rails のバージョンがテストできない

ひろやんさんにお助けいただいた。 RialsのPATHが通ってないと思っていたら、rbenvが管理しているrubyのpathが通っていなかった。 しかもまたsudoかsudoじゃないかではまってしまった。

  describe command('source ~/.bash_profile; cd ~/sample_app; bundle exec rails -v') do
    let(:disable_sudo) { true }
    its(:stdout) { should match /4\.0\.\d/ }
  end

git reset --hard してしまい、今までのデータがぶっ飛んだ

違うタブにserverspecのファイルが開きっぱなしになっていたのと、gistにprovisioningファイルのバックアップがあったので、なんとか復旧できました。 git reset --hardこわい。

もう一度最初から作り直してみる。。うう。

一通り元に戻せたのでvagrat up してみる。 するとエラーが。。

==> default: ++ su - vagrant -c 'gem install bundler'
==> default: /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/psych.rb:370:in `parse': (<unknown>): could not find expected ':' while scanning a simple key at line 2 column 1 (Psych::SyntaxError)
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/psych.rb:370:in `parse_stream'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/psych.rb:318:in `parse'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/psych.rb:245:in `load'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/rubygems/config_file.rb:333:in `load_file'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/rubygems/config_file.rb:198:in `initialize'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/rubygems/gem_runner.rb:74:in `new'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/rubygems/gem_runner.rb:74:in `do_configuration'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/lib/ruby/2.1.0/rubygems/gem_runner.rb:39:in `run'
==> default:    from /home/vagrant/.rbenv/versions/2.1.5/bin/gem:21:in `<main>'
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

どうやら、余計な:が入っているもよう。 疑わしい.gemrcを見てみると、

:sources:
u https://rubygems.org/
install: --no-rdoc --no-ri
update: --no-rdoc --no-ri

になっていた。調べたところsourcesの部分はいらなそうなので排除してみるとテストが通った。 一から作り直したことで、今まで見えてこなかったエラーを確認することができて良かった。

元通りに復旧してテストも全て通りました!やったあ!今回の事件で大幅に遅れてしまったので明日こそ頑張ってPRだします!

yutokyokutyo commented 9 years ago

Ops研修(12月2日)

Chapter 5: Serverspec の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/1

レビューをしていただき適宜修正しております!

Chapter 6: shell provisioner の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/2

レビューをしていただき適宜修正しております!

備考

https://www.gitignore.io/

  • vagrant box update をしていなかったので、boxの内容が更新されていませんでした!うがあ!
% vagrant box update                                                  (git)-[serverspec]
==> default: Checking for updates to 'hfm4/centos6'
    default: Latest installed version: 1.0
    default: Version constraints:
    default: Provider: virtualbox
==> default: Updating 'hfm4/centos6' with provider 'virtualbox' from version
==> default: '1.0' to '1.1'...
==> default: Loading metadata for box 'https://vagrantcloud.com/hfm4/centos6?access_token=FWxorYY7gVqaptL6_fxbezCkqoXLCMYJns4D5x4x-xz4dtMz3KLdkaWyJ43BoTuzvmQ'
==> default: Adding box 'hfm4/centos6' (v1.1) for provider: virtualbox
    default: Downloading: https://vagrantcloud.com/hfm4/boxes/centos6/versions/1.1/providers/virtualbox.box
==> default: Successfully added box 'hfm4/centos6' (v1.1) for 'virtualbox'!
yutokyokutyo commented 9 years ago

Ops研修(12月3日)

Chapter 5: Serverspec の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/1

明日は rbenv のバージョンの確認について、正規表現を%記法で書く件について、ruby-version についてレビューを取り込んでいきます!

Chapter 6: shell provisioner の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/2

一通りレビューを取り込んだつまおりでしたが、取り込んでいる最中に Gemfil eについて不備が見つかったので、明日はその部分について修正したいと思います。

yutokyokutyo commented 9 years ago

Ops研修(12月4日)

Chapter 5: Serverspec の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/1

Chapter 6: shell provisioner の導入

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/2

備考

http://qiita.com/harapeko_wktk/items/f329ba818690bdee7dd8

  • git で詰まったら一旦元に戻してみること
  • gibo を活用するのだ!
% git st                                                                                         (git)-[serverspec]
On branch serverspec
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   spec/default/sample_spec.rb
    deleted:    vagrant/.provision.sh.swp

deleted: vagrant/.provision.sh.swp の消し方が分からない。邪魔ぽよ。 checkout で表示からは消すことができるが、またswpファイルが復活してしまう。

どのレイヤーで動かすのかを意識する

更新頻度の時間軸と時間が前後するかどうか 変更をしたい

http://mizzy.org/blog/2013/10/29/1/

yutokyokutyo commented 9 years ago

Ops研修(12月4日)

Chapter 5: Serverspec の導入

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm/pull/1

テストが実行できない?

% bundle exec rake spec                                                                                                                                                                                                                                      (git)-[serverspec]
Could not find rake-10.4.0 in any of the sources
Run `bundle install` to install missing gems.

Rake のGemが消えてしまったのでインストールしました。 でもこれは良いのです! 以前とは違う環境でテストを実行したので、Rake がインストールできていないだけでした。Gemfileにrakeが書いてあるので、もしも自分ではない誰かがこのリポジトリをcloneしてきたとしても bundle install してもらえばいいだけ! むしろ、事前にインストールされたリポジトリにしてしまう方が良くない。

therubyracer がインストールされない

==> default: Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
==> default:
==> default:     /home/vagrant/.rbenv/versions/2.1.5/bin/ruby extconf.rb
==> default: checking for main() in -lpthread... yes
==> default: creating Makefile
==> default:
==> default: make "DESTDIR=" clean
==> default:
==> default: make "DESTDIR="
==> default: compiling rr.cc
==> default: make: g++: Command not found
==> default: make: *** [rr.o] Error 127
==> default:
==> default: make failed, exit code 2
==> default:
==> default: Gem files will remain installed in /home/vagrant/Sample_app_on_VM/vendor/bundle/ruby/2.1.0/gems/therubyracer-0.12.1 for inspection.
==> default: Results logged to /home/vagrant/Sample_app_on_VM/vendor/bundle/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/therubyracer-0.12.1/gem_make.out
==> default: An error occurred while installing therubyracer (0.12.1), and Bundler cannot
==> default: continue.
==> default: Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

インストールされた!そして vagrant provision も成功!

==> default: Dependencies Resolved
==> default:
==> default: ================================================================================
==> default:  Package                 Arch           Version              Repository    Size
==> default: ================================================================================
==> default: Installing:
==> default:  gcc-c++                 x86_64         4.4.7-11.el6         base         4.7 M
==> default: Installing for dependencies:
==> default:  libstdc++-devel         x86_64         4.4.7-11.el6         base         1.6 M
==> default:
==> default: Transaction Summary
==> default: ================================================================================
==> default: Install       2 Package(s)
==> default: Total download size: 6.3 M
==> default: Installed size: 20 M
==> default: Downloading Packages:
==> default: --------------------------------------------------------------------------------
==> default: Total                                           7.9 MB/s | 6.3 MB     00:00
==> default: Running rpm_check_debug
==> default: Running Transaction Test
==> default: Transaction Test Succeeded
==> default: Running Transaction
  Installing : libstdc++-devel-4.4.7-11.el6.x86_64                          1/2
==> default:
  Installing : gcc-c++-4.4.7-11.el6.x86_64                                  2/2
==> default:
  Verifying  : libstdc++-devel-4.4.7-11.el6.x86_64                          1/2
==> default:
  Verifying  : gcc-c++-4.4.7-11.el6.x86_64                                  2/2
==> default:
==> default:
==> default: Installed:
==> default:   gcc-c++.x86_64 0:4.4.7-11.el6

Chapter 6: shell provisioner の導入

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm/pull/2

unbound variable

一通りレビューを取り込んだので一旦 vagrat destroy をして環境構築をし直してみるとエラーが!

==> default: +++ . /etc/bashrc
==> default: /etc/bashrc: line 12: PS1: unbound variable
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

変数が未定義だった

set +u
source /home/vagrant/.bash_profile
set -u

-u は未定義の変数が存在するとエラーをはくので、ここを一旦飛ばすエラーレベルに設定しなおしました

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm

Shell provisioner と serverspec のテストをひとまず完成できました!(Development環境版) ありがとうございました!

備考

yutokyokutyo commented 9 years ago

Ops研修(12月5日)

Chapter 5: Serverspec の導入

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm/pull/1

テストが実行できない?

% bundle exec rake spec                                                                                                                                                                                                                                      (git)-[serverspec]
Could not find rake-10.4.0 in any of the sources
Run `bundle install` to install missing gems.

Rake のGemが消えてしまったのでインストールしました。 でもこれは良いのです! 以前とは違う環境でテストを実行したので、Rake がインストールできていないだけでした。Gemfileにrakeが書いてあるので、もしも自分ではない誰かがこのリポジトリをcloneしてきたとしても bundle install してもらえばいいだけ! むしろ、事前にインストールされたリポジトリにしてしまう方が良くない。

therubyracer がインストールされない

==> default: Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
==> default:
==> default:     /home/vagrant/.rbenv/versions/2.1.5/bin/ruby extconf.rb
==> default: checking for main() in -lpthread... yes
==> default: creating Makefile
==> default:
==> default: make "DESTDIR=" clean
==> default:
==> default: make "DESTDIR="
==> default: compiling rr.cc
==> default: make: g++: Command not found
==> default: make: *** [rr.o] Error 127
==> default:
==> default: make failed, exit code 2
==> default:
==> default: Gem files will remain installed in /home/vagrant/Sample_app_on_VM/vendor/bundle/ruby/2.1.0/gems/therubyracer-0.12.1 for inspection.
==> default: Results logged to /home/vagrant/Sample_app_on_VM/vendor/bundle/ruby/2.1.0/extensions/x86_64-linux/2.1.0-static/therubyracer-0.12.1/gem_make.out
==> default: An error occurred while installing therubyracer (0.12.1), and Bundler cannot
==> default: continue.
==> default: Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

インストールされた!そして vagrant provision も成功!

==> default: Dependencies Resolved
==> default:
==> default: ================================================================================
==> default:  Package                 Arch           Version              Repository    Size
==> default: ================================================================================
==> default: Installing:
==> default:  gcc-c++                 x86_64         4.4.7-11.el6         base         4.7 M
==> default: Installing for dependencies:
==> default:  libstdc++-devel         x86_64         4.4.7-11.el6         base         1.6 M
==> default:
==> default: Transaction Summary
==> default: ================================================================================
==> default: Install       2 Package(s)
==> default: Total download size: 6.3 M
==> default: Installed size: 20 M
==> default: Downloading Packages:
==> default: --------------------------------------------------------------------------------
==> default: Total                                           7.9 MB/s | 6.3 MB     00:00
==> default: Running rpm_check_debug
==> default: Running Transaction Test
==> default: Transaction Test Succeeded
==> default: Running Transaction
  Installing : libstdc++-devel-4.4.7-11.el6.x86_64                          1/2
==> default:
  Installing : gcc-c++-4.4.7-11.el6.x86_64                                  2/2
==> default:
  Verifying  : libstdc++-devel-4.4.7-11.el6.x86_64                          1/2
==> default:
  Verifying  : gcc-c++-4.4.7-11.el6.x86_64                                  2/2
==> default:
==> default:
==> default: Installed:
==> default:   gcc-c++.x86_64 0:4.4.7-11.el6

Chapter 6: shell provisioner の導入

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm/pull/2

unbound variable

一通りレビューを取り込んだので一旦 vagrat destroy をして環境構築をし直してみるとエラーが!

==> default: +++ . /etc/bashrc
==> default: /etc/bashrc: line 12: PS1: unbound variable
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what
went wrong.

変数が未定義だった

set +u
source /home/vagrant/.bash_profile
set -u

-u は未定義の変数が存在するとエラーをはくので、ここを一旦飛ばすエラーレベルに設定しなおしました

PR(マージ済)

https://github.com/yutokyokutyo/sampleapp_vm

Shell provisioner と serverspec のテストをひとまず完成できました!(Development環境版) ありがとうございました!

備考

yutokyokutyo commented 9 years ago

Ops研修(12月8日)

Chapter 7: Puppet, Chef, itamae で環境構築する

Puppet

file { '/etc/hosts':
    owner  => 'root',
    group  => 'root',
    mode   => 644,
}

リソースタイプ一覧

https://docs.puppetlabs.com/references/stable/type.html

  • puppet:manifests *.pp ;module
  • chef:recipes *.rb ; cookbook
  • puppet apply:manifestをそれぞれのnode上で個別に運用する

chef

itamae

サーバー構成管理ツール

Puppet入門書を読む!

Vagrantで開発環境を用意するところまで読みましたので、本格的に内容に入るには明日かな。

備考

yutokyokutyo commented 9 years ago

Ops研修(12月9日)

Chapter 7: Puppet を導入する

Puppet入門書を読む!

vagrant ssh-configする

sshコマンドで仮想ホストにログインする際にhostnameを追記。ログインの応答も早くなるとのこと。

出典:http://qiita.com/Sanche/items/43d615beef05cd9417e2#1-2

Vagrant ssh-config --host puppet-book.localの実行内容は以下の通り。

Host puppet-book.local
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/usr0600328/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

あれれ?でもVagrant ssh-config --host puppet-book.local >> ~/ssh/configを実行してみたら、もともとあった.ssh/configには以下のように記述されてしまったぞう。。いいのかな?

Host host1
HostName manage001.tokyo.pb
User kyokutyo
Host dokku001.tokyo.pb
    HostName dokku001.tokyo.pb
    User dokku
    IdentityFile ~/.ssh/id_dsa.pbHost puppet-book.local
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/usr0600328/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

sshでログインをを試みる。

% ssh puppet-book.local
/Users/usr0600328/.ssh/config line 7: garbage at end of line; "puppet-book.local".

ダメだ!7行目にゴミがあるって言われてる。

.ssh/config の書き方を調べる。複数のHostセクションの設定をする場合、Host毎に区別して書かなくてはいけないみたい。

出典:http://nauthiz.hatenablog.com/entry/20100919/1284892108

書き直してみた。

Host host1
  HostName manage001.tokyo.pb
  User kyokutyo

Host dokku001.tokyo.pb
  HostName dokku001.tokyo.pb
  User dokku

Host puppet-book.local
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/usr0600328/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

sshでログインできるようになったああ!!

Nginxとは

地雷

ldapname が deprecated らしい・・・どゆこと??

$ puppet apply hello_world.pp
ldapname is deprecated and will be removed in a future version
Facter::Util::EC2.has_euca_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_openstack_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_ec2_arp? is deprecated; see the Facter::EC2 classes instead
Error loading fact /usr/lib/ruby/site_ruby/1.8/facter/macosx.rb: no such file to load -- cfpropertylist
Could not retrieve fact='arp_lo', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Could not retrieve fact='arp_eth0', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Notice: Scope(Class[main]): Hello, World!
Notice: Compiled catalog for puppet-book.local in environment production in 0.02 seconds
Notice: Finished catalog run in 0.02 seconds

Warning!?

[vagrant@puppet-book nginx]$ sudo puppet apply --templatedir=. nginx.pp
ldapname is deprecated and will be removed in a future version
Facter::Util::EC2.has_euca_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_openstack_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_ec2_arp? is deprecated; see the Facter::EC2 classes instead
Error loading fact /usr/lib/ruby/site_ruby/1.8/facter/macosx.rb: no such file to load -- cfpropertylist
Could not retrieve fact='arp_lo', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Could not retrieve fact='arp_eth0', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Warning: Variable access via 'port' is deprecated. Use '@port' instead. template[/vagrant/puppet/nginx/my.conf]:2
   (at /usr/lib/ruby/gems/1.8/gems/puppet-3.7.3/lib/puppet/parser/templatewrapper.rb:76:in `method_missing')
Notice: Compiled catalog for puppet-book.local in environment production in 0.65 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/lib/ruby/gems/1.8/gems/puppet-3.7.3/lib/puppet/type/package.rb:430:in `default')
Notice: Finished catalog run in 0.36 seconds

でも一応nginxは起動しているみたい

[vagrant@puppet-book nginx]$ curl http://localhost:80/
Hello, Puppet!

Puppetをインストールしなおした

[vagrant@puppet-book ~]$ sudo gem install puppet --no-rdoc --no-ri
Successfully installed facter-2.3.0
Successfully installed json_pure-1.8.1
Successfully installed hiera-1.3.4
Successfully installed puppet-3.7.3
4 gems installed

いやいや待て待て。。Vagrant file の中身も間違っていた

修正前

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "centos-6.4-puppet"
  config.vm.box = "http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210.box"

修正後

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "centos-6.4-puppet"
  config.vm.box_url = "http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210.box"

vagrant destroy してもう一度vagrant upをしてからpuppet apply してみた

[vagrant@puppet-book nginx]$ sudo puppet apply --templatedir=. nginx.pp
ldapname is deprecated and will be removed in a future version
Facter::Util::EC2.has_euca_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_openstack_mac? is deprecated; see the Facter::EC2 classes instead
Facter::Util::EC2.has_ec2_arp? is deprecated; see the Facter::EC2 classes instead
Error loading fact /usr/lib/ruby/site_ruby/1.8/facter/macosx.rb: no such file to load -- cfpropertylist
Could not retrieve fact='arp_lo', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Could not retrieve fact='arp_eth0', resolution='<anonymous>': undefined method `get_arp_value' for Facter::Util::IP:Module
Notice: Compiled catalog for puppet-book.local in environment production in 0.61 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/lib/ruby/gems/1.8/gems/puppet-3.7.3/lib/puppet/type/package.rb:430:in `default')
Notice: /Stage[main]/Main/Yumrepo[nginx]/ensure: created
Notice: /Stage[main]/Main/Package[nginx]/ensure: created
Notice: /Stage[main]/Main/File[/usr/share/nginx/html/index.html]/content: content changed '{md5}e3eb0a1df437f3f97a64aca5952c8ea0' to '{md5}1db16ebfb21d376e5b2ae9d1eaf5b3c8'
Notice: /Stage[main]/Main/File[/etc/nginx/conf.d/my.conf]/ensure: created
Notice: /Stage[main]/Main/Service[nginx]/ensure: ensure changed 'stopped' to 'running'
Notice: Finished catalog run in 47.00 seconds

ダメだ!まだエラーをはく!!

vagrant box remove で関連するboxを削除して、もう一度vagrant upする。

もう一度gem を入れ直して、puppet apply してみると、Facterエラーが出なくなりました!

[vagrant@puppet-book nginx]$ sudo puppet apply --templatedir=. nginx.pp
Warning: Setting templatedir is deprecated. See http://links.puppetlabs.com/env-settings-deprecations
   (at /usr/local/lib/ruby/gems/2.1.0/gems/puppet-3.7.3/lib/puppet/settings.rb:1139:in `issue_deprecation_warning')
Notice: Compiled catalog for puppet-book.local in environment production in 1.42 seconds
Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
   (at /usr/local/lib/ruby/gems/2.1.0/gems/puppet-3.7.3/lib/puppet/type/package.rb:430:in `block (3 levels) in <module:Puppet>')
Notice: /Stage[main]/Main/Yumrepo[nginx]/ensure: created
Notice: /Stage[main]/Main/Package[nginx]/ensure: created

解決しました!ありがとうございました!!!

入門Puppetメモ

備考

インターネット経由で入れるサーバの sshd を、 デフォルトの22番ポートのまま動かしていますと、 不埒な輩からの不正なアクセスに悩まされますので、 たいていはポート番号を変更して運用されていると思います。

そうなんだ。いつもデフォルトのまま動かしてた。。

出典:http://www.usupi.org/sysad/247.html

  • マウントする:セットする。配置する。組み込む。認識させて利用可能な状態にすること
  • mkdir -p :サブディレクトリごと作成することができる

出典:http://itpro.nikkeibp.co.jp/article/COLUMN/20060227/230831/

英単語

yutokyokutyo commented 9 years ago

Ops研修(12月10日)

Chapter 7: Puppet を導入する

Puppet入門書を読む!

入門Puppetメモ

puppet を導入するにあたって

vagrant provision することで puppet apply を実行できるようにする

NOOP と DRY RUN

方針

PR(WIP)を作成しました

https://github.com/yutokyokutyo/sampleapp_vm/pull/4

備考

yutokyokutyo commented 9 years ago

Ops研修(12月11日)

Chapter 7: Puppet を導入する

パッケージインストール時のエラー

https://gist.github.com/yutokyokutyo/0d774cebab0c07877a9a

rbenv を git clone するときのエラー

https://gist.github.com/yutokyokutyo/a3d34d9d941dcdbdf1ce

PR

https://gist.github.com/yutokyokutyo/a3d34d9d941dcdbdf1ce

備考

Vimについて

出典:http://qiita.com/hachi8833/items/7beeee825c11f7437f54#level-4

yutokyokutyo commented 9 years ago

Ops研修(12月12日)

Chapter 7: Puppet を導入する

git clone してくるときに、もうそのディレクトリありますよと言われる

creates で指定しているのになんでこんなエラーが出てくるのだろう。。

==> default: Notice: /Stage[main]/Main/Exec[clone rbenv]/returns: fatal: destination path 'rbenv' already exists and is not an empty directory.
==> default: Error: git clone https://github.com/sstephenson/rbenv.git returned 128 instead of one of [0]
==> default: Error: /Stage[main]/Main/Exec[clone rbenv]/returns: change from notrun to 0 failed: git clone https://github.com/sstephenson/rbenv.git returned 128 instead of one of [0]
    cwd      => "/home/vagrant",
    path     => ['/usr/bin'],
    command  => "git clone https://github.com/sstephenson/rbenv.git",
    creates => "/home/vagrant/.rbenv",

依存関係

実行したいリソースタイプ内で他のリソースが必要な場合は require で依存関係を作らないと実行できないと思ってました。例えば、git clone するには、Package の git について依存関係を作らないと、実行できないと思ってました。

==> default: Notice: /Stage[main]/Main/File[/home/vagrant/.bash_profile]: Dependency Exec[clone rbenv] has failures: true
==> default: Warning: /Stage[main]/Main/File[/home/vagrant/.bash_profile]: Skipping because of failed dependencies
==> default: Notice: Finished catalog run in 0.36 seconds

allow_virtual Warning

==> default: Warning: The package type's allow_virtual parameter will be changing its default value from false to true in a future release. If you do not want to allow virtual packages, please explicitly set allow_virtual to false.
==> default:    (at /usr/lib/ruby/site_ruby/1.8/puppet/type/package.rb:430:in `default')

Package { allow_virtual => true } をmanifest の文頭に付け加えることでWorningが消えました。 ちょっと難しいので保留。

テンプレートについて勘違い

file { '/home/vagrant/.bash_profile':
source => '/vagrant/template_bash_profile',
}

bash_profile の再読み込み

notify を指定したものを再読み込みさせる atributes だと思っていたので、以下のように記述すればいいのかなと勘違いしました。

file { '/home/vagrant/.bash_profile':
source => '/vagrant/template_bash_profile',
notify => File['/home/vagrant/.bash_profile']
}

でも、notice はそんな機能ではなかった。 notice は、例えば file から service に対して依存関係を作ったときに、fileの内容を変更したときなんかに通知がいくようにしてくれる atributes 。(変更に対してリスタートしてね〜とか)(iptablesの設定のときとかに必要かな?)

==> default: Error: Could not apply complete catalog: Found 1 dependency cycle:
==> default: (File[/home/vagrant/.bash_profile] => File[/home/vagrant/.bash_profile])
==> default: Try the '--graph' option and opening the resulting '.dot' file in OmniGraffle or GraphViz

notice はいらなかったのであった。

.bash_profile を読み込む

exec リソースタイプでsourseを使って .bash_profile を読みこもうとするとエラーがでる。

==> default: Error: Validation of Exec[.bash_profile load] failed: 'source /home/vagrant/.bash_profile' is not qualified and no path was specified. Please qualify the command or specify a path. at /tmp/vagrant-puppet-3/manifests/init.pp:43
==> default: Wrapped exception:
==> default: 'source /home/vagrant/.bash_profile' is not qualified and no path was specified. Please qualify the command or specify a path.

manifestはこれ

exec { '.bash_profile load':
    command     => 'source /home/vagrant/.bash_profile',
    subscribe   => File['/home/vagrant/.bash_profile'],
    refreshonly => true,
}

解決

ruby-build をcloneする

clone しようと思ったら、~/.rbenv/pluginsなんてディレクトリはないよっていわれた

==> default: Error: Working directory '/home/vagrant/.rbenv/plugins' does not exist
==> default: Error: /Stage[main]/Main/Exec[clone ruby-build]/returns: change from notrun to 0 failed: Working directory '/home/vagrant/.rbenv/plugins' does not exist
==> default: Notice: Finished catalog run in 0.20 seconds

ssh でみてみたら、確かにない。。もしかしてこのディレクトリを作る必要あるのかな。。 いや、そんなことしなくても、cwd と command の中の path の指定をしてあげることで実行された

==> default: Notice: /Stage[main]/Main/Exec[clone ruby-build]/returns: executed successfully
==> default: Notice: Finished catalog run in 8.20 seconds

Ruby をインストールする

source が見つからないよ!エラー

==> default: Error: Could not find command '/bin/bash/source'
==> default: Error: /Stage[main]/Main/Exec[ruby install]/returns: change from notrun to 0 failed: Could not find command '/bin/bash/source'

PR

https://gist.github.com/yutokyokutyo/a3d34d9d941dcdbdf1ce

備考

英単語

yutokyokutyo commented 9 years ago

Ops研修(12月16日)

Chapter 7: Puppet を導入する

rbenv の環境変数を設定する

HOME の環境変数が指定されていなかった

rbenv についての環境変数をpathで指定したつもりだったのに、なんで command not found になってしまうのだろう。

==> default: Error: /home/vagrant/.bash_profile: line 4: rbenv: command not found
==> default: sh: rbenv: command not found
==> default:
==> default: Error: /Stage[main]/Main/Exec[install ruby]/returns: change from notrun to 0 failed: /home/vagrant/.bash_profile: line 4: rbenv: command not found
==> default: sh: rbenv: command not found
==> default:
==> default: Notice: Finished catalog run in 0.39 seconds

HOMEの環境変数が指定されていなかったことが原因だった。

command のクオートの位置が間違っていた

でもまだ rbenv が command not found になる。

    command     => "bash -c 'source /home/vagrant/.bash_profilei' ; env > /tmp/env ; rbenv install 2.1.5",

クオートの位置が間違っていた! 上のコードで書いていたのですが、この場合だと sourceenvrbenv のプロセスが違うものになってしまうのであった。 bashという親プロセスから子プロセスをはやして実行していることを忘れておりました。

    command     => "bash -c 'source /home/vagrant/.bash_profile ; env > /tmp/env ; rbenv install 2.1.5'",

ということで、修正してみたらrubyをインストールすることができました!

==> default: Notice: Compiled catalog for localhost in environment production in 0.40 seconds
==> default: Info: Applying configuration version '1418704433'
==> default: Notice: /Stage[main]/Main/Exec[install ruby]/returns: executed successfully
==> default: Notice: Finished catalog run in 218.26 seconds

bundler をインストールする

おふ。。今度はgemのpathが通ってなさそう。

==> default: Error: Could not find command 'gem'
==> default: Error: /Stage[main]/Main/Exec[install bundler]/returns: change from notrun to 0 failed: Could not find command 'gem'

http://pocketstudio.jp/linux/?%A5%D1%A5%B9%28PATH%29%A4%CE%B3%CE%C7%A7%A4%C8%C0%DF%C4%EA%CA%FD%CB%A1%A4%CF%A1%A9

  • bash_profile の中に$PATHも環境変数に含めるという設定がある。
  • ここに今回扱うコマンドたちpathが入っているので、これを環境変数に含めているのかぁ。
$ echo $PATH
/home/vagrant/.rbenv/shims:/home/vagrant/.rbenv/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/sbin:/usr/sbin:/home/vagrant/bin

iptables

テンプレートを使ったらあっさりできた。

allow_virtualについて

virtual packageとは

virtual resource

virtual resource はpuppetの機能。コンパイルもされないし、ないのにあるように仮想的に何か作ってしまうみたい。 本番とは乖離すべきもの。開発環境等テストとかで使うといいっぽい。

PR

https://gist.github.com/yutokyokutyo/a3d34d9d941dcdbdf1ce

今日でひととおりprovisioningができたました(まだvagrant up で一発で通らないので、依存関係の問題を修正する) 明日はコーディング規約に則り、コードを奇麗にしていこうと思います。その後にPRだします!

ペパボコーディング規約

http://pepabo.github.io/docs/puppet/style-guide.html

備考

yutokyokutyo commented 9 years ago

Ops研修(12月17日)

Chapter 7: Puppet を導入する

vagrant destroy => up をして何もない状態から provisioning をすると Worning がでる

==> default: Error: Working directory '/home/vagrant/Sample_app_on_VM' does not exist
==> default: Error: /Stage[main]/Main/Exec[install gem]/returns: change from notrun to 0 failed: Working directory '/home/vagrant/Sample_app_on_VM' does not exist

テストは通っていたが、gem がインストールされていない。bundle install されていないっぽい。

(テストはGemfileに、入れたいgemの文字列があるかどうかのテストとなっています)

[vagrant@localhost Sample_app_on_VM]$ bundle exec rails s
bundler: command not found: rails
Install missing gem executables with `bundle install`
# 必要な Gem を bundle install する
exec { 'install gem':
    user        => "vagrant",
    cwd         => "/home/vagrant/Sample_app_on_VM",
    environment => ['HOME=/home/vagrant'],
    command     => "bash -c 'source /home/vagrant/.bash_profile ; bundle install --without production --path vendor/bundle'",
    creates     => "/home/vagrant/Sample_app_on_VM/vendor/bundle",
}

よく表示されるエラー

==> default: Error: Could not parse for environment production: Syntax error at 'require'; expected '}' at /tmp/vagrant-puppet-3/manifests/init.pp:109 on node localhost
==> default: Error: Could not parse for environment production: Syntax error at 'require'; expected '}' at /tmp/vagrant-puppet-3/manifests/init.pp:109 on node localhost

大体末尾に,がついていないことが原因

この Worning は何だろう?

vagrant up 時のyum install 時に必ず表示されるこの Warning はなんなんだろう?

==> default: Warning: RPMDB altered outside of yum.

RPMDBというDBがあって、そこにはrpmの依存関係や、yumの依存関係の情報がキャッシュされている。 そこで、rpmとyumの依存関係の整合性がとれなくなってしまい、Warning がでている。

shell script の先頭にyum history syncを追加することで rpm/yum DB の再同期が行なわれるので解決できそう。

http://kometchtech.blog.fc2.com/blog-entry-1506.html

むむ!!まだWarningがでる!! yum clean all をしてみてもまだでる! vagrant で環境構築をする分には直接被害を被らないないので、この warning は今回は保留にすることに。

PR

一応一通りPRが完成したのでWIPを外しました。 どうかお手すきの際にレビューをよろしくお願いします!

https://github.com/yutokyokutyo/sampleapp_vm/pull/4

備考

yutokyokutyo commented 9 years ago

Ops研修(12月18日)

Chapter 7: Puppet を導入する

.bash_profile の中に書いてあった paeth をexecリソースのデフォルト値に全部突っ込んだらエラーがでてきた

==> default: Notice: /Stage[main]/Main/Exec[install ruby]/returns: rbenv: no such command `install'
==> default: Notice: /Stage[main]/Main/Exec[install ruby]/returns: rbenv: version `2.1.5' not installed
==> default: Error: rbenv install 2.1.5 ; rbenv global 2.1.5 returned 1 instead of one of [0]
==> default: Error: /Stage[main]/Main/Exec[install ruby]/returns: change from notrun to 0 failed: rbenv install 2.1.5 ; rbenv global 2.1.5 returned 1 instead of one of [0]
==> default: Notice: /Stage[main]/Main/Exec[install bundler]: Dependency Exec[install ruby] has failures: true
==> default: Warning: /Stage[main]/Main/Exec[install bundler]: Skipping because of failed dependencies
==> default: Notice: /Stage[main]/Main/Exec[install gem]: Dependency Exec[install ruby] has failures: true
==> default: Warning: /Stage[main]/Main/Exec[install gem]: Skipping because of failed dependencies
思案
原因と解決
if [ -z "${RBENV_ROOT}" ]; then
  RBENV_ROOT="${HOME}/.rbenv"
else
  RBENV_ROOT="${RBENV_ROOT%/}"
fi
export RBENV_ROOT

https://github.com/sstephenson/rbenv/blob/master/libexec/rbenv#L50-L55

tips

bundle install 時にもHOMEがないとエラーになってしまう!

==> default: Notice: /Stage[main]/Main/Exec[install bundler]/returns: executed successfully
==> default: Error: Could not find command 'bundle'
==> default: Error: /Stage[main]/Main/Exec[install gem]/returns: change from notrun to 0 failed: Could not find command 'bundle'
==> default: Info: Creating state file /var/lib/puppet/state/state.yaml

bundle install の方にもHOMEのpathをセットしなくてはいけないようです。 bundle を扱うためにはrbenvも扱わなくてはいけないからでした!そっか!

PR

https://github.com/yutokyokutyo/sampleapp_vm/pull/4

備考

yutokyokutyo commented 9 years ago

Ops研修(12月19日)

Chapter 7: Puppet を導入する

bundle install で gem が入らない。。

.bash_profile を source してくるやり方を試してみたところ、gem が入らなくなりました。

==> default: Error: Could not find command 'bundle'
==> default: Error: /Stage[main]/Main/Exec[install gem]/returns: change from notrun to 0 failed: Could not find command 'bundle'
==> default: Info: Creating state file /var/lib/puppet/state/state.yaml

今回logが少ない。。

実際にsshでvm上にはいって、bundle install を叩いてみた

capybaraのバージョンについてのお知らせ? でもこれは特にbundle install 失敗には繋がらないみたい。

It was installed into ./vendor/bundle
Post-install message from capybara:
IMPORTANT! Some of the defaults have changed in Capybara 2.1. If you're experiencing failures,
please revert to the old behaviour by setting:

    Capybara.configure do |config|
      config.match = :one
      config.exact_options = true
      config.ignore_hidden_elements = true
      config.visible_text_only = true
    end

If you're migrating from Capybara 1.x, try:

    Capybara.configure do |config|
      config.match = :prefer_exact
      config.ignore_hidden_elements = false
    end

Details here: http://www.elabs.se/blog/60-introducing-capybara-2-1

Post-install message from rdoc:
Depending on your version of ruby, you may need to install ruby rdoc/ri data:

<= 1.8.6 : unsupported
 = 1.8.7 : gem install rdoc-data; rdoc-data --install
 = 1.9.1 : gem install rdoc-data; rdoc-data --install
>= 1.9.2 : nothing to do! Yay!

原因と解決

$ which bundle
~/.rbenv/shims/bundle

今度はgem install bundler ができなくなった!

path に .rbenv/shims をを追加すると、今度はgem install bundler ができなくなりました!

==> default: Notice: /Stage[main]/Main/Exec[install bundler]/returns: ERROR:  While executing gem ... (Gem::FilePermissionError)
==> default: Notice: /Stage[main]/Main/Exec[install bundler]/returns:     You don't have write permissions into the /usr/lib/ruby/gems/1.8 directory.
==> default: Error: gem install bundler returned 1 instead of one of [0]
==> default: Error: /Stage[main]/Main/Exec[install bundler]/returns: change from notrun to 0 failed: gem install bundler returned 1 instead of one of [0]
==> default: Notice: /Stage[main]/Main/Exec[install gem]: Dependency Exec[install bundler] has failures: true
==> default: Warning: /Stage[main]/Main/Exec[install gem]: Skipping because of failed dependencies
==> default: Info: Creating state file /var/lib/puppet/state/state.yaml

どうやら、/usr/lib/ruby/gems/1.8 のディレクトリの permission が通らないらしい。。 そのディレクトリにいってみると、確かにpermissionがrootになってました。 でもなんでここにあるgemをみているのでしょう。。。 このディレクトリのgemの中には、edit_json.rb prettify_json.rbが入っていました。 ううむ。

which gem をしてみると以下のような感じ。。

$ which gem
~/.rbenv/shims/gem

むむ?このpathはさっき通したばかり。pathは良さそう。 問題は、なぜ usr/lib/ruby/gem/1.8 のディレクトリなんてみているかのかということ。

原因と解決

pathの優先順位は先頭から順に低くなっていく。にも関わらず、gemやbundleのpathをシステム系のものよりも後に書いていたため、システム系のgemのpathを優先させてしまったことが原因。 そのため、今まで引っ掛かったことのないpermissionエラーになってしまったようです。

sshでvm上にログインした後にenvで表示されるpathは、優先順位が環境構築する上で最適なものになっていたので、ここは問題ないと決めつけていました。もともとこのpathは、.bash_profile を source してできたpathであって、今回のリソースとは無関係なのでした。puppetってそういうものだった。

sshでログインした後のenv

PATH=/home/vagrant/.rbenv/shims:/home/vagrant/.rbenv/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/sbin:/usr/sbin:/home/vagrant/bin

解決策としては、pathを最適な順番に並び替えること。

テスト通りました!おk!

iptables の設定

notify も require も依存関係をつくるけど、どうちがうのだろう? と思って調べてみたら、require はインストールを基準にした依存関係作る君だということが分かった。

出典:http://takuya-1st.hatenablog.jp/entry/20120125/1327467007

入門puppetには、notify と subscribe は結果はどちらも同じなので、分かりやすい方を使うといいよと書いてあるのですが、今回はどっちの方が分かりやすいのだろう。。

puppet apply してみるとエラーがでてきた
==> default: Error: Could not start Service[restart iptables]: Execution of '/sbin/service restart iptables start' returned 1: restart iptables: unrecognized service
==> default: Wrapped exception:
==> default: Execution of '/sbin/service restart iptables start' returned 1: restart iptables: unrecognized service
==> default: Error: /Stage[main]/Main/Service[restart iptables]/ensure: change from stopped to running failed: Could not start Service[restart iptables]: Execution of '/sbin/service restart iptables start' returned 1: restart iptables: unrecognized service

service リソースでは、リソースタイプの名前?の部分を、指定したいサービス名にしなくてはいけないのでした。 service { 'restart iptables': からservice { 'iptables':に変更したところ、エラーが消えました。

PR

レビューの取り込みが一通りできました。この内容でマージしてもよろしいでしょうか?

https://github.com/yutokyokutyo/sampleapp_vm/pull/4