Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ansible, how is the environment keyword used?

Tags:

ansible

I have a playbook to install PythonBrew. In order to do this, I have to modify the shell environment. Because shell steps in Ansible are not persistent, I have to prepend export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc; to the beginning of each of my PythonBrew-related commands:

    - name: Install python binary
      shell: export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc; pythonbrew install ${python.version}
        executable=/bin/bash

    - name: Switch to python version
      shell: export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc; pythonbrew switch ${python.version}
        executable=/bin/bash

I'd like to eliminate that redundancy. On the Ansible discussion group, I was referred the environment keyword. I've looked at the examples in the documentation and it's not clicking for me. To me, the environment keyword doesn't look much different than any other variable.

I've looked for other examples but have only been able to find this very simple example.

Can someone demonstrate how the environment keyword functions in Ansible, preferably with the code sample I've provided above?

like image 425
klenwell Avatar asked Oct 23 '13 21:10

klenwell


Video Answer


1 Answers

Not sure if it will fits your need, but this is how I see this :

- hosts: all
  vars:
    env:
      PYTHONBREW_ROOT: "{{ pythonbrew.root }}"
  tasks:  
    - name: Install python binary
      shell: pythonbrew install {{ python.version }} executable=/bin/bash
      environment: env

    - name: Switch to python version
      shell: pythonbrew switch {{ python.version }} executable=/bin/bash
      environment: env

It simply sets a variable named env and reuse it as environment in both of your shell commands. This way your shell command will have the PYTHONBREW_ROOT path set.

like image 166
magnetik Avatar answered Oct 17 '22 11:10

magnetik