Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active January 15, 2016 09:08
Show Gist options
  • Save maxivak/31e7b30e224258c99a56 to your computer and use it in GitHub Desktop.
Save maxivak/31e7b30e224258c99a56 to your computer and use it in GitHub Desktop.
Provision servers with Ansible and Vagrant

Provision servers with Ansible and Vagrant

Servers are managed by Vagrant and provisioned using Ansible scripts.

Structure

Servers (machines) are managed by Vagrant.

Files structure

/../machines/myserver1
/../machines/myserver2
/../machines/myserver3
...

Each server might have multiple instances.

In the example below, server 'myserver1' has two instances(machines) named 'main' and 'dev' which defined in Vagrantfile

# in  /../machines/myserver1/Vagrantfile

Vagrant.configure(2) do |config|

config.vm.define "main", primary: true do |m|
    # settings for 'main' machine
end


config.vm.define "dev", primary: true do |m|
end


end

Files for the server:

# in ../machines/myserver1/

Vagrantfile
playbook.yml - main Ansible playbook for initial provisining of a server

task1.yml - other Ansible files

Vagrantfile

Each vagrant can manage multiple machines. There are two machines - 'main' and 'dev' in the example below:

Vagrant.configure(2) do |config|

config.vm.define "main", primary: true do |m|
    # settings for 'main' machine
    
    m.vm.provision "ansible" do |ansible|
      ansible.playbook = "playbook.yml"
      ansible.extra_vars =
          {
          }
    end
end


config.vm.define "dev", primary: true do |m|
    # settings for 'dev' machine
    
    m.vm.provision "ansible" do |ansible|
      ansible.playbook = "playbook.yml"
      ansible.extra_vars =
          {
          }
    end
end


end

Provision using Vagrant

run playbook.yml for 'main' machine:

vagrant provision main --provision-with=ansible

run playbook.yml for 'dev' machine:

vagrant provision dev --provision-with=ansible

Provision with arbitrary Ansible file

Create the following files in /../machines/

provision.rb - main executable script
inventory - Ansible inventory file

common/ - all common scripts
common/task1.yml - Ansible script

Ansible inventory

[myserver1]
s1.local ...

[myserver1:vars]
vagrant_machine_name=main



Provision with Ansible

run task 'common/task1.yml' on myserver1

provision.rb myserver1 common/task1.yml

Multiple inventories

If you have many inventories like this:

inventory_production
inventory_dev
inventory2

you can specify which inventory to use while running provision script:

provision.rb myserver1 common/task1.yml -i inventory_dev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment