Provision & Configure EC2 instance with Vagrant and Ansible

In this Simple tutorial, I’ll show you that how you can use the Vagrant with Ansible to provision and configure the EC2 instance on AWS. I am assuming that you already have Vagrant installed and have an AWS account(and know how to use both).

First you need to install the Vagrant AWS plugin:

vagrant plugin install vagrant-aws

After installing the plugin, add dummy AWS box:

vagrant box add aws

Next login to your AWS console to get the following things:

1- AWS access key
2- AWS secret key
3- Security Group name (Make sure that security group enables the SSH port (22) from anywhere)
4- SSH private key file, which will be in .pem extension

I like to set up these parameters as environment variables so that I’ll keep them out of the Vagrantfile. On Linux/MAC, you can add them to ~/.profile file:

export AWS_PRIVATE_KEY="/Users/arbab/KEYS/vagrant.pem"

After that use the following simple Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config| = "aws"
config.vm.synced_folder ".", "/vagrant", disabled: true
config.vm.provider :aws do |aws, override|
aws.access_key_id = ENV['AWS_ACCESS_KEY']
aws.secret_access_key = ENV['AWS_SECRET_KEY']
aws.region = "us-east-1"
aws.availability_zone = "us-east-1c"
# AMI from which we'll launch EC2 Instance
aws.ami = "ami-9a562df2" # Ubuntu 14.04
aws.keypair_name = "vagrant"
aws.instance_type = "t2.micro"
aws.block_device_mapping = [{ 'DeviceName' => '/dev/sda1', 'Ebs.VolumeSize' => 10 }]
aws.security_groups = ["vagrant-sg"]
aws.tags = {
'Name' => 'Vagrant EC2 Instance',
'Environment' => 'vagrant-sandbox'
# Credentials to login to EC2 Instance
override.ssh.username = "ubuntu"
override.ssh.private_key_path = ENV['AWS_PRIVATE_KEY']
# Configuration for Ansible as Provisioner
config.vm.provision :ansible do |ansible|
ansible.playbook = "site.yml"
ansible.verbose = "v"
ansible.host_key_checking = false
ansible.limit = 'all'
view raw vagrant-aws hosted with ❤ by GitHub

In this file, I have all the basic AWS-related settings, please refer to the vagrant-aws documentation for detail options.

And then run by specifying the AWS plugin as the provider:

vagrant up --provider=aws

This will launch an Ubuntu 14.04 instance in the us-east-1 region within your account. If you have issues with SSH connecting, make sure that the SSH access is allowed in the security group of launched instance.

Note: Don’t forget to run vagrant halt and vagrant destroy once you’re done(if you are only using it for testing)!

Enjoy :-)

Hope this will help you!

Please Remember me in your prayers!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: