【问题标题】:How to run a shell function as a command in Ansible?如何在 Ansible 中将 shell 函数作为命令运行?
【发布时间】:2016-09-21 17:00:50
【问题描述】:
【问题讨论】:
标签:
bash
shell
ansible
ansible-playbook
nvm
【解决方案1】:
您需要使用shell 模块,因为您想要运行shell 命令,并且您需要将nvm 脚本中的源代码放入该环境。比如:
- shell: |
source /path/to/nvm
nvm install ...
您是否使用become 取决于您是否要以root(或其他用户)身份运行命令。
【解决方案2】:
这是我的剧本:
- 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 }}