0
votes

How should i define VM made on Vagrant from my host in ansible?

I have just one Vagrant machine with default config: `

Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
config.vm.network "private_network", ip: "55.55.55.55"

and in ssh-config i have port 2222.

When i try from host ssh [email protected]:2222 i can not login (user is created on both), i am not even prompted set password. Also i have same situation in ansible

55.55.55.55 ansible_ssh_port=2222 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.ssh/id_rsa 

Is possible to do that in this way? I dont want to create two Vagrant VMs and have server/client, i have no idea where i should put my ansible code to have it persistant per server.

1

1 Answers

0
votes

The 2222 SSH port in Vagrant is the value on the host (your localhost) of the forwarded port 22 of the guest (the VM).

==> ansible: Forwarding ports...
    ansible: 22 (guest) => 2222 (host) (adapter 1)

So you should connect by using either:

  • localhost on port 2222
  • 55.55.55.55 on port 22

I don't know if you did put your ~/.ssh/id_rsa.pub in the authorized keys on the guest, but by default it's not and you should use the private key .vagrant/machines/<MACHINE_NAME>/virtualbox/private_key.

Also, you can connect into the VM using SSH with vagrant ssh <MACHINE_NAME>.

Usually I use an inventory script with my vagrant hosts (to put in the same dir as Vagrantfile):

#!/bin/bash

INVENTORY_DIR=$(cd $(dirname $0) && pwd)

list() {

  cat <<EOF
{
    "all": {
        "hosts": [
            "$(vagrant status --machine-readable | cut -d ',' -f 2 | sort -u | sed '/^$/d' | paste -sd ',' - | sed 's/,/","/g')"
        ]
    }
}
EOF

}

host() {

  local hostname=$1
  local port="$(VAGRANT_CWD=${INVENTORY_DIR} vagrant port --guest 22 ${hostname})"
  [[ ! ${port} =~ ^[0-9]+$ ]] && port=0

  cat <<EOF
{
  "ansible_host": "localhost",
  "ansible_port": ${port},
  "ansible_user": "vagrant",
  "ansible_ssh_private_key_file": "${INVENTORY_DIR}/.vagrant/machines/${hostname}/virtualbox/private_key"
}
EOF

}

case $1 in
  --list) list;;
  --host) host $2;;
  *) exit 1;;
esac

Then you can use ansible with --inventory <INVENTORY_SCRIPT>