Ansible: create a user with sudo privileges
我已经接管了Ubuntu 14.04服务器。它有一个名为" deployer"的用户(与capistrano一起使用),因此,它需要sudo特权。通过此设置,我可以登录服务器并执行以下操作:
1 2 3 4 | workstation> ssh deployer@myserver myserver> sudo apt-get install git myserver> exit workstation> |
我试图弄清楚如何使用Ansible(2.0.2.0版和python 2.7.3版)创建一个名为" deployer"的用户,并能够使用该ID登录到服务器,然后使用诸如" apt"之类的类似东西。 -get install"。我的剧本看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | --- - 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 |
运行完此剧本后,我可以作为"部署者"(例如ssh deployer @ myserver)以ssh身份进入计算机,但是如果我运行sudo命令,它将始终要求我提供我的sudo密码。
我知道"部署者"用户最终必须找到进入visudo用户文件的方式,但是我无法弄清楚要调用哪个神奇的Ansible咒语,以便我可以作为部署者使用ssh进入计算机,然后运行sudo命令(例如sudo apt-get install git"),而不会提示您输入sudo密码。
我已经搜索了很多东西,但似乎找不到Ansible剧本片段,该片段将用户"部署者"放入sudo组而无需密码。怎么做?
有时它知道要问什么。我不知道自己是从事某些DevOps工作的开发人员。
显然," passwordless"或NOPASSWD登录是您需要放在/ etc / sudoers文件中的东西。
我的问题的答案在Ansible:维护sudoers列表的最佳实践。
从我的问题来看,Ansible剧本的代码片段如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | - 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 |
最好的部分是解决方案是幂等的。它不添加线
1 | %wheel ALL=(ALL) NOPASSWD: ALL |
下次运行该剧本时,将其转到/ etc / sudoers。是的...我能够以"部署者"身份进入服务器并运行sudo命令,而无需提供密码。
创建具有sudo特权的用户是将用户置于
1 2 3 4 5 6 7 8 | ## 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 |
而不是摆弄
要在Ansible中实现以上目标,请参考以下内容:
1 2 3 4 5 | - name: sudo without password for wheel group copy: content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL' dest: /etc/sudoers.d/wheel_nopasswd mode: 0440 |
您可以将
使用visudo,按
1 | deployer ALL=(ALL) NOPASSWD: ALL |
然后写并退出(