Ansible 权限问题

8

我正在尝试将当前用户添加到系统中的一个组中,然后执行需要该组权限的命令。我的playbook如下:

- name: Add this user to RVM group
  sudo: true
  user: state=present name=vagrant append=yes groups=rvm group=rvm
- name: Install Ruby 1.9.3
  command: rvm install ruby-1.9.3-p448 creates=/usr/local/rvm/bin/ruby-1.9.3-p448

问题在于所有这些操作都在同一个 shell 中进行。vagrant 的 shell 尚未更新新的组。有没有一种干净的方法在 Ansible 中刷新用户当前的组?我想我需要让它重新连接或打开一个新的 shell。
然而,我尝试打开一个新的 shell,但它却一直挂起:
- name: Open a new shell for the new groups
  shell: bash

当然会挂起:该进程永远不会退出!

newgrp也是同样的情况。

- name: Refresh the groups
  shell: newgrp

因为它基本上做的是同样的事情。
有任何想法吗?

你提到了“playbook”。我猜你是指黑莓Playbook?也许可以删除“Linux”标签,添加“QNX”标签? - thom
这是一个Ansible Playbook - 一个配置管理文件。 - brendan
4个回答

4

请阅读手册。

这里的解决方案是使用'command'或'shell'模块的'executable'参数。

因此,我尝试使用如下命令模块:

- name: install ruby 1.9.3
  command: rvm install ruby-1.9.3-p448 executable=/bin/bash creates=/usr/local/rvm/bin/ruby-1.9.3-p448
  ignore_error: true

但是playbook卡在了那里。根据手册的描述:

如果您想通过shell运行命令(比如使用<, >, |等字符),实际上您需要使用shell模块。与用户环境无关的command模块更加安全。

因此,我尝试使用shell模块:
- name: install ruby 1.9.3
  shell: rvm install ruby-1.9.3-p448 executable=/bin/bash creates=/usr/local/rvm/bin/ruby-1.9.3-p448
  ignore_error: true

它有效!


3

正如其他人所述,这是由于与远程主机的一个活动ssh连接。用户需要注销并重新登录以激活新组。

一个单独的shell操作可能是一个解决方案,但如果你想运行多个其他任务,并不想被强制编写所有命令并使用Ansible模块代替,可以终止ssh连接。

- name: Killing all ssh connections of current user
  delegate_to: localhost
  shell: ssh {{ inventory_hostname }} "sudo ps -ef | grep sshd | grep `whoami` | awk '{print \"sudo kill -9\", \$2}' | sh"
  failed_when: false

我们不使用Ansible的开放式ssh连接,而是通过shell操作启动自己的ssh连接。然后我们杀死当前用户的所有打开的ssh连接。这将强制Ansible在下一个任务中重新登录。


这是一个非常有趣的方法;希望我有机会尝试一下。 - brendan

2

我在capistranochef中遇到过这个问题,这是因为您已经有了一个用户会话,而该用户还没有该组,您需要关闭会话并打开新会话,以使用户看到所添加的组。


1
我在使用Ansible 1.8的RHEL 7.0上,但是已接受的答案对我没有用。唯一的方法是使用sg来强制Ansible加载新添加的rvm组。
- name: add user to rvm group
  user: name=ec2-user groups=rvm append=yes
  sudo: yes

- name: install ruby
  command: sg rvm -c "/usr/local/rvm/bin/rvm install ruby-2.0.0"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接