Over a million developers have joined DZone.

Environment Variables with Vagrant and Ansible

How to configure Ansible and Vagrant to use a web proxy server.

· DevOps Zone

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

One of the joys of working in a big corporate environment is the use of a Web proxy server for connection to the Internet. When provisioning a virtual machine with Vagrant and Ansible, this means that sometimes the VM has to go through the proxy and sometimes it doesn’t. I’d rather this was as seamless a transition as possible. The solution I came up with can be extended to other cases where different Ansible behavior is needed at different times.

The first step is to configure Ansible to use the environment variable. This is done using the environment attribute on a task in a playbook. For example, a task to update an Ubuntu box looks like this:

- name: update
    apt: upgrade=yes
    environment: proxy_env

The proxy_env variable could be declared in a vars section within the Ansible playbook. But it’s more flexible to pass it through from the Vagrantfile. This means a provisioning section like this:

config.vm.provision "ansible" do |ansible|
    ansible.playbook = "playbook.yml"
    ansible.extra_vars = {
      proxy_env: {
        http_proxy: proxy

This in turn sets the http_proxy to a proxy variable in the Vagrantfile. Theproxy variable is set elsewhere in the Vagrantfile, like this:

proxy = ENV['http_proxy'] || ""

So if the http_proxy environment variable is set on the host, it will be set in the Vagrantfile, which will cause it to be passed to Ansible, which will cause Ansible to set it in the VM before it runs the apt-get update task.

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

vagrant ,ansible

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}