awsebcliインストールから、ElasticBeanstalkをebコマンドで動かすまで

#■参考サイト
## ebコマンド準備
- [いつの間にかpipのインストールが楽になってた件 - Qiita](http://qiita.com/who_you_me/items/831d62f396e6d66dda66)
- [pip - Python入門](http://kaworu.jpn.org/python/pip#python_setup.py_egg_info)
- [Amazon Linux のPython をアップデートしてbotoをインストールします。 | ナレコムAWSレシピ](http://recipe.kc-cloud.jp/archives/4296)
- [Install the EB Command Line Interface (CLI) - AWS Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html?icmpid=docs_elasticbeanstalk_console)

## その他
- [AWSでジョブWorkerを構成するベストプラクティス 〜 Beanstalk worker tierの巻 ｜ Developers.IO](http://dev.classmethod.jp/cloud/aws/aws-job-worker-beanstalk/#note-1-2)
- [（超メモ）Elastic Beanstalk の Worker Tier について（cron っぽいことをやってみる） - ようへいの日々精進XP](http://inokara.hateblo.jp/entry/2015/11/29/230124)
- [Amazon Web Services ブログ: AWS Elastic Beanstalk - Ebを使ってコマンドラインから簡単操作!](http://aws.typepad.com/aws_japan/2012/06/aws-elastic-beanstalk-simplified-command-line-access-with-eb.html)
- [AWS Elastic BeanstalkがIAMRoleに対応したようです ｜ Developers.IO](http://dev.classmethod.jp/cloud/eb-iamrole/)
- [amazon web services - AWS Elastic Beanstalk ServiceRole Error When Logging In To A Role - Stack Overflow](http://stackoverflow.com/questions/31977441/aws-elastic-beanstalk-servicerole-error-when-logging-in-to-a-role)
- [2秒で設定！ AWS Elastic Beanstalk によるオートスケールアウトなサーバー構築｜DX.univ](http://dx.24-7.co.jp/beanstalk/)
- [ElasticBeanstalk .ebextensions 逆引き辞典 - Qiita](http://qiita.com/inouet/items/e8b39962c0de0f866531)
- [AWS Elastic Beanstalkで環境構築自動化 - Qiita](http://qiita.com/supertaihei02/items/b2373890b7e739ded318)
- [Amazon Web Services (AWS) users | New Relic Documentation](https://docs.newrelic.com/docs/accounts-partnerships/partnerships/partner-based-installation/amazon-web-services-aws-users)
- [Amazon ElasticBeanstalkインスタンスをNewRelicでモニタリングする - yustam.jp](http://yustam.hatenablog.com/entry/2014/04/09/142410)


#■実行した手順
## はじめに
###ローカルの環境だと、python2.7がyumから簡単にインストールできない環境っぽかったのであきらめました。
```bash
$ cat /etc/redhat-release 
CentOS release 6.4 (Final)
```

## 手順変更
###今のdev環境のEC2で試してみた
```bash
# pipがいるみたいなのでインストール、パイプ後にsudo入れなかったらエラーになった・・
$ curl -kL https://bootstrap.pypa.io/get-pip.py | sudo python

# インストール実行！けどエラーになっちゃった・・・
$ sudo pip install awsebcli
    error: invalid command 'egg_info'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-BsqCf2/awsebcli/

# 下記で解決するらしいので、実行！これも失敗するかと思ったけど、成功したみたい
$ sudo pip install --upgrade setuptools
....
Successfully installed setuptools-20.7.0

# 前に戻って、awsebcliのインストール
$ sudo pip install awsebcli
.....
Successfully installed awsebcli-3.7.5 backports.ssl-match-hostname-3.5.0.1 blessed-1.9.5 botocore-1.4.11 cement-2.8.2 colorama-0.3.7 docker-py-1.7.2 dockerpty-0.4.1 docopt-0.6.2 jmespath-0.9.0 pathspec-0.3.4 pyyaml-3.11 requests-2.9.1 semantic-version-2.5.0 texttable-0.8.4 wcwidth-0.1.6 websocket-client-0.37.0

# initしてみたけど、インスタンスにロールがなかった・・・orz
$ eb init -p PHP
ERROR: Elastic Beanstalk could not find any platforms. Ensure you have the necessary permissions to access Elastic Beanstalk.
```

## また手順変更
###別のEC2インスタンス(Amazon Linux)で試すが、またエラー・・・
```bash
# 上記の順番で pip と setuptools をインストールした後、awsebcli のインストールを試すと、、、、エラー・・・
$ sudo /usr/local/bin/pip install awsebcli
....
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  
  ----------------------------------------
  Failed building wheel for pyyaml
  Running setup.py clean for pyyaml
Failed to build pyyaml
    gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.7 -c ext/_yaml.c -o build/temp.linux-x86_64-2.7/ext/_yaml.o
    ext/_yaml.c:8:22: fatal error: pyconfig.h: そのようなファイルやディレクトリはありません
     #include "pyconfig.h"
                          ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    
    ----------------------------------------
  Rolling back uninstall of PyYAML
Command "/usr/bin/python27 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-OUqEgT/pyyaml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-4aVRaP-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-OUqEgT/pyyaml/
```

###困り果て、とりあえずEC2へ python2.7 をインストールする手段をググると、[参考サイトのURL](http://recipe.kc-cloud.jp/archives/4296)を発見し、その手順通り進める。
```bash
$ sudo yum install python27
読み込んだプラグイン:priorities, update-motd, upgrade-helper
amzn-main/latest                                                                                                             | 2.1 kB     00:00     
amzn-updates/latest                                                                                                          | 2.3 kB     00:00     
パッケージ python27-2.7.10-4.120.amzn1.x86_64 はインストール済みか最新バージョンです

#これをインストールしてなかった模様。。。orz
$ sudo yum install python27-devel
完了しました!
$ sudo rm /usr/bin/python
$ sudo ln -s /usr/bin/python2.7 /usr/bin/python
$ sudo cp /usr/bin/yum /usr/bin/_yum_old

#　ここは、URLの通りたたくとダメでした。
$ sudo sed -i s/python/python2.6/g /usr/bin/yum
$ python --version
Python 2.7.10

$ sudo curl -o /usr/local/src/ez_setup.py https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
$ cd /usr/local/src/
$ sudo python ez_setup.py 
$ which easy_install-2.7
/usr/local/bin/easy_install-2.7

$ sudo /usr/local/bin/easy_install-2.7 pip
Finished processing dependencies for pip

# ここもそのままではなかったようで、「pip」として上書きされているようでした。
$ which pip
/usr/local/bin/pip
$ sudo /usr/local/bin/pip install awsebcli
Successfully installed awsebcli-3.7.5 cement-2.8.2 colorama-0.3.7 docker-py-1.7.2 docopt-0.6.2 pathspec-0.3.4 pyyaml-3.11 semantic-version-2.5.0 texttable-0.8.4

#できたー！
$ eb --version
EB CLI 3.7.5 (Python 2.7.1)
```

###インストールができたので、早速作ってみる
```bash
$ eb init
Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : EU (Ireland)
5) eu-central-1 : EU (Frankfurt)
6) ap-southeast-1 : Asia Pacific (Singapore)
7) ap-southeast-2 : Asia Pacific (Sydney)
8) ap-northeast-1 : Asia Pacific (Tokyo)
9) ap-northeast-2 : Asia Pacific (Seoul)
10) sa-east-1 : South America (Sao Paulo)
11) cn-north-1 : China (Beijing)
(default is 3): 8 # Asia Pacific (Tokyo)を指定。

Select an application to use
1) 初めての Elastic Beanstalk アプリケーション
2) [ Create new Application ]
(default is 2): 2　# 新規で作成

Enter Application Name
(default is "ec2-user"): dev-XXXXX-XXXXX-worker　# Worker tierを使ってみた。
Application dev-XXXXX-XXXXX-worker has been created.

Select a platform.
1) Node.js
2) PHP
3) Python
4) Ruby
5) Tomcat
6) IIS
7) Docker
8) Multi-container Docker
9) GlassFish
10) Go
11) Java
(default is 1): 2　# PHPなので。

Select a platform version.
1) PHP 5.4
2) PHP 5.5
3) PHP 5.6
4) PHP 5.3
(default is 1): 1　# 5.4を選択
Do you want to set up SSH for your instances?　#　SSHのセットアップをするか
(y/n): y

Select a keypair.
1) XXXXXdev
2) XXXXXproxy
3) [ Create new KeyPair ]
(default is 3): 1　# とりあえず既存のものを使う。

#　アプリケーションを作成　プロファイルを指定して、ロールを設定。
$ eb create --tier worker --instance_profile aws-elasticbeanstalk-ec2-role
Enter Environment Name
(default is dev-XXXXX-XXXXX-XXXXX): 
Creating application version archive "app-XXXXX_XXXXX".
Uploading dev-XXXXX-XXXXX-XXXXX/app-XXXXX_XXXXX.zip to S3. This may take a while.
Upload Complete.
Environment details for: dev-XXXXX-XXXXX-XXXXX
  Application name: dev-XXXXX-XXXXX-XXXXX
  Region: ap-northeast-1
  Deployed Version: app-XXXXX_XXXXX
  Environment ID: e-XXXXX
  Platform: 64bit Amazon Linux 2016.03 vX.X.X running PHP 5.4
  Tier: Worker-SQS/HTTP
  CNAME: UNKNOWN
  Updated: 2016-XX-XX XX:XX:XX.XXXXXX+00:00
Printing Status:
INFO: createEnvironment is starting.
INFO: Using elasticbeanstalk-ap-northeast-1-XXXXXXXXX as Amazon S3 storage bucket for environment data.
ERROR: Unable to assign role. Please verify that you have permission to pass this role: aws-elasticbeanstalk-service-role.
ERROR: Failed to launch environment.
                                
ERROR: Failed to launch environment.
# またエラー。。。。
```

### もろもろ試してみると、ebコマンドに設定したAPIキーを持つユーザの権限に ElasticBeanstalk の権限がなかったので、下記の権限を一旦付与。
* AWSElasticBeanstalkFullAccess

### もう一度実行
```bash
$ eb create --tier worker --instance_profile aws-elasticbeanstalk-ec2-role
Enter Environment Name
(default is dev-XXXXX-XXXXX-eb-0): 
Creating application version archive "app-XXXXX_XXXXX".
Uploading dev-XXXXX-XXXXX-eb/app-XXXXX_XXXXX.zip to S3. This may take a while.
Upload Complete.
Application dev-XXXXX-XXXXX-eb has been created.
Environment details for: dev-XXXXX-XXXXX-eb-0
  Application name: dev-XXXXX-XXXXX-eb
  Region: ap-northeast-1
  Deployed Version: app-XXXXX_XXXXX
  Environment ID: e-XXXXX
  Platform: 64bit Amazon Linux 2016.03 vX.X.X running PHP 5.4
  Tier: Worker-SQS/HTTP
  CNAME: UNKNOWN
  Updated: 2016-XX-XX XX:XX:XX.XXXX000+00:00
Printing Status:
INFO: createEnvironment is starting.
INFO: Using elasticbeanstalk-ap-northeast-1-XXXXXXXXX as Amazon S3 storage bucket for environment data.
INFO: Created security group named: awseb-e-XXXXXX-stack-AWSEBSecurityGroup-XXXXXXXXXX
INFO: Created Auto Scaling launch configuration named: awseb-e-XXXXXXXX-stack-AWSEBAutoScalingLaunchConfiguration-XXXXXXXXXXXX
INFO: Environment health has transitioned to Pending. Initialization in progress (running for 25 seconds). There are no instances.
INFO: Created Auto Scaling group named: awseb-e-XXXXXXXX-stack-AWSEBAutoScalingGroup-XXXXXXXXXXXX
INFO: Waiting for EC2 instances to launch. This may take a few minutes.
INFO: Added instance [i-XXXXXXXXXX] to your environment.
# キターーーーーーーーー！

# 下記コマンドで作成状況が確認できるとのこと
$ eb status
Environment details for: dev-XXXXX-XXXXX-eb-0
  Application name: dev-XXXXX-XXXXX-eb
  Region: ap-northeast-1
  Deployed Version: None
  Environment ID: e-XXXXXXXXXX
  Platform: 64bit Amazon Linux 2016.03 vX.X.X running PHP 5.4
  Tier: Worker-SQS/HTTP
  CNAME: UNKNOWN
  Updated: 2016-XX-XX XX:XX:XX.XXXXXX+00:00
  Status: Launching
  Health: Grey　　　　←　まだGreyなので、未完成。Greenになるので、待つ。

# 出来た！！！！
$ eb status
Environment details for: dev-XXXXX-XXXXX-eb-0
  Application name: dev-XXXXX-XXXXX-eb
  Region: ap-northeast-1
  Deployed Version: None
  Environment ID: e-XXXXXXXXXX
  Platform: 64bit Amazon Linux 2016.03 vX.X.X running PHP 5.4
  Tier: Worker-SQS/HTTP
  CNAME: UNKNOWN
  Updated: 2016-XX-XX XX:XX:XX.XXXXXX+00:00
  Status: Ready
  Health: Green

# 出来たら、下記コマンドでSSHできるらしい。
$ eb ssh
INFO: Attempting to open port 22.
INFO: SSH port 22 open.
The authenticity of host 'XXX.XXX.XXX.XXX (XXX.XXX.XXX.XXX)' can't be established.
ECDSA key fingerprint is XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'XXX.XXX.XXX.XXX' (ECDSA) to the list of known hosts.
 _____ _           _   _      ____                       _        _ _
| ____| | __ _ ___| |_(_) ___| __ )  ___  __ _ _ __  ___| |_ __ _| | | __
|  _| | |/ _` / __| __| |/ __|  _ \ / _ \/ _` | '_ \/ __| __/ _` | | |/ /
| |___| | (_| \__ \ |_| | (__| |_) |  __/ (_| | | | \__ \ || (_| | |   <
|_____|_|\__,_|___/\__|_|\___|____/ \___|\__,_|_| |_|___/\__\__,_|_|_|\_\
                                       Amazon Linux AMI

This EC2 instance is managed by AWS Elastic Beanstalk. Changes made via SSH 
WILL BE LOST if the instance is replaced by auto-scaling. For more information 
on customizing your Elastic Beanstalk environment, see our documentation here: 
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html

$ 
```

#■まとめ
* 上記を見ると、ある程度すんなり進んだように見えますが、結構苦戦してしまいました。。。TT  ああ長かった・・・