Search code examples
proxyansiblehttp-proxy

Dynamicly set HTTP_PROXY in an ansible playbook


I'm running a playbook either on a bunch of servers with no need of http_proxy and others with needs of it (on different runs).

I've read https://docs.ansible.com/ansible/latest/user_guide/playbooks_environment.html but it doesn't really answer this...

here's an example:

- hosts: all tasks: - name: install vi become: true apt: name: vi state: present

I would like to launch it with a group of servers (let's say server01-atlanta) without proxy and in another run with a group of servers (let's say server01-berlin) with proxy and without changing the code between each run (so managing to do it with inventory variables).

I would


Solution

  • You can solve this with group_vars / host_vars in combination with environment variables. Her is a simple example based on the code from ansible docs.

    ---
    - hosts: all
      vars:
        proxy: # default empty
      tasks:    
        - apt: name=cobbler state=installed
          environment:
            http_proxy: "{{ proxy }}"
    

    This is how you define a environment variable per task. You can also use normal ansible variables for this. There is also a example with proxy settings and variables in the docs. See: https://docs.ansible.com/ansible/latest/user_guide/playbooks_environment.html

    In your inventory you can define the proxy variable per host or group:

    atlanta:
      hosts:
        host1:
        host2:
      vars:
        proxy: proxy.atlanta.example.com
    

    See inventory docs for more details: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#host-variables