【问题标题】:How to run a shell function as a command in Ansible?如何在 Ansible 中将 shell 函数作为命令运行?
【发布时间】:2016-09-21 17:00:50
【问题描述】:

我正在使用nvm (https://github.com/creationix/nvm),它本质上是一个 shell 脚本,您可以将其作为源代码输入到您的 shell 中,然后调用,例如,nvm install [version]。但无论我如何尝试调用该函数,ansible 似乎都找不到它。

我尝试过使用commandshell 模块。我试过使用becomebecome_user。我试过像https://github.com/leonidas/ansible-nvm/blob/master/tasks/main.yml 一样使用sudo -iu,但它对我不起作用。但它必须是可能的,因为它在那个文件中工作。

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

【问题讨论】:

    标签: 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 }}
      

      【讨论】:

        猜你喜欢
        • 2013-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        相关资源
        最近更新 更多