aboutnagaishiの日記

テレコム屋さん出身で、現在はweb企業の社内インフラやっています。インフラ周りを中心に業務の備忘録として使用します。

ansible.cfgを設定しコマンドをシンプルに

ansibleを色々試しているとオプションを毎回入力することが手間になったり、オプションを明示しないことでつまずくことがある。 ansible.cfgを設定すればコマンドをスッキリかつミスを防ぐことができる。

ローカルマシンから仮想マシンpingが通らない。

$ ansible -m ping -i hosts 192.168.33.12 -u vagrant
192.168.33.12 | 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

オプションにプライベートキーを明示したら解決した。

$ ansible -m ping -i hosts 192.168.33.12 -u vagrant --private-key /Users/NAGAISHI/.vagrant.d/insecure_private_key
192.168.33.12 | success >> {
    "changed": false, 
    "ping": "pong"
}

ansible.cfgの設定

毎度ansibleを実行する際にオプションをしてするのは大変。 ansible.cfgにあらかじめオプションを記載しておけば指定する必要がない。 ansible tutorialによれば以下の順番でansible.cfgを探す。

  1. カレントディレクトリ
  2. 環境変数の ANSIBLE_CONFIG or ~/ansible.cfg
  3. /etc/ansible/ansible.cfg

引用元: ansible tutorial

ansible.cfg

[defaults]
hostfile = ./hosts
remote_user = vagrant
private_key_file=/Users/NAGAISHI/.vagrant.d/insecure_private_key

hosts

[default]
192.168.33.11

ansible.cfgを設定した後、例のコマンドは以下のようにスッキリした。 (ansible.cfgはカレントディレクトリに格納)

$ ansible all -m ping
192.168.33.12 | success >> {
    "changed": false, 
    "ping": "pong"
}