在Ansible中,如何使用environment关键字?

时间:2013-10-23 21:14:23

标签: ansible

我有a playbook to install PythonBrew。为此,我必须修改shell环境。因为Ansible中的shell步骤不是持久的,所以我必须将export PYTHONBREW_ROOT=${pythonbrew.root}; source ${pythonbrew.root}/etc/bashrc;添加到每个与PythonBrew相关的命令的开头:

    - 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

我想消除这种冗余。在Ansible discussion group上,我引用了environment个关键字。我查看过examples in the documentation并没有点击给我。对我来说,environment关键字与其他任何变量都没有太大的不同。

我已经找了其他例子,但只能找到this very simple example

有人可以演示environment关键字在Ansible中的功能,最好是我上面提供的代码示例吗?

2 个答案:

答案 0 :(得分:16)

不确定它是否符合您的需要,但这就是我看到的:

- 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

它只是设置一个名为env的变量,并在两个shell命令中将其重用为环境。这样shell命令就会设置PYTHONBREW_ROOT路径。

答案 1 :(得分:0)

我有一个非常相似的问题;我想让ansible在Python virtualenv中做一些事情(当然,确保它为我设置之后)。

到目前为止,这是我完成环境先决条件的一种方式;基本上我必须添加(并可选择删除)行到.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

我不知道我是不是“做错了”,但是直到我弄明白或有人来告诉我如何更好地做到这一点,我想这会有用。