我正在尝试运行一个相对简单的Ansible剧本,以通过Vagrant设置Ubuntu VM。大致可分为3个步骤:
前两个步骤很好,但是我正在努力。使用其他剧本作为引用(rbenv和nvm之一),我创建了以下基本剧本:
---
- hosts: all
vars:
user: joe_bloggs
ruby_version: 2.1.5
tasks:
#
# System
#
- name: Update apt cache
sudo: yes
apt: update_cache=yes cache_valid_time=86400
- name: Upgrade existing system packages
sudo: yes
apt: upgrade=dist
- name: Install essential system packages
sudo: yes
apt: name={{ item }} state=latest
with_items:
- git
- curl
- openssl
- build-essential
- name: Add user
sudo: yes
user: name={{user}} shell=/bin/bash groups=sudo
#
# rbenv
#
- name: Install rbenv | Clone repo
sudo: yes
sudo_user: "{{ user }}"
git: repo=https://github.com/sstephenson/rbenv.git dest=~/.rbenv accept_hostkey=yes update=yes
- name: Install rbenv | Create plugins directory
sudo: yes
sudo_user: "{{ user }}"
file: path=~/.rbenv/plugins/ mode=0755 state=directory
- name: Install rbenv | Install ruby-build plugin
sudo: yes
sudo_user: "{{ user }}"
git: repo=git://github.com/sstephenson/ruby-build.git dest=~/.rbenv/plugins/ruby-build accept_hostkey=yes
- name: Install rbenv | Add path to profile
sudo: yes
sudo_user: "{{ user }}"
lineinfile: line='export PATH="$HOME/.rbenv/bin:$PATH"' regexp="\$HOME\/\.rbenv\/bin:\$PATH" dest=~/.bashrc
- name: Install rbenv | Enable shims in profile
sudo: yes
sudo_user: "{{ user }}"
lineinfile: line='eval "$(rbenv init -)"' regexp="rbenv init \-" dest=~/.bashrc
- name: Install Ruby | Install version
sudo: yes
sudo_user: "{{ user }}"
shell: rbenv install {{ ruby_version }} executable=/bin/bash
- name: Install Ruby | Set default version and rehash
sudo: yes
sudo_user: "{{ user }}"
shell: rbenv global {{ ruby_version }} && rbenv rehash executable=/bin/bash
运行上面的剧本时遇到错误:
stderr: /bin/bash: rbenv: command not found
有没有一种优雅的方式可以通过使用Ansible作为用户通过使用他们的shell和环境变量来运行命令?
我尝试添加
-i
sudo标志和类似sudo -iu {{user}} rbenv install ...
的命令,但是我还没有运气。我可以通过指定
rbenv
可执行文件的完整路径来运行Ruby安装,但是这种技术并不总是适用的(某些工具可能不提供单个可执行文件)。 最佳答案
在尝试在 Vagrant 的盒子上使用Ansible 2.1使用rbenv安装ruby-2.2.3时遇到了同样的问题。
rbenv安装在ubuntu上名为rails
的用户上,该用户没有sudo权限,但是当ansible连接到我的ubuntu盒时,它将释放环境。 $ PATH在/home/rails/.bashrc中定义,默认情况下仅为ansible_env.PATH
假设您已经按照以下步骤安装了rbenv:
git clone git://github.com/sstephenson/rbenv.git .rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
为了使路径正常工作,我需要手动设置它,因此对于该特定任务,我做了以下操作:
- name: install rubies
become_user: rails
environment:
PATH: "{{ ansible_env.PATH }}:/home/rails/.rbenv/shims:/home/rails/.rbenv/bin "
shell: '{{ rbenv_shell }} -lc "rbenv install {{ item[0] }}"'
with_together
- "{{ rubies }}"
- "{{ ruby_installed.results }}"
...
这会将您的rbenv命令的路径附加到ansible_env.PATH查找,并使其按预期工作。
关于ubuntu - Ansible剧本,可从用户 shell 执行命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28550619/