大多数服务器最初都会部署有root
SSH 密钥或密码的直接 SSH 访问权限,以便您可以配置服务器。由于安全问题,我想配置一个具有sudo
权限的新用户并禁用 的直接访问权限root
。
我想创建一个可以帮我完成这项任务的 Ansible Playbook,但我不知道是否可以根据“您可以以 root 身份 ssh 吗?”之类的条件设置等。在运行剧本时ansible_user
,ansible_become
是否可以让 Ansible 检测到这一点?
答案1
是的,这是可能的,但大多数解决方案乍一看都会显得相当复杂。你最好简单地定义一个只执行一次的“引导”剧本。这就是我必须安装 python 并设置初始用户的原因。
但是,为了直接回答这个问题,这里有一个可行的解决方案:
# Experiment to "fix" `ansible_user` depending upon host availability
- hosts: all
gather_facts: false # Otherwise initial connection will fail
vars:
- bootstrap_user: root
tasks:
- debug:
msg: |
ansible_user: {{ ansible_user | d('unset') }};
remote_user: {{ remote_user | d('unset') }}
- action: ping
ignore_unreachable: true # requires Ansible >= 2.7
ignore_errors: yes
register: pingtest
# Works (mostly) for Ansible >= 2.2.
# Might think this alone would work, but only if NOT *ALL* hosts failed up to
# this point, which makes running the playbook on only a single host pointless.
# Therefore, also set `ignore_unrechable` in `ping` above.
# - https://github.com/ansible/ansible/issues/26362
# - https://github.com/ansible/ansible/issues/19673
# - https://github.com/ansible/ansible/issues/18075
- meta: clear_host_errors
- name: set ansible_user if no ping failed
set_fact:
ansible_user: "{{ bootstrap_user }}"
when: pingtest.failed | d(pingtest.unreachable) | d(false)
- debug:
msg: "ansible_user: {{ ansible_user | d('unset') }}"
# Connect as ansible_user from here on
- name: Show remote user
shell: "echo $USER"
changed_when: false
一般来说,以下两个参考将帮助您理解变量(和优先级,这在这里很重要)以及错误恢复: