LoginSignup
10
8

More than 5 years have passed since last update.

Vagrant AWS Provider プラグインでEC2インスタンスを使う

Posted at

今さらながらVagrantでAWS Provider(Virtual Box の仮想マシンではなく、EC2インスタンスを使うやつ)を使ってみたのでメモ

事前にAWSプラグインをいれましょう

$ vagrant plugin install vagrant-aws

Vagrantfile

Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "dummy"
  config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"
  config.ssh.pty = true
  config.vm.provider :aws do |aws, override|
    aws.access_key_id = "AWSNOACCESSKEY"
    aws.secret_access_key = "AWSNOSECRETKEY"
    aws.ami = "ami-cbf90ecb"
    aws.instance_type="t2.micro"
    aws.security_groups=["sg-873248e2"]
    aws.keypair_name = "newgyu-dev1"
    aws.region = "ap-northeast-1"
    aws.associate_public_ip = true
    aws.subnet_id = "subnet-be3dbdc9"
    override.ssh.username="ec2-user"
    override.ssh.private_key_path = '~/.ssh/newgyu-dev1.pem'
  end
  config.vm.synced_folder "../playbook", "/playbook"
end

providerとして:awsを指定

https://github.com/mitchellh/vagrant-aws/blob/master/README.md に書いてあるとおりですが、

config.vm.provider :aws do |aws, override|
   :
end

で囲ったブロック内に aws.* , override.* に対する設定を書きます。

boxファイルはダミーのものを指定する

config.vm.box = "dummy"
config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"

ここは素直に。

AWSでEC2インスタンスのcreate,dropができるユーザーのAPIキーを指定

aws.access_key_id = "AWSNOACCESSKEY"
aws.secret_access_key = "AWSNOSECRETKEY"

必須ですね。ベタに書きたくない場合は環境変数から取得するように、

aws.access_key_id = ENV["AWS_ACCESS_KEY"]
aws.secret_access_key = ENV["AWS_SECRET_KEY"]

とかでもいいです。(このへんはVagrantfileはrubyなのでrubyの書式を利用する感じです)

通常はインターネット経由での利用になるのでpublic_ipで

自分の場合はVPCを設定していたので、

  • VPCの中に公開サブネット
  • インターネット越しにsshが通るセキュリティグループ

を事前にAWS Consoleで作っておく必要がありました。

aws.security_groups=["sg-873248e2"]
aws.associate_public_ip = true
aws.subnet_id = "subnet-be3dbdc9"

VPCなしの直EC2の場合はたぶんセキュリティーグループでsshが通るようにだけすればいいと思います。

vagrant sshできるように

aws.keypair_name = "newgyu-dev1"
override.ssh.username="ec2-user"
override.ssh.private_key_path = '~/.ssh/newgyu-dev1.pem'
  • keypair_nameを指定するとそのキーペアをEC2インスタンスに設定してくれます 無指定だとどうなるのかは試していません。(新たにキーペアつくるのかな?)
  • ssh.usernameの指定はほぼ必須だと思われます
  • ssh.private_key_pathは指定したキーペアの秘密鍵の方を指定します。

synced_folderを使う場合

config.ssh.pty = true
config.vm.synced_folder "../playbook", "/playbook"

まず、AWSプロバイダーを使った場合のsynced_folderはrsync over sshで実現されています。
そのためVagrantファイルの設定でsshログインしてsudoできるようにしておく必要があります。それは上記のec2-userによるssh接続設定をすることでクリアしているはずなのですが、sudoができなくて怒られます。
最近のAmazon LinuxのAMIの初期sudoersにはrequirettyという設定が組み込まれていて、ttyを介さない接続でのsudoをさせないようにしているのが原因とのことで、config.ssh.ptyの設定をすることでttyっぽく振る舞ってくれるようです。

いざ起動

$ vagrant up --provider=aws
10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8