LoginSignup
65
64

More than 5 years have passed since last update.

Vagrantで作成したVMにAnsibleを使う時にハマったこと

Posted at

Vagrantfile

安易に以下のようなBoxとVagrantfileを使ってVMを作成。

vagrant box add trusty64 https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "trusty"
  config.vm.network :private_network, ip:"192.168.200.100"
end

VMと通信できない

とりあえずpingモジュールを使って疎通確認をしてみるが失敗。

$ ansible all -i hosts -m ping

192.168.200.100 | FAILED => SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue

  

普通にPingすれば通る

ping 192.168.200.100

  
ansibleコマンドに"-vvvv"オプションを付けると、何が起こっているかは大体わかる。

答え

  • ~/.ssh/config に設定をちゃんと書く。

何も考えずにansibleコマンドを使うと、rootユーザー&.ssh以下にある秘密鍵を使ってSSHしようとするため失敗する。したがって、ログインユーザー名を指定して、鍵も指定すれば解決する。

cat < _EOS_ >> ~/.ssh/config
Host 192.168.200.*
  User vagrant
  IdentityFile /Users/pengin/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
_EOS_

  
.ssh/configに書き込んだら、以下のコマンドを再度実行する。

$ ansible all -m ping

192.168.200.100 | success >> {
    "changed": false,
    "ping": "pong"
}

root権限が必要なタスクの実行に失敗する

例えばaptなど、root権限が確実に必要なタスクを素で実行してみると以下のようなエラーを出力して失敗する。

$ ansible all -i hosts -m apt -a "name=nginx state=present"

192.168.200.100 | FAILED >> {
    "failed": true,
    "msg": "'apt-get install 'nginx' ' failed: E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)\nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root?\n",
    "stderr": "E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)\nE: Unable to lock the administration directory (/var/lib/dpkg/), are you root?\n",
    "stdout": ""
}

答え

  • root以外のユーザーでログインするように設定した場合には、"-s" オプションを指定してsudoするようにしなくてはいけない。
  • パスワードなしでsudoできないユーザーの場合には、"-K" オプションを指定してパスワードを尋ねるようにしなくてはいけない。

vagrantユーザーはroot権限を持っていないし、パスワードなしでsudoを実行できるようにもなっていない。したがって、sudoを使ってコマンドを実行してもらうようにするのとともに、パスワードも与えるようにすれば解決。
    

$ ansible all -i hosts -m apt -a "name=nginx state=present" -s -K

192.168.200.100 | success >> {
    "changed": true,
    "stderr": "",
    "stdout": "Reading package lists...
(以下略)
65
64
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
65
64