Bash 如何在Ansible中作为命令运行shell函数?

Bash 如何在Ansible中作为命令运行shell函数?,bash,shell,ansible,ansible-playbook,nvm,Bash,Shell,Ansible,Ansible Playbook,Nvm,我使用的是nvm(),它本质上是一个shell脚本,您可以将其源代码导入shell,然后调用,例如,nvm install[version]。但无论我如何尝试调用该函数,ansible似乎都找不到它 我已经尝试使用命令和shell模块。我试过使用been和been\u user。我试过像在中一样使用sudo-iu,但它对我不起作用。但它必须是可能的,因为它在该文件中工作 如何在Ansible中运行任何shell函数?在本例中,我的.zshrc中有一个source nvm.sh,它允许我从交互式s

我使用的是
nvm
(),它本质上是一个shell脚本,您可以将其源代码导入shell,然后调用,例如,
nvm install[version]
。但无论我如何尝试调用该函数,ansible似乎都找不到它

我已经尝试使用
命令
shell
模块。我试过使用
been
been\u user
。我试过像在中一样使用
sudo-iu
,但它对我不起作用。但它必须是可能的,因为它在该文件中工作


如何在Ansible中运行任何shell函数?在本例中,我的.zshrc中有一个
source nvm.sh
,它允许我从交互式shell中执行
nvm
命令。

您需要使用
shell
模块,因为您想要运行shell命令,并且需要在
nvm
脚本中将源代码导入该环境。比如:

- shell: |
    source /path/to/nvm
    nvm install ...

您是否使用
been
取决于您是否希望以
root
(或其他用户)身份运行命令。

这是我的操作手册:

- hosts: all
  vars:
    # https://github.com/nvm-sh/nvm/releases
    nvm_version: "0.34.0"

    # https://github.com/nodejs/node/releases
    # "node" for latest version, "--lts" for latest long term support version,
    # or provide a specific version, ex: "10.16.3"
    node_version: "--lts"
  tasks:
  - name: Get_nvm_install_script | {{ role_name | basename }}
    tags: Get_nvm_install_script
    get_url:
      url: https://raw.githubusercontent.com/nvm-sh/nvm/v{{ nvm_version }}/install.sh
      dest: "{{ ansible_user_dir }}/nvm_install.sh"
      force: true

  - name: Install_or_update_nvm | {{ role_name | basename }}
    tags: Install_or_update_nvm
    command: bash {{ ansible_user_dir }}/nvm_install.sh

  - name: Install_nodejs | {{ role_name | basename }}
    tags: Install_nodejs
    shell: |
      source {{ ansible_user_dir }}/.nvm/nvm.sh
      nvm install {{ node_version }}
    args:
      executable: /bin/bash
注意
executable:/bin/bash
的使用,因为
source
命令在所有shell中都不可用,所以我们指定
bash
,因为它包括
source

作为
source
的替代方法,您可以使用点:

  - name: Install_nodejs | {{ role_name | basename }}
    tags: Install_nodejs
    shell: |
      . {{ ansible_user_dir }}/.nvm/nvm.sh
      nvm install {{ node_version }}