klenwell
klenwell

Reputation: 7148

In Ansible, how is the environment keyword used?

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?

Upvotes: 13

Views: 12883

Answers (2)

magnetik
magnetik

Reputation: 4431

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.

Upvotes: 16

Matt Schlobohm
Matt Schlobohm

Reputation: 1378

I have a very similar issue; I'd like to have ansible do it's stuff inside a Python virtualenv (after it's made sure it's set up for me, of course).

Here's one way I've done the environment preconditions so far; essentially I have had to add (and optionally remove) lines to .bashrc:

  tasks:
    - name: "Enable virtualenv in .bashrc"
      lineinfile: dest=.bashrc
                  line="source {{ PROJECT_HOME }}/venv/bin/activate"

    # Put tasks that rely on this environmental precondition here (?)

    - name: "Disable virtualenv in .bashrc"
      lineinfile: dest=.bashrc
                  line="source {{ PROJECT_HOME }}/venv/bin/activate"
                  state=absent

I don't know if I'm "Doing It Wrong", but until I figure it out or someone comes along to tell me how to do it better, I suppose this will work.

Upvotes: 0

Related Questions