LoginSignup
3
3

More than 5 years have passed since last update.

VagrantでAWSのインスタンスを指定時間後に停止

Posted at

 AWSのインスタンスを指定時間帯で停止する方法は見かけますが、指定時間後に停止する方法は見かけません。今回は、Vagrantで起動したAWSのインスタンスを指定時間後に停止したいと思います。
 事前準備として、Vagrant及びvagrant-awsプラグインをインストールして置いてください。

 まず、指定時間後の停止については、shutdownコマンドのオプションを利用します。Vagrantのプロビジョニングで以下のコマンドを実行します(指定時間は分単位です)。

sudo shutdown -h +60

ここで問題なのが、AMIでは初期状態でtty経由でのsudoコマンドしか受け付けない設定であることです。そのため、初期状態では以下のエラーメッセージが表示され、プロビジョニングは失敗します。

sudo: sorry, you must have a tty to run sudo

 そこで、回避方法としてプロビジョニングをpty(擬似端末)で実行するよう設定します。なお、このオプションはVagrantの1.4以上のバージョンで適用できます。

config.ssh.pty = true

それでは、Vagrantfileの記載内容を以下に提示します。初回以降のプロビジョニング実行については、VagrantでのAWSのインスタンス起動時にporovisionオプションを指定してください。

Vagrant.configure(2) do |config|
  config.vm.box = "dummy"

  config.vm.provider :aws do |aws, override|
    aws.access_key_id     = 'AWS_ACCESS_KEY_ID'
    aws.secret_access_key = 'AWS_SECRET_ACCESS_KEY'
    aws.keypair_name      = 'AWS_KEYPAIR_NAME'
    aws.security_groups   = 'AWS_SECURITY_GROUP'

    aws.ami = "ami-xxxxxxxx"
    aws.instance_type = "t2.micro"
    aws.region = "ap-northeast-1"
    aws.availability_zone = "ap-northeast-1a"

    override.ssh.username = 'AWS_SSH_USERNAME'
    override.ssh.private_key_path = 'AWS_SSH_KEY'

    # pty will be used for provisioning >= 1.4
    override.ssh.pty = true

  end

  # provisioning with a shell script
  config.vm.provision "shell", inline: <<-SHELL
    sudo shutdown -h +60 &
    sudo ps ax |grep shutdown
  SHELL
end

参照

3
3
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
3
3