TerraformのstateをS3でリモート管理する

Terraformの管理下にあるリソースの情報は tfstate ファイルに保存されている。たとえば、チームでこのtfstateを共有したいときにどうすべきかというのが課題になる。

tfstate ファイルをS3バケットに保存する(version >= 0.9.0)

Terraform 0.9.0 から terraform remote の変わりに Remote Backend になった。 - terraform/CHANGELOG.md at master · hashicorp/terraform · GitHub

❯ tf remote pull 
Local and remote state in sync

tfstate ファイルをS3バケットに保存する(version < 0.9.0)

S3バケットにこの状態ファイルを保存するのは簡単で、単に以下のコマンドで設定すれば良い。

terraform remote config \
  -backend=S3 \
  -backend-config="region=ap-northeast-1" \
  -backend-config="bucket=<YOUR_STATE_BUCKET_NAEM>" \
  -backend-config="key=<STATE_PATH>/<STATE_FILE_NAME>.tfstate"

この設定を行った後にpushする。

terraform remote push

以下のコマンドを実行すればpushしたファイルが一覧されるはず。

aws s3 ls s3://<YOUR_STATE_BUCKET_NAME> --recursive

ローカルにリモートのステートを持ってくるにはpullを実行する。

terraform remote pull

また、

terraform remote config -disable

でリモート管理をやめ、ローカルに戻せるらしい。

References

Alfred 3 のテーマ

先日、Alfred 3がリリースされた。パワーパックは2で購入していたので £12 でアップグレードできる。 とはいえ、2で満足できてたし1,600円払ってまでアップグレードするほどの目玉機能入ったの?? 早くなった?ワークフローが強くなった?いやー、2で十分でしょと思っていた。

でも、即アップグレードすることになった。

2で唯一困っていたことは「テーマのフォントが好きなフォントに変更できない」ということ。 不満に思っている人も多いらしく、海外の掲示板でもイロイロ議論されていた。

しかし、今回3ではこのフォント変更が可能になったことに加え、Blurエフェクトをつけることが可能になった。 この機能追加を見た途端、アップグレードするしかないと思い立ち £12 の支払いをPayPalにて完了した。

幾つかテーマを作って公開しようとしたが、公式(?)に投稿するテーマには制限があり「Standard Fonts」を使ったものしか投稿できない仕様になっているようだ(そんな気はしてた)。

To share themes on alfredapp.com, your theme needs to use fonts from the 'Standard Fonts' section in the font popup menu. These fonts will work in Alfred on every standard Mac configuration.

最終的にはGitHubにアップロードした。

作ったテーマは以下の3つ。

f:id:ringo6119:20161003001843p:plain

f:id:ringo6119:20161003001849p:plain

f:id:ringo6119:20161003001856p:plain

やっぱ、細いフォント綺麗だね。Retinaあってこそだけど。

よかったらどうぞ(Hiragino Sans 使ってます)。

沖縄の岩場 読谷ボルダーと瀬底ボルダー

ぼくは、趣味であるスキューバダイビングをするため、年に一度くらいのペースで沖縄に行く。 さらに、もう一つの趣味であるボルダリングもついでにやろうと思い登れる岩場を調査した。調べてみると、あまり多くの情報は無く(あっても古く)トポなどは存在しなかった。 沖縄のボルダーを登る人は少ないかもしれないが、探している人のためにメモを書いておこうと思う。今回は名護に滞在したため、読谷と瀬底ボルダーに行った(前回は具志頭に行った)。

トポについて

以前はコーラルロックというところでトポが販売されていた模様。「ぶり」(具志頭ボルダーのトポ)も「Coral on the beach 沖縄ボルダリング課題集」(沖縄本島のトポ)も販売していないようだ。

前回沖縄に訪れたときは、具志頭ボルダーに行ったときに地元のボルダーの方がトポ(ぶり)を持っていたので観せてくれて大変助かった。トポを持っていない状態ではYoutubeの動画を観ながらラインや岩を探すしかないのが現状。

少しでも参考になるように(自分で忘れないために)、場所だけメモしておく。 また、余裕があったら写真も撮ってきたので何処かにメモ用のトポをアップロードしようと思う。

トポ情報お待ちしております(切実)。

岩質

岩は琉球石灰岩という沖縄特有のもので、登ると凄い痛い。岩肌が鋭利なうえ、課題はバルジやルーフが多くとにかく痛い。テーピングが必須とされる。親指以外の指の腹に細いテーピングを巻きつけるとよい。膝とかをぶつけるとすぐ血が出るので注意。

読谷ボルダー

ホテル日航アリビラ」の隣(?)のビーチにある「アリビラボルダー」と、近くにある「体験王国むら咲むら」の「むら咲むらビーチ」の隣りにある「熟女岩」からなるボルダーで、今回はアリビラボルダーしか行けなかった。

最初は、それっぽい岩がありすぎて、どの岩が「それ」なのか全く分からず30分くらいマットを背負って浜辺を歩き回った。

f:id:ringo6119:20160929123113p:plain f:id:ringo6119:20160929123123p:plain

それっぽいのが見つかったのがこれ。おそらく右側がアリビラボルダーで、左側もなんだか少し登った形跡がある。

f:id:ringo6119:20160920143534j:plain

右側の岩は、写真右上のヤシの木(?)と、左下の三角形のように黒く飛び出している岩の形が特徴だと思う。あと、濡れてる。

f:id:ringo6119:20160920144518j:plain

下地は岩がむき出しだったが、平らだったのでブルーシートとマットを敷いた。 正直課題はどこになにがあるかよくわからなかったので、適当に登ってYoutubeにあった動画から「無名4級」を登った。他にも初段とか熟女岩の方も挑戦したかったが、この後名護まで行かなければならず、時間がなくて撤退。

f:id:ringo6119:20160929122931p:plain

地図はこんな感じ。

もっと、やりたかった。。。あと、トポがほしい。。

参考動画・サイト

瀬底ボルダー

ここもあまり情報は無かったので、Youtubeの動画をもとに岩を探してそれっぽいのを見つけた。この後、ヘリオス酒造の酒造見学があったので、滞在時間が30分しかなく悲しかった。酒造見学に行かずここで登っていたかったがドライバーがぼくしかいなかったので断念(そして、見学に行ってもドライバーなので飲めない)。

瀬底ビーチの駐車場(1,000円)に車を停め5分くらい浜辺を北に歩く。どれも登れそうで、時間があれば課題とか気にせず登ってみたかった。

こういうルーフとかがたくさんあった。

f:id:ringo6119:20160922091033j:plain

すると、動画に写っているっぽい岩が見つかった。写真右側の手前に写っている、ふたコブの岩がそうだと思う。水の流れたような黒い跡や、左奥に写っているヤシの木の生えた岩が目印。

f:id:ringo6119:20160922092033j:plain

ところが動画を見てみると、スタートはもっと下からしているようにみえる。どうやら砂で1mほど埋まってしまっている模様。仕方ないので出来るところからスタートして登れるところまで登った。動画も一つしか見つからず、時間もないのですぐ撤退。

地図はこんな感じ。

参考動画

まとめ

今回は、名護周辺のボルダーを回った。まだ、北側や東側のボルダーは行ったことがないので調査して行ってみたい。具志頭も行きたかったが真逆だったため断念。岩場の規模としては具志頭ボルダーが一番大きいようだ。

課題が設定されていない場所(そもそもトポがないからよくわからないが)じゃなくても登って楽しめる岩がたくさんあるのでまた行きたい。あとチョークは一応持っていったけど全く使わなかった。ゴミは残さないように。

最後に、沖縄ボルダリングマップを置いておきます。

参考文献

Terraform に入門してみる

Terraformを使うのでとりあえず入門記事を漁って見る。

とりあえず、 Terraform簡易チュートリアル on AWS - Qiita をハンズオンしてみる。

事前準備

AWS アクセスキーの発行

公式ドキュメントを参照(アクセスキー ID と秘密アクセスキーの取得 )して、アクセスキーとシークレットアクセスキーを発行する。

また、 aws-cli をインストールして aws configure を実行しておく。

Terraformのインストール

OSXなのでhomebrewを使ってインストール

brew update && brew install terraform

インストール出来た。

$ terraform -v
Terraform v0.6.14

Your version of Terraform is out of date! The latest version
is 0.6.15. You can update by downloading from www.terraform.io

AWSにEC2インスタンスを立ててみる

Terraform の設定ファイルを書く

「Terraform」の設定ファイルは「JSON」か「HCL」のどちらかで記述できる。 JSON の場合は *.tf.json 、 HCL の場合は *.tf という拡張子をつける。 HCL は「HashiCorp Configuration Language」の略で、設定ファイルを記述するために HashiCorp が独自に設計したシンタックスJSON と比較して可読性がよいらしい(いちいち{}でくくらなくてもよいのもメリット)。

とりあえず、 git init して書き始めよう。

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_instance" "hello-aws" {
  ami = "ami-a21529cc"
  instance_type = "t2.micro"
}

この、 provider とか resource をブロックを呼ぶらしい。

まず、 provider を記述する。今回は AWS に構築をしてみるので aws を指定指定する。 プロバイダの一覧は公式ドキュメント参照access_keysecret_keyaws configure で設定していない場合はここで記述する。 reagion には対象のリージョンを指定する(リージョンとアベイラビリティーゾーン)。東京は ap-northeast-1 なので、これを指定。

resource ブロックは引数を二つとり、第一引数に「作成するリソースのタイプ」を、第二引数に「リソース名」を指定する。プロバイダが AWS の場合に指定できるリソースは公式ドキュメント参照(AWS PROVIDER)。 とりあえずチュートリアルに習って、 EC2 のインスタンスを作成してみる。

リソースブロックの第一引数に aws_instance 、第二引数の名前に hello-aws を記述(AWS: aws_instance - Terraform by HashiCorp)。

ドキュメントをみると、この aws_instance には必須項目が二つある。

AMI はなんとなく ami-a21529ccUbuntu (無料枠の対象)を指定してみる。 インスタンスタイプは t2.nano が一番安いんだけど、無料枠の対象の t2.micro を指定。

インスタンスを起動する

plan で Dry Run してみる

terraform のサブコマンドに plan というのがある。このコマンドを実行することにより、どのような変更が適用されるか事前に確認することができる。

terraform plan
Refreshing Terraform state prior to plan...


The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

+ aws_instance.hello-aws
    ami:                      "" => "ami-a21529cc"
    availability_zone:        "" => "<computed>"
    ebs_block_device.#:       "" => "<computed>"
    ephemeral_block_device.#: "" => "<computed>"
    instance_state:           "" => "<computed>"
    instance_type:            "" => "t2.micro"
    key_name:                 "" => "<computed>"
    placement_group:          "" => "<computed>"
    private_dns:              "" => "<computed>"
    private_ip:               "" => "<computed>"
    public_dns:               "" => "<computed>"
    public_ip:                "" => "<computed>"
    root_block_device.#:      "" => "<computed>"
    security_groups.#:        "" => "<computed>"
    source_dest_check:        "" => "1"
    subnet_id:                "" => "<computed>"
    tenancy:                  "" => "<computed>"
    vpc_security_group_ids.#: "" => "<computed>"


Plan: 1 to add, 0 to change, 0 to destroy.

Note が表示された。

Note: You didn’t specify an “-out” parameter to save this plan, so when “apply” is called, Terraform can’t guarantee this is what will execute.

これは、「 out パラメータを指定してプランを保存しなかったら、 apply 呼ばれた時に何を実行するか保証できないよ!」ってことだと思う。多分、 plan した後に別の人が別のところで apply した場合は、今回行った plan は意味なくなるから気をつけろよってことだと思う。

あとで、実験しよう。

あと、 terraform.tfstate というファイルが作成される。これは、 Terraform が管理しているリソースを JSON で保存しておくファイルらしい。 いまは、何も適用してないから空っぽいファイルができてるね。

{
    "version": 1,
    "serial": 0,
    "modules": [
        {
            "path": [
                "root"
            ],
            "outputs": {},
            "resources": {}
        }
    ]
}

apply で適用する

apply のサブコマンドを実行すると、 *.tf ファイルの記述に従って処理が適用される。

$ terraform apply
aws_instance.hello-aws: Creating...
  ami:                      "" => "ami-a21529cc"
  availability_zone:        "" => "<computed>"
  ebs_block_device.#:       "" => "<computed>"
  ephemeral_block_device.#: "" => "<computed>"
  instance_state:           "" => "<computed>"
  instance_type:            "" => "t2.micro"
  key_name:                 "" => "<computed>"
  placement_group:          "" => "<computed>"
  private_dns:              "" => "<computed>"
  private_ip:               "" => "<computed>"
  public_dns:               "" => "<computed>"
  public_ip:                "" => "<computed>"
  root_block_device.#:      "" => "<computed>"
  security_groups.#:        "" => "<computed>"
  source_dest_check:        "" => "1"
  subnet_id:                "" => "<computed>"
  tenancy:                  "" => "<computed>"
  vpc_security_group_ids.#: "" => "<computed>"
aws_instance.hello-aws: Creation complete

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate

作成されたっぽい。 computed の部分は特になにも指定してないので動的に作成される(っぽい)。 インスタンスの詳細を見るには show を使えって書いてあるので実行してみる。

$ terraform show
aws_instance.hello-aws:
  id = i-4a10aed5
  ami = ami-a21529cc
  availability_zone = ap-northeast-1a
  ebs_block_device.# = 0
  ebs_optimized = false
  ephemeral_block_device.# = 0
  iam_instance_profile =
  instance_state = running
  instance_type = t2.micro
  key_name =
  monitoring = false
  private_dns = ip-172-31-4-134.ap-northeast-1.compute.internal
  private_ip = 172.31.4.134
  public_dns = ec2-52-192-1-94.ap-northeast-1.compute.amazonaws.com
  public_ip = 52.192.1.94
  root_block_device.# = 1
  root_block_device.0.delete_on_termination = true
  root_block_device.0.iops = 24
  root_block_device.0.volume_size = 8
  root_block_device.0.volume_type = gp2
  security_groups.# = 0
  source_dest_check = true
  subnet_id = subnet-8b78affc
  tags.# = 0
  tenancy = default
  vpc_security_group_ids.# = 1
  vpc_security_group_ids.1967208828 = sg-9257fef7

なんかイロイロ表示されましたね。 ちゃんと起動してるかチェック。

$ aws ec2 describe-instances --instance-ids "i-4a10aed5" | jq '.Reservations[].Instances[] | {"Image ID": .ImageId, "Instance ID": .InstanceId, "Status": .State.Name}'
{
  "Image ID": "ami-a21529cc",
  "Instance ID": "i-4a10aed5",
  "Status": "running"
}

起動してるっぽい。

インスタンスを変更する

ためにしに、 AMI を Ubuntu から Amazon Linux に変更してみる。

diff --git hello-aws.tf hello-aws.tf
index cbe294a..62aeca0 100644
--- hello-aws.tf
+++ hello-aws.tf
@@ -3,6 +3,6 @@ provider "aws" {
 }

 resource "aws_instance" "hello-aws" {
-  ami = "ami-a21529cc"
+  ami = "ami-f80e0596"
   instance_type = "t2.micro"
 }

terraform plan を実行。

Refreshing Terraform state prior to plan...

aws_instance.hello-aws: Refreshing state... (ID: i-4a10aed5)

The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

-/+ aws_instance.hello-aws
    ami:                      "ami-a21529cc" => "ami-f80e0596" (forces new resource)
    availability_zone:        "ap-northeast-1a" => "<computed>"
    ebs_block_device.#:       "0" => "<computed>"
    ephemeral_block_device.#: "0" => "<computed>"
    instance_state:           "running" => "<computed>"
    instance_type:            "t2.micro" => "t2.micro"
    key_name:                 "" => "<computed>"
    placement_group:          "" => "<computed>"
    private_dns:              "ip-172-31-4-134.ap-northeast-1.compute.internal" => "<computed>"
    private_ip:               "172.31.4.134" => "<computed>"
    public_dns:               "ec2-52-192-1-94.ap-northeast-1.compute.amazonaws.com" => "<computed>"
    public_ip:                "52.192.1.94" => "<computed>"
    root_block_device.#:      "1" => "<computed>"
    security_groups.#:        "0" => "<computed>"
    source_dest_check:        "true" => "1"
    subnet_id:                "subnet-8b78affc" => "<computed>"
    tenancy:                  "default" => "<computed>"
    vpc_security_group_ids.#: "1" => "<computed>"


Plan: 1 to add, 0 to change, 1 to destroy.

新しいリソースを作るみたいな表示になってる。

ami: "ami-a21529cc" => "ami-f80e0596" (forces new resource) Plan: 1 to add, 0 to change, 1 to destroy.

terraform apply を実行。

aws_instance.hello-aws: Refreshing state... (ID: i-4a10aed5)
aws_instance.hello-aws: Destroying...
aws_instance.hello-aws: Destruction complete
aws_instance.hello-aws: Creating...
  ami:                      "" => "ami-f80e0596"
  availability_zone:        "" => "<computed>"
  ebs_block_device.#:       "" => "<computed>"
  ephemeral_block_device.#: "" => "<computed>"
  instance_state:           "" => "<computed>"
  instance_type:            "" => "t2.micro"
  key_name:                 "" => "<computed>"
  placement_group:          "" => "<computed>"
  private_dns:              "" => "<computed>"
  private_ip:               "" => "<computed>"
  public_dns:               "" => "<computed>"
  public_ip:                "" => "<computed>"
  root_block_device.#:      "" => "<computed>"
  security_groups.#:        "" => "<computed>"
  source_dest_check:        "" => "1"
  subnet_id:                "" => "<computed>"
  tenancy:                  "" => "<computed>"
  vpc_security_group_ids.#: "" => "<computed>"
aws_instance.hello-aws: Creation complete

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate

確認してみる。

$ terraform show | grep " id ="
  id = i-1cd06883
$ aws ec2 describe-instances --instance-ids "i-4a10aed5" "i-1cd06883" | jq '.Reservations[].Instances[] | {"Image ID": .ImageId, "Instance ID": .InstanceId, "Status": .State.Name}'
{
  "Image ID": "ami-a21529cc",
  "Instance ID": "i-4a10aed5",
  "Status": "terminated"
}
{
  "Image ID": "ami-f80e0596",
  "Instance ID": "i-1cd06883",
  "Status": "running"
}

古い方は terminated になってるし、新しい方は違う AMI ID で running になってる。

インスタンスの削除

インスタンスの削除は plan-destroy オプションをつけてプランファイルを作成し、 apply 実行時にプランファイルを指定して実行する。

プランファイルを作成して。

$ terraform plan -destroy -out=destroy.tfplan
efreshing Terraform state prior to plan...

aws_instance.hello-aws: Refreshing state... (ID: i-1cd06883)

The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Your plan was also saved to the path below. Call the "apply" subcommand
with this plan file and Terraform will exactly execute this execution
plan.

Path: destroy.tfplan

- aws_instance.hello-aws


Plan: 0 to add, 0 to change, 1 to destroy.

削除。

$ terraform apply ./destroy.tfplan
aws_instance.hello-aws: Destroying...
aws_instance.hello-aws: Destruction complete

Apply complete! Resources: 0 added, 0 changed, 1 destroyed.

確認してみると両方とも terminated になってた。

$ aws ec2 describe-instances --instance-ids "i-4a10aed5" "i-1cd06883" | jq '.Reservations[].Instances[] | {"Image ID": .ImageId, "Instance ID": .InstanceId, "Status": .State.Name}'
{
  "Image ID": "ami-a21529cc",
  "Instance ID": "i-4a10aed5",
  "Status": "terminated"
}
{
  "Image ID": "ami-f80e0596",
  "Instance ID": "i-1cd06883",
  "Status": "terminated"
}

References

ES2015(ES6) でスクリプトを書ける Hubot 環境を作る

Hubotのスクリプトを書くとき、今更coffeeは辛いのでES2015(ES6)で運用できる環境を作りたくなりました。

STEP1: Hubotのスケルトンを作成する

まず、Hubotのスケルトンを作成します。公式ドキュメント がよいです。

本当は対話的に各項目を埋めていくんだけど、オプションで指定するとコマンド一発でいけます。サイコーですね。

npm install -g yo generator-hubot
mkdir aokibot && cd aokibot && \
  yo hubot \
    --owner="Yoshiki Aoki <yoshiki_aoki@example.com>" \
    --name="aokibot" \
    --description="Excellent working bot" \
    --adapter=slack

試しに実行するにはbin/hubotで起動します。

STEP2: ES2015の環境を整える

babelを使ってES2015で書いたコードをES5に変換します。 変換に必要なモジュールをnpmでインストール。それと、ES2015のソース用ディレクトリとビルド後のディレクトリを作成しておきます。

npm i --save-dev babel babel-cli babel-preset-es2015
mkdir src builds

STEP3: サンプルスクリプトを書いてみる

src/example.jsにES2015の文法を使って書いたサンプルスクリプトを追加します。

// Description:
//  Example scripts for you to examine and try out.
//
// Notes:
//  They are commented out by default, because most of them are pretty silly and
//  wouldn't be useful and amusing enough for day to day huboting.
//  Uncomment the ones you want to try and experiment with.
//
//  These are from the scripting documentation: https://github.com/github/hubot/blob/master/docs/scripting.md

module.exports = (robot => {
  robot.hear(/hello/i, res => {
    res.send("World!!");
  });
});

Hello World!!

STEP4: 起動設定をする

ビルドして起動してってあんまりゴチャゴチャさせたくないですよね。なので、トランスパイル、起動はnpm経由でやるのがスマートです。

package.jsonにビルドや起動の設定を追加します。

まず、run-scriptbuildを追加してトランスパイルを行います。

"build": "babel src --presets es2015 --out-dir ./builds"

そして、起動スクリプトにbin/hubotを指定します。この時、-rオプションでbuildsディレクトリを指定してやることによって、素の(?)スクリプトはscripts、ES2015からトランスパイルされたスクリプトはbuildsと住み分けることができます。

"start": "bin/hubot -r builds"

最後に起動するときはnpm run build && npm startとすれば起動します。 が、そんなダサい方法は使いたくありません。 npm startだけで終わらせたいので、prestartnpm run buildを指定してあげます。

"prestart": "npm run build"

トランスパイルしてから起動するコマンドはnpm startだけでよくなりました。スマートなのはいいですね。

最後に差分貼っておきます。

diff --git a/package.json b/package.json
index 71768eb..879620b 100644
--- a/package.json
+++ b/package.json
@@ -4,6 +4,11 @@
   "private": true,
   "author": "Yoshiki Aoki <yoshiki_aoki@example.com>",
   "description": "Excellent working bot",
+  "scripts": {
+    "build": "babel src --presets es2015 --out-dir ./builds",
+    "prestart": "npm run build",
+    "start": "bin/hubot -r builds"
+  },
   "dependencies": {
     "hubot": "2.18.0",
     "hubot-help": "0.1.3",

Problems

deprecated documentation syntax というINFOメッセージが出る

トランスパイル後のファイルには先頭に"use strict"がついている。 これが、原因で builds/example.js is using deprecated documentation syntax というメッセージが出てしまう。悪影響は全くないけども、解決する方法があるのであれば解決したいですね。

References

Amazon Fire TV Stick のリモコンを忘れた話

正月は実家に帰ってAmazon Fire TV Stick 海外ドラマ見てダラダラ過ごす他ほかないと計画し、TV Stick を忘れずにカバンに入れて安心しきっていた。いざ、ゴロゴロしようと思ったらリモコンを忘れていたことに気づいた*1

色々調べてみると、BRAVIA とかだとテレビのリモコンがそのまま使えるって書いてあったので、家にあった REGZA 37H3100 で試してみたが全然反応しなかった。もう一個小さいテレビ(REGZA 19A2)があったので、それで試すとちゃんとTVのリモコンでも反応して大勝利だった。

そいつでWi-Fiを設定したら、あとは、iPhoneAmazon Fire TV Remote を認証してiPhoneから操作することができた。

リモコンを忘れてもなんとかなるという知見が得られて非常によかった。 でも、やっぱりリモコンのほうがいいね。アプリめっちゃ操作し辛い。

References

*1:もちろんArduinoも忘れた

dockerがVPNのせいで繋がらなくなった時は面倒くさい

VPNとか繋いだりすると、詳しいことはよくわからないがdockerコマンドが返ってこないことがよくある。

そういう時は、次のコマンドを打つと直る。

boot2docker down
sudo route -nv delete -net 192.168.59 -interface vboxnet1
sudo route -nv add -net 192.168.59 -interface vboxnet1
boot2docker up

それも面倒くさいので、.zshrcに以下の様なエイリアスを付けてやると楽。

alias redock="boot2docker down && sudo route -nv delete -net 192.168.59 -interface vboxnet1 && sudo route -nv add -net 192.168.59 -interface vboxnet1 && boot2docker up"

redock を打つだけで再起動できる。

References

OSX docker のセットアップ

今更、書くことでもないが。 基本的に公式ドキュメント見ればいいと思う。

VertualBoxが必要なので、予めインストールしておくとよい。

インストール

インストールは homebrew でサックっと行う。

brew update
brew install boot2docker

OS起動時に起動設定するので、書いてある通り実行する。

To have launchd start boot2docker at login:
    ln -sfv /usr/local/opt/boot2docker/*.plist ~/Library/LaunchAgents
Then to load boot2docker now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.boot2docker.plist

環境変数の設定

今までは

export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=${HOME}/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1

を書いてたけど、

shellinitコマンドができてから、

eval "$(boot2docker shellinit)"

でよくなったみたい。

これだと、毎回シェル起動するたびに Writing ~/.boot2docker/certs/boot2docker-vm/ca.pem みたいに出てきてうざいので、少しアレンジして以下の行をrcなどに追加するとよい。

eval "$(boot2docker shellinit 2> /dev/null)"

ただ、毎回Writing~も実行されてるっぽくて気持ち悪い場合は、最初のexport形式に戻すことになる。

実験。

$ time (eval "$(boot2docker shellinit 2> /dev/null)")
( eval "$(boot2docker shellinit 2> /dev/null)"; )  0.05s user 0.04s system 38% cpu 0.244 total
$ time (export DOCKER_HOST=tcp://192.168.59.103:2376 && export DOCKER_CERT_PATH=${HOME}/.boot2docker/certs/boot2docker-vm && export DOCKER_TLS_VERIFY=1 )
( export DOCKER_HOST=tcp://192.168.59.103:2376 && export  && export ; )  0.00s user 0.00s system 61% cpu 0.001 total

exportのほうがいいね。

IntelliJ をターミナルから開く

これも、一年前くらいの下書きを放出。

sbt経由でIntelliJを起動する方法があったが、sbtの起動がおそいので辛い気持ちがあった。

d.hatena.ne.jp

もう、直接起動すれば良いのではないかということで、以下の関数を bashrc なり zshrc なりに追加する。

idea () {
  /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS/idea $(cd "${1}" && /bin/pwd)
}

すると、カレントディレクトリの場合は idea . 、対象のディレクトリにあるプロジェクトを開きたい場合は idea foo/bar とすれば起動できる。

相対パス絶対パスに変換してやらないと、ideaコマンドのあるディレクトリを元に起動してしまう。

octocatが居るとターミナルで文字がずれる

いつも使っている別のPCで、いろいろと環境を整えていた。 ところが、タブで補完しようとすると、今まで入力していたところが位置も自分ずれてしまう現象が発生した。

f:id:ringo6119:20150926122416g:plain

原因は、表示されているoctocatであることはすぐに確認できた。 文字幅が2つ分とられているが、そこら辺が原因でなにかおかしくなってるっぽい。 補完のタイミングでずれるので、zshのhook関数などを色々調べてみたがさっぱりわからなかった。

最終的にiTerm2のとあるオプションが原因だったことがわかった。 iTerm2のPreference > Profiles > Text > Double-Width CharactersTreat ambiguous-width characters as double widthにチェックが入っているとずれるらしい。

まさか、iTerm2だとは思わなかったけど解決できてよかった。

f:id:ringo6119:20150926122430p:plain

References

IntelliJでSpecs2をs2形式で書くと重い

ここに、同じ症状の方が居た。

やっても改善せず。

ついでに、なぜか一つめに赤線がひかれる。 MatcherResultがかえってるけど、Resultがほしいからエラーっぽい。 ただ、暗黙変換をしてくれてるっぽいのでテストは走る。 これも、telliJが重い原因になってるんじゃないかなぁとかおもう。 ちなみに、${e1: Result} とかtoResultとか書くと赤線はなおる。

Scientific Linux 7.0, 7.1 の Docker ベースイメージを作る

タイトルのまんまですが、ScientificLinux 7.0, 7.1用の Dockerベースイメージを作りました。 一年くらい前に6.5のものを使っ他やり方(Scientific LinuxのDockerイメージを作成する - リジェクトされました)でつくろうとしたらうまく行かなかったのでメモしておこうと思います。

まず、Scientific Linux 7.0/7.1 の VirtualBox イメージを準備しましたが、これはまた別の機会に書こうと思います。 ということで、VMのイメージはこれ(ringo | Atlas by HashiCorp )を使います。

作成したコンテナはこちら(Docker Hub )

Scientific Linux の Docker ベースイメージを作成

Vagrantfile を作成する

まず、ベースとなるVagrantfileを作成します。 特にかわったことはしていません。 vboxに ringo/scientific-linux-7.0 を指定しています。 このイメージを作成する元のスクリプトこちらです。 あと、 provisionbuild.sh を指定しています。

VAGRANTFILE_API_VERSION = '2'

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = 'ringo/scientific-linux-7.0'
  config.vm.network 'private_network', ip: '192.168.33.11'
  config.vm.provision :shell, :path => 'build.sh'
end

Build.sh を作成する

ここにDockerイメージを作成するメインの処理を書きます。 作成するためのコマンドは以前と異なり、 febootstrap コマンドに代わって supermin5 コマンドを使います。

普通に yum install -y supermin をしてしまうと1.4系が入ってしまうので注意。 --prepare オプションでインストールしておきたいパッケージを指定します。 今回は yum のみ。あとは、フォーマットに chroot を指定してビルドするだけ。

# Install supermin
yum update -y && yum install -y supermin5

# Build
supermin5 --prepare yum -o supermin.d && \
  supermin5 --build --format chroot supermin.d -o appliance.d

Locale や I18N を削除

ココらへんを削除するとコンテナのサイズが軽くなります(supermin - fedoraのDockerイメージを作成する - Qiita

# Remove locales
readonly LOCALE_DIR=${CMD_PATH}/appliance.d/usr/share/locale
mv ${LOCALE_DIR}/en ${LOCALE_DIR}/en_US /tmp && \
  rm -rf ${LOCALE_DIR}/* && \
  mv /tmp/en /tmp/en_US ${LOCALE_DIR}/

# Remove i18ns
readonly I18N_DIR=${CMD_PATH}/appliance.d/usr/share/i18n/locales
mv ${I18N_DIR}/en_US /tmp && \
  rm -rf ${I18N_DIR}/*  && \
  mv /tmp/en_US ${I18N_DIR}/

Tarball の作成

tar で固めて圧縮します。それだけ。

# Create tarball and compress
cd ${CMD_PATH}/appliance.d && tar --create . | xz --best > /vagrant/scientific-linux_${VERSION}_x86_64.tar.xz

コンテナを作成して Docker Hub にプッシュ

# Install the docker
curl -sSL https://get.docker.com/ | sh

# docker import and push
cat /vagrant/scientific-linux_${VERSION}_x86_64.tar.xz | docker import - ringo/scientific:${VERSION} && \
  docker push ringo/scientific:${VERSION}

yum update するとマイナーバージョンが上がってしまう

7.0をわざわざ入れる人は7.0を使いたいというモチベーションがあって入れるわけなので、lockしてあげたかったけど、 やり方がよくわからなかったので、最終的には yum 実行時に --releasever で指定することにした。

色々試した

/etc/yum/vars/releasever に色々書いてみて実験した。 7.0 と書いてみると、7.1 にアップグレードされた。 70 と書いてみると、やはり 7.1 にアップグレードされた。

/etc/yum/vars/slreleasever に色々書いてみて実験した。 7.0 と書いてみると、 /etc/yum/vars/releasever ができて 7 が書かれてた。 そのまま、もう一度 yum update したら 7.1 にあがる。 70 と書いてみると、エラーになってしまう。

他にもなにかやった気がするけど、忘れた。

References

VirtualBox で Scientific Linux 7.0 を起動しようとしたら Guest Additions のインストールに失敗

Scientific Linux 7.0 の Docker用ベースイメージをつくろうと思い、 vagrant up をしたらエラーが発生してうまく行かなかった。人生は厳しい。 おかげで、 /vagrant がマウントされなかった。

環境

$ vagrant --version
Vagrant 1.7.4
$ VBoxManage --version
4.3.28r100309

忙しい人のための

こんなエラーが出たら

The missing package can be probably installed with
yum install kernel-devel-3.10.0-123.el7.x86_64

Building the main Guest Additions module[FAILED]

こうする。

host $ vagrant ssh
vagrant # sudo yum install -y ftp://mirror.switch.ch/pool/4/mirror/scientificlinux/7.0/x86_64/os/Packages/kernel-devel-3.10.0-123.el7.x86_64.rpm
vagrant # exit
host $ vagrant reload

詳細

エラーは以下のような感じ。

Building the VirtualBox Guest Additions kernel modules
The headers for the current running kernel were not found. If the following
module compilation fails then this could be the reason.
The missing package can be probably installed with
yum install kernel-devel-3.10.0-123.el7.x86_64

Building the main Guest Additions module[FAILED]
(Look at /var/log/vboxadd-install.log to find out what went wrong)

...

An error occurred during installation of VirtualBox Guest Additions 4.3.28. Some functionality may not work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
==> default: Checking for guest additions in VM...
    default: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default:
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Configuring and enabling network interfaces...
==> default: Mounting shared folders...
    default: /vagrant => /Users/yoshiki_aoki/work/github.com/ringohub/docker-base-image/sl70-base
Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:

mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` vagrant /vagrant

The error output from the last command was:

/sbin/mount.vboxsf: mounting failed with the error: No such device

どうやら、virtual box guest additions のインストールが失敗してる模様。 気になるログはここらへん。

The missing package can be probably installed with
yum install kernel-devel-3.10.0-123.el7.x86_64

Building the main Guest Additions module[FAILED]
(Look at /var/log/vboxadd-install.log to find out what went wrong)

ここでわかるのは、kernel-devel-3.10.0-123.el7.x86_64 をインストールしなきゃいけなさそうっていうのと、/var/log/vboxadd-install.log のログを見ようってこと。

ログから見てみる。

[root@localhost ~]# cat /var/log/vboxadd-install.log
/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.

KERN_DIR を指定しろよって言ってる。カーネルのディレクトリをしてしようと思って、みてみる。

[root@localhost vagrant]# ls /usr/src/kernels/
[root@localhost vagrant]#

何もなかった。 ここで、yum install -y kernel-devel でインストールしてしまうと kernel-devel-3.10.0-123.el7.x86_64 が入らない。 なので、ここから rpmを指定バージョンをインストールした。

yum install -y ftp://mirror.switch.ch/pool/4/mirror/scientificlinux/7.0/x86_64/os/Packages/kernel-devel-3.10.0-123.el7.x86_64.rpm

一応確認。

[root@localhost vagrant]# ls /usr/src/kernels/
3.10.0-123.el7.x86_64

KERN_DIR を指定しなきゃだめかなと思ったんだけど、ためにしログアウトして vagrant reload したら無事インストールされた。

...
Installing Virtualbox Guest Additions 4.3.28 - guest version is
Verifying archive integrity... All good.
Uncompressing VirtualBox 4.3.28 Guest Additions for Linux............
VirtualBox Guest Additions installer
Removing installed version 4.3.28 of VirtualBox Guest Additions...
Copying additional installer modules ...
Installing additional modules ...
Removing existing VirtualBox non-DKMS kernel modules[  OK  ]
Building the VirtualBox Guest Additions kernel modules
Building the main Guest Additions module[  OK  ]
Building the shared folder support module[  OK  ]
Building the OpenGL support module[  OK  ]
Doing non-kernel setup of the Guest Additions[  OK  ]
Starting the VirtualBox Guest Additions [  OK  ]
...

References

nodebrew をアップデートしたら exec format error: nodebrew がでた

久しぶりにnodeを最新にあげようと思って、まずnodebrew self updateしたら exec format error: nodebrewがでてきて動かなくなってしまった。が、調べたらすぐ解決できた。よかった。

書いてあるとおり

curl -L http://git.io/nodebrew  | perl - selfupdate

を実行したら直った。

rbenv で ruby の環境を整える

忙しい人のためのまとめ

  1. インストール

    Macbrew install rbenv ruby-build でインストール。

     git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
     git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
     apt-get install -y autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev
    
  2. .bash/zshrc ファイルに追加。

     [[ -d ~/.rbenv  ]] && \
       export PATH=${HOME}/.rbenv/bin:${PATH} && \
       eval "$(rbenv init -)"
    
  3. rubyのインストール

     rbenv install 2.2.2
     rbenv global 2.2.2
     ruby -v
    

rbenvのインストール

GitHub: sstephenson/rbenvに書いてある通りインストールする 。また、rubyをインストールするためのプラグインである、ruby-buildもインストールする。ruby-buildとrbenvの関係については「rbenv + ruby-build はどうやって動いているのか」を参照。

git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build

また、ruby-buildの``Suggested build environment''に必要な環境が記述されているので、各システムにあった方法を参照しインストールする。

今回はUbuntuなので下記のコマンドでインストールする。

apt-get install -y autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev

Macbrew install rbenv でインストール。

.bashrc.zshrcもしくは.zshenv等に下記を追加し、パスを通す。

[[ -d ~/.rbenv  ]] && \
  export PATH=${HOME}/.rbenv/bin:${PATH} && \
  eval "$(rbenv init -)"

rubyのインストール

rbenv install -l

でインストール可能なrubyのバージョンが一覧される。特定のバージョンをインストールするコマンドはつぎのようになる。

rbenv install 2.2.2

rubyのインストールが完了したら、利用するrubyのバージョンを指定する。 指定方法はrbenv localrbenv globalがあり、localは特定のワークスペース(ディレクトリ)でrubyのバージョンを使用する場合に指定する。これは、そのディレクトリにある.ruby-versionファイルを書き換えて管理している。一方、globalはシステム全体で使用するバージョンを指定するコマンドである。基本的に使いたいバージョンをglobalで指定し、プロジェクトによってバージョンを変更したい場合はlocalで指定するのがよい。

rbenv global 2.2.2

また、rbenvでrubyをインストールしたり、gemでパッケージをインストールした後はrbenv rehashを実行しなければならなかった。実行することによって、指定したバージョンのrubygemコマンドが.rbenv/shimsに配置される。現在はrbenv本体に取り込まれたため不要である(sstephenson/rbenv/pull/638)。

最後に、指定したバージョンのrubyにパスが通っているか確認しておこう。

$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
$ which ruby
~/.rbenv/shims/ruby
$ which gem
~/.rbenv/shims/gem

Errors

The Ruby openssl extension was not compiled. Missing the OpenSSL lib?

Downloading ruby-2.2.2.tar.gz...
-> http://dqw8nmjcqpjn7.cloudfront.net/5ffc0f317e429e6b29d4a98ac521c3ce65481bfd22a8cf845fa02a7b113d9b44
Installing ruby-2.2.2...

BUILD FAILED (Ubuntu 14.04 using ruby-build 20150519-3-ge932d47)

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

Last 10 log lines:
                              rake 10.4.2
                              rdoc 4.2.0
skip installing bundle gems because of lacking zlib
...
The Ruby openssl extension was not compiled. Missing the OpenSSL lib?

opensslのなにかが不足してるっぽいのでインストールする。 ruby-buildの``Suggested build environment''に必要な環境が記述されていた。

apt-get install -y autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm3 libgdbm-dev

References