我有一个Ansible任务,可以在远程盒子上创建新用户,使该用户成为sudo
用户,然后禁用root
用户的SSH登录。随后,远程盒上的所有任务都以此新用户身份运行。有没有办法在同一个游戏/剧本中切换到新用户?
例如,这是当前目录结构的样子:
|-- initial_setup
| |-- change_hostname.yml
| |-- main.yml
| `-- newuser.yml
|-- main.yml
|-- README.md
|-- roles
| `-- apache
| |-- conf
| | `-- httpd.conf
| |-- handlers
| | `-- main.yml
| `-- tasks
| `-- main.yml
|
`-- start_install.sh
目前,我运行 start_install.sh
脚本开始诉讼:
#!/bin/bash
# Install a new remote user with 'sudo' privileges
ansible-playbook initial_setup/main.yml
# Start main installation process
ansible-playbook main.yml
如上所示,它首先执行initial_setup/main.yml
,然后进入“正确”的剧本。这些都列在下面:
initial_setup/main.yml
[root@testserver record1]# cat initial_setup/main.yml
- include: newuser.yml
- include: change_hostname.yml
initial_setup/newuser.yml
---
- hosts: redbox1
remote_user: root
vars:
NEW_SUDO_USER: 'ansibleuser'
tasks:
- name: Create a new secondary, non-root, sudo user
user: name={{ NEW_SUDO_USER }}
password='testpass'
shell='/bin/bash'
# followed by the tasks to give the user sudo privileges,
# allow SSH access to the new user, remove root SSH etc.
然后正确的剧本( ./main.yml
)开始,如下所示:
[root@testserver record1]# cat main.yml
---
- hosts: redbox1
remote_user: ansibleuser
become: yes
become_method: sudo
roles:
- apache
我不确定这是在Ansible中完成这些任务的正确方法(也就是说,使用shell脚本执行不同的 play ,每个都使用不同的remote_user
)。是否有其他更清洁的解决方案可以达到相同的效果?