ラベル aws の投稿を表示しています。 すべての投稿を表示
ラベル aws の投稿を表示しています。 すべての投稿を表示

2015年3月13日金曜日

AWS CLIを使って OpsworksのSTACK_IDとAPP_IDを取得する

OpsWorksのSTACK_IDとAPP_IDの取得方法について下記します。
今回、値の取得にaws cliを使用しています。
aws cliの設定については、MacにAWS CLIをインストールする方法 をご参考ください。

Stack id 取得

aws cliから取得する場合は、describe-stacksを以下のように実行してください。

aws opsworks --region us-east-1 --profile myprj describe-stacks

–regionが東京(ap-northeast-1) かと思って頑張っていたけど、us-east-1を指定しないとダメらしい。

AWS - describe-stacks

※ は、OpsWorks IDと同じです。

app id 取得

aws cliから取得する場合は、describe-appsを以下のように実行してください。
には、前項で取得したSTACK_IDを指定してください。

aws opsworks --region us-east-1 describe-apps --stack-id <STACK_ID>

AWS - describe-apps

MacにAWS CLIをインストールする方法

pipのインストール

easy_installでpipをインストールします。

pipはphysonのパッケージ管理ソフト

以下を実行します。パスワードが求められるの合わせて入力します。

sudo easy_install pip
Password:

pipのインストールの確認

以下を実行して

pip -h

以下のようにUsageが出力されれば成功です。

Usage:
  pip <command> [options]

Commands:
  install                     Install packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  search                      Search PyPI for packages.
  wheel                       Build wheels from your requirements.
  zip                         DEPRECATED. Zip individual packages.
  unzip                       DEPRECATED. Unzip individual packages.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --isolated                  Run pip in an isolated mode, ignoring environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output.
  --log <path>                Path to a verbose appending log.
  --proxy <proxy>             Specify a proxy in the form [user:passwd@]proxy.server:port.
  --retries <retries>         Maximum number of retries each connection should attempt (default 5 times).
  --timeout <sec>             Set the socket timeout (default 15 seconds).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup.
  --trusted-host <hostname>   Mark this host as trusted, even though it does not have valid or any HTTPS.
  --cert <path>               Path to alternate CA bundle.
  --client-cert <path>        Path to SSL client certificate, a single file containing the private key and the certificate in PEM format.
  --cache-dir <dir>           Store the cache data in <dir>.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check

AWS CLIのインストール

上記でpipのインストールが完了したら、下記を実行します。
また、パスワードも聞かれるの再度入力してください。

sudo pip install awscli
Password:

AWS CLIのインストールの確認

以下を実行してみて

aws -h

以下のように usageが出力されればインストール完了です。

usage: aws [options] <command> <subcommand> [parameters]

設定の追加

以下を実行すると

aws configure

下記をきかれるの、順次入力していきます。

AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXX
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Default region name [None]: ap-northeast-1
Default output format [None]: json

AWS Access Key IDやAWS Secret Access Keyは各自に環境に合わせて入力してください。

動作確認

以下を実行して、結果がかえってくることを確認してください。

aws ec2 describe-instances

インスタンスの情報を取得

複数アカウント運用する場合

.aws/configを以下のように設定します。

[default]
output = json
region = ap-northeast-1

[profile myprj]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
region = ap-northeast-1

[profile myprj]以下を追加するアカウント情報を追記する。

動作確認

以下を実行して、結果がかえってくることを確認できれば成功です。

aws ec2 describe-instances --profile myprj 

2014年12月24日水曜日

AWS Elastic Beanstalkで作られたS3 のバケットを削除する方法

Elastic Beanstalkを使って、試しの環境を作成して、
使い終わったので、環境を管理コンソールから削除したらS3のバケットだけ残ってしまった。
しかも、手で削除しようとしたら、以下の”パーミッションがない”的なメッセージが出て削除できなかったため、なくなく調べました。

You don't have permissions to delete this bucket. You can check your bucket's permissions within bucket properties

バケットの [Permissions] > [ Edit bucket policy]を開いて以下のように修正。

"Effect": "Deny" => "Effect": "Allow"

設定を保存して、削除すると無事に削除できます。

2014年12月19日金曜日

EC2インスタンスからAMIを作成する

AWSでマシンイメージを生成する方法です。
簡単に作成できます。
サーバーのコピーやバックアップが簡単に行えます。

以下簡単ですが、作業の手順です。

AMIの作成

AMIを作成するEC2のインスタンスを選択して

[Action] > [Image] > [Create Image]

Create Imageダイアログ

下記の各項目を設定して、[Create Image]ボタンをクリック

Create Image

マシンのイメージ名 必須項目です。

以下のようにサーバー名と日付で主に名前を付けています。

sever-name_yyyy-mm-dd

Image description

マシンイメージの説明。任意項目です。

No reboot

サーバーを再起動させてたくない場合は、チェックを入れる。
チェックを入れないとリブートしてくれます。こちらの方がきれいにイメージがとれそうな気がします。

定期的なバックアップ用でAMIを作成する時などには、サーバーを動かしたまま、No rebootにチェックを入れて作成するには有効だと思います。
ただし、データが消えたりする事例もあるようなので、要注意です。
Qiita - No RebootでAMIを作成したらファイルが消えたりした

Instance Volumes

イメージ生成に含めるEBSを選択。

状況確認

AMIsから状況の作成状況の確認ができます。

statusがpendingからavailableに変わったら完成です。

2014年10月25日土曜日

AWS EC2のPostgresを9.2から9.3にバージョンアップする方法

EC2とRDSの環境でRailsのdb:migrateしたら、おこられました。
pg_dump:
server version: 9.3.3; pg_dump version: 9.2.9
pg_dump: aborting because of server version mismatch
rake aborted!
ほったらかしにしておいた環境なので、気がついたら、RDSだけPostgresのバージョンが上がっていました。
そのため、EC2側のPostgresを9.3にバージョンアップすることにしました。

インストールされているPostgresの確認

    rpm -qa | grep postgres
をすると、9.2系が入ってることが確認できます。
postgresql92-libs-9.2.9-1.46.amzn1.x86_64
postgresql92-9.2.9-1.46.amzn1.x86_64
postgresql92-devel-9.2.9-1.46.amzn1.x86_64

Postgres9.2のアンインストール

9.2を削除します。
削除方法は下記。
rpm -e postgresql92-libs-9.2.9-1.46.amzn1.x86_64 postgresql92-9.2.9-1.46.amzn1.x86_64 postgresql92-devel-9.2.9-1.46.amzn1.x86_64

Postgres9.3のインストール

yum list すると、Postgresの9.3系は、以下が入っていることが確認できます。
postgresql93.x86_64            
postgresql93-contrib.x86_64    
postgresql93-devel.x86_64      
postgresql93-docs.x86_64       
postgresql93-libs.i686         
postgresql93-libs.x86_64       
postgresql93-plperl.x86_64     
postgresql93-plpython.x86_64   
postgresql93-pltcl.x86_64      
postgresql93-server.x86_64
postgresql93-test.x86_64
この中から、必要なものをインストールしていきます。
それぞれの、パッケージは以下の通りです。
パッケージ名 主に格納しているもの
postgresql-libs libpqなどのPostgreSQLのライブラリ群。PostgreSQL以外のパッケージが必要とすることもあります。
postgresql psqlやpg_dumpなどのPostgreSQLのクライアントユーティリティ
postgresql-server initdbやpg_ctlなどのPostgreSQLのサーバユーティリティ。DBMSサーバとして必要な機能はこれに含まれています。
postgresql-contrib pgbenchやpg_statstatementなどのPostgreSQLのcontribモジュール。
postgresql-devel PostgreSQLのヘッダやpg_configなどの開発用モジュール。
postgresql-doc PostgreSQLのドキュメント。
postgresql-test PostgreSQLのリグレッションテスト用モジュール。

インストール

今回、以下のリポジトリをインストールしました。
yum install postgresql93.x86_64
yum install postgresql93-devel.x86_64
yum install postgresql93-server.x86_64

インストールの確認

rpm -qa | grep postgres
postgresql93-9.3.5-1.52.amzn1.x86_64
postgresql93-devel-9.3.5-1.52.amzn1.x86_64
postgresql93-libs-9.3.5-1.52.amzn1.x86_64

参考サイト

http://lets.postgresql.jp/documents/tutorial/yum/yum
http://d.hatena.ne.jp/kasahi/20070819/1187545636

2014年10月9日木曜日

RailsでCSVを生成して、そのままS3にアップロードする方法

夜間バッチなどで、定期的に外部システム用のCSVをAWSのS3にアップロードすることを想定しています。

作成方法

gemのインストール

まず、gemのインストール。
Gemfileに以下を追加。
# http://aws.amazon.com/sdkforruby/
# https://github.com/aws/aws-sdk-core-ruby
gem 'aws-sdk'
GitHubaws : aws-sdk-core-rubyはこちら。
以下を実行
bundle install

Railsへの実装

前提条件として、S3にbucketが作成済みの想定です。
      require 'csv'

      begin
        users = user.all

        data = CSV.generate do |csv|

          csv << ['id', '氏名']

          users.each do |user|
            raw = []
            raw << user.id
            raw << user.name
            csv << raw
          end
        end

        AWS.config(:access_key_id => 'your-access_key_id',
                   :secret_access_key => 'your-secret_access_key',
                   :region => 'your-bucket_region')

        s3 = AWS::S3.new
        bucket = s3.buckets['your-backet']

        file = data.sjisable.encode(Encoding::SJIS, {:invalid => :replace, :undef => :replace, :replace => '?'})
        file_name = "users.csv"
        file_full_path="user_data/#{file_name}"

        object = bucket.objects[file_full_path]
        object.write(file ,:acl => :public_read)

        puts '全ての処理に成功しました。'
      rescue => e
        puts "error occurred batch : #{Time.now} : #{e.message}"
      end
上記では、全Userのid と 氏名のカラムを持ったCSVを作成して、それを、S3にアップロードすることを想定しています。
途中こちらの部分でS3へのアクセスの設定を行っています。
 AWS.config(:access_key_id => 'your-access_key_id',
                   :secret_access_key => 'your-secret_access_key',
                   :region => 'your-bucket_region')
s3 = AWS::S3.new
bucket = s3.buckets['your-backet']
下記は適宜、自分の環境にあったものを設定してください。
  • your-access_key_id
  • your-secret_access_key
  • your-bucket_region
  • your-backet
頻繁にアクセスが発生する場合は、こちらconfig/initialyzerのしたaws.rb見たいのを作ってそちらで設定してしまってもよいかもしれません。
今回は、単発のバッチということなので、つどつど設定を行っています。

2014年9月23日火曜日

AWSのCloud Watchでディスク容量を監視する方法

awsのCloudWatchの管理画面の機能では、ec2のディスク容量を確認するUIが用意されていないようなので、自分でスクリプトを仕込んでCloudWatchにデータを送ってやる必要があります。
その設定方法は以下の通りです。

インストール方法

Amazon CloudWatch Monitoring Scriptsのインストール

/opt/aws配下にインスールを想定
cd /opt/aws
wget http://ec2-downloads.s3.amazonaws.com/cloudwatch-samples/CloudWatchMonitoringScripts-v1.1.0.zip
unzip CloudWatchMonitoringScripts-v1.1.0.zip
rm CloudWatchMonitoringScripts-v1.1.0.zip
cd aws-scripts-mon/

AWSのアクセスキーとシークレットキーの登録

awscredsに、AWSAccessKeyIdとAWSSecretKeyを設定します。
cp awscreds.template awscreds
vim awscreds

AWSAccessKeyId=xxxxxxxxxxxxx
AWSSecretKey=xxxxxxxxxxxxx

テスト用のコマンド実行

上記の設定が終わったら、下記のコマンドを実行してみる。
/dev/hoge のディスク容量を監視することを想定しており、適宜ディスクの場所は変更してください。
それから、以下のコマンドは実際にCloudWatchにはデータを送信されません。
あくまで、動作確認用になります
./mon-put-instance-data.pl --disk-space-util --disk-path=/dev/hoge --verify --verbose --aws-credential-file=/opt/aws/aws-scripts-mon/awscreds

–verif

メトリックスを収集するスクリプトのテストを実行し、完全な HTTP リクエストを準備します。ただし、実際に CloudWatch コールを実行して、データをレポートしません。また、このオプションは、認証情報が提供されているかどうかもチェックします。このオプションを冗長モードで実行すると、CloudWatch に送信されるメトリックスを出力します。

–verbose

スクリプトが実行する内容についての詳細情報を表示します。

–aws-credential-file=PATH

AWS 認証情報が格納されているファイルの場所を指定します。

cronに設定

上記コマンドが問題がなければ、cronに設定する。
crontab -e

*/5 * * * * /opt/aws/aws-scripts-mon/mon-put-instance-data.pl --disk-space-util --disk-path=/dev/hoge --aws-credential-file=/opt/aws/aws-scripts-mon/awscreds
これで、5分間隔で、cloudwatchにデータが収集されます。
送信されたMetricsは、Linux System > Filesystem,InstanceId,MountPathとして登録されます。
あとは、適宜アラートを設定して、監視に利用する。

cronが動作しているか確認する5つの項目

あれっ!?クーロン動いてるの?って思ったことは無いでしょうか?
そんなときは、以下の5点を確認してみてください。
  1. デーモンの確認
  2. サービス自動起動の設定の確認
  3. 実行権限の確認
  4. クーロンログの確認
  5. スクリプ自体のログを確認

1.デーモンの確認

下記のコマンドを実行して、クーロンのデーモンが実行中になっていることを確認
# /etc/rc.d/init.d/crond status 
crond (pid  1346) を実行中...

2.サービス自動起動の設定の確認

chkconfig –list crond
2~5までがonになっていることを確認
# chkconfig --list crond
crond           0:off   1:off   2:on    3:on    4:on    5:on    6:off

3.実行権限の確認

実行するファイルの実行権限が付いているか確認
# ls -al
-rwxr-xr-x 1 root root  9376  2月  9 10:39 2013 script.sh
もし、実行権限が付いていないようであれば、権限を変更する
# chmod 755 script.sh 

4.クーロンログの確認

クーロンログを確認する
# tail -100 /var/log/cron
以下のようなエラーが出ていたら
Sep 22 16:01:01 ip-10-0-4-29 crond[3465]: (root) FAILED to authorize user with PAM (Module is unknown)
クーロンを再起動で対処できるようです。
/etc/init.d/crond restart
or
sudo service cornd restart

5.スクリプ自体のログを確認

スクリプトのログを設定する

* * * * * /bin/sh /script.sh >>/var/log/script.log 2>>/var/log/script-error.log
/var/log/script.logに標準出力のログ、/var/log/script-error.logにエラーログが出力されるので、そのログを確認する。

statistics