Ansible:使用sudo权限创建用户

问题描述 投票:52回答:3

我接管了一台Ubuntu 14.04服务器。它有一个名为“deployer”的用户(与capistrano一起使用),因此需要sudo权限。通过此设置,我可以登录服务器并执行以下操作:

workstation> ssh deployer@myserver
myserver>  sudo apt-get install git
myserver> exit
workstation>

我试图找出如何使用Ansible(版本2.0.2.0和python 2.7.3)来创建一个名为“deployer”的用户,并能够使用该id登录到服务器然后sudo-ish之类的东西,如“apt --get install“。我的剧本看起来像这样:

---
- hosts: example
  become: yes
  tasks:
  - name: Update apt cache
    apt:
      update_cache: yes
      cache_valid_time: 3600

  - group: name=sudo state=present

  - name: Add deployer user and add it to sudo
    user: name=deployer
          state=present
          createhome=yes
    become: yes
    become_method: "sudo"

  - name: Set up authorized keys for the deployer user
    authorized_key: user=deployer key="{{item}}"
    with_file:
      - /home/jaygodse/.ssh/id_rsa.pub

运行这个剧本之后,我能够以“deployer”(例如ssh deployer @ myserver)进入机器,但是如果我运行sudo命令,它总是要求我输入我的sudo密码。

我理解“deployer”用户最终必须找到进入visudo用户文件的方式,但是我无法弄清楚要调用哪个神奇的Ansible咒语以便我可以作为部署者ssh进入机器然后运行sudo命令(例如sudo) apt-get install git“)没有提示输入sudo密码。

我已经搜索了高低,我似乎无法找到一个Ansible playbook片段,它将用户“deployer”放入sudo组而不需要密码。这是怎么做到的?

ansible-playbook sudoers
3个回答
99
投票

有时它知道该问什么。我不知道,因为我是开发人员,他接受了DevOps的一些工作。

显然,'无密码'或NOPASSWD登录是你需要放在/ etc / sudoers文件中的东西。

我的问题的答案是在Ansible: best practice for maintaining list of sudoers

Ansible playbook代码片段从我的问题看起来像这样:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user: name=deployer groups=wheel append=yes state=present createhome=yes


- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

最好的部分是解决方案是幂等的。它不添加该行

%wheel ALL=(ALL) NOPASSWD: ALL

当playbook随后运行时,到/ etc / sudoers。是的...我能够以“deployer”的形式进入服务器并运行sudo命令而无需提供密码。


2
投票

要创建具有sudo权限的用户,请将用户置于/etc/sudoers中,或使用户成为/etc/sudoers中指定的组的成员。并且要使其无密码是在NOPASSWD中另外指定/etc/sudoers

/etc/sudoers的例子:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

而不是摆弄/etc/sudoers文件,我们可以在/etc/sudoers.d/目录中创建一个新文件,因为这个目录默认包含在/etc/sudoers中,这避免了破坏现有sudoers文件的可能性,并且还消除了对/etc/sudoers内容的依赖。

要在Ansible中实现上述目的,请参阅以下内容:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

您可以将%wheel替换为%sudoers等其他组名或deployer等其他用户名。


-6
投票

使用visudo,按Shift+G并附加到文件末尾:

deployer  ALL=(ALL)       NOPASSWD: ALL

写然后退出(:wq

© www.soinside.com 2019 - 2024. All rights reserved.