AWS CodeDeploy Agent をインストールする Recipe を書いてみた

2014.11.18

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

AWS CodeDeploy Agent

AWS CodeDeploy (以下 CodeDeploy) を使って EC2 インスタンスにアプリケーションをデプロイするには、対象となる EC2 インスタンスに AWS CodeDeploy Agent がインストールされている必要があります。つまり EC2 インスタンスを立てただけではデプロイできないということですね。

公式サンプルでは、AWS CodeDeploy Agent のインストールについて、ユーザーデータを使ってインストールする処理を含む CloudFormation を実行することで実現しています。これを参考に Cloud Formation を作っていくようにしても良いのですが、個人的に Chef を使ってインフラ環境構築を行っていたので、AWS CodeDeploy Agent をインストールする処理を Recipe 化してみました。

なお、CodeDeploy とは何か知りたいかたはこちらを参照してください。

Recipe を書いてみる

Chef の基本的な使いかたは割愛させていただきます。ということで早速本題です。まずは Cookbook を新規作成します。

$ bundle exec knife cookbook create codedeploy-agent -o site-cookbooks
** Creating cookbook codedeploy-agent
** Creating README for cookbook: codedeploy-agent
** Creating CHANGELOG for cookbook: codedeploy-agent
** Creating metadata for cookbook: codedeploy-agent

site-cookbooks/codedeploy-agent/recipes/default.rb を次のように編集します。

default.rb

execute 'copy' do
  command 'aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region us-east-1'
  cwd '/home/ec2-user'
end

file "/home/ec2-user/install" do
  owner 'root'
  group 'root'
  mode '0775'
  action :create
end

execute 'install' do
  command './install auto'
  user 'root'
  cwd '/home/ec2-user'
  action :run
end

あとは nodes/xxx.xxx.xxx.xxx.json で Recipe を読み込むように設定します。

xxx.xxx.xxx.xxx.json

{
  "run_list": [
    "recipe[codedeploy-agent]"
  ],
  "automatic": {
    "ipaddress": "xxx.xxx.xxx.xxx"
  }
}

以上で終わりです。

Cook してみる

Recipe が完成したところで Cook してみます。

$ bundle exec knife solo cook -i XXX.pem ec2-user@xxx.xxx.xxx.xxx
Running Chef on xxx.xxx.xxx.xxx...
Checking Chef version...
Installing Berkshelf cookbooks to 'cookbooks'...
Resolving cookbook dependencies...

... 中略 ...

Recipe: codedeploy-agent::default
  * execute[copy] action run
    - execute aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region us-east-1
  * file[/home/ec2-user/install] action create (up to date)
  * execute[install] action run
    - execute ./install auto

Running handlers:
Running handlers complete
Chef Client finished, 8/46 resources updated in 185.961159698 seconds

無事にインストールできました!

まとめ

複雑な処理は特になく、非常にシンプルな Recipe ですが、Recipe を書く勉強も兼ねて書いてみました。ぜひ参考にしていただければと思います。

参考