Search code examples
vagrantansibleansible-ad-hoc

Vagrant and Ansible: ad-hoc command does not work


I'm trying to get Ansible and Vagrant working. In a folder (called Vagrant) I have a Vagrantfile, a hosts file and an ansible.cfg file with following contents:

Vagrantfile

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

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# General Vagrant VM configuration.
 config.vm.box = "geerlingguy/centos7"
 config.ssh.insert_key = false
 config.vm.synced_folder ".", "/vagrant", disabled: true

 config.vm.provider :virtualbox do |v|
   v.memory = 256
   v.linked_clone = true
 end

  # Server 1.
 config.vm.define "server1" do |app|
   app.vm.hostname = "server1.dev"
   app.vm.network :private_network, ip: "192.168.0.10"
 end
end

Hosts file

[server1]
192.168.0.10

And ansible.cfg file

[defaults]
inventory = hosts
remote_user = vagrant
host_key_checking = False
ansible_ssh_private_key_file=<absolute_path_to_folder>/.vagrant/machines/server1/virtualbox/private_key
ansible_ssh_user=vagrant

When I run the following command, it does not work:

macbook-pro:Vagrant user1$  ansible server1 -m command -a uptime
192.168.0.10 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh.",
    "unreachable": true
}

There seems to be no private key file in the .vagrant/machines/server1/virtualbox folder.

When I change the ansible.cfg file to

[defaults]
inventory = hosts
remote_user = vagrant
host_key_checking = False
private_key_file = /Users/wauterw/.vagrant.d/insecure_private_key

it works.

How can I use/create a private key in the .vagrant/machines/server1/virtualbox/private_key instead of the general insecure_private_key?


Solution

  • Remove config.ssh.insert_key = false or change to true as suggested by other answer. This will create a new key whenever you create the instance.

    Use hosts file to specify your Ansible connection.

    Tested this with ansible-2.1.1.0 and Vagrant 1.8.1:

    ansible.cfg:

    [defaults]
    inventory = hosts
    host_key_checking = False
    

    hosts:

    [server1]
    192.168.0.10 ansible_ssh_private_key_file=.vagrant/machines/server1/virtualbox/private_key ansible_user=vagrant
    

    Run with ansible -vvvv to verify the connection ansible is using. You should see something like:

    I.e.

    <192.168.0.10> SSH: EXEC ssh -C -vvv ... -o 'IdentityFile=".vagrant/machines/server1/virtualbox/private_key"' 
    -o User=vagrant