Ansible:检查我的用户是否存在于远程主机上,否则使用 root 用户通过 ssh 连接

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

我目前正在编写一个 Ansible 脚本,该脚本应该在运行 Debian 或 CentOS 的每台主机上更新 openssl。在主机上,我们的 SSH 密钥是为我自己的用户 root 存放的。我想检查我的用户是否存在于主机上,如果不存在,我想使用根用户进行身份验证。有可能这样做吗?我用 bash 命令尝试了它,但我想在运行任务之前检查我的用户是否存在。也许我的问题还有其他解决方案,但我不知道。运行此剧本会引发语法错误。我的脚本现在看起来像这样: --- - hosts: "{{ host_group }}" remote_user: "{{ username }}" tasks: # Check whether there's a existinig user or whether you have to use root - name: Check whether there's your user on the machine action: shell /usr/bin/getent passwd $username | /usr/bin/wc -l | tr -d '' register: user_exist remote_user: root when: user_exist.stdout == 0 tags: - users # Install openssl on Ubuntu or Debian - name: Install openssl on Ubuntu or Debian become: True become_user: root apt: name=openssl state=latest when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu' # Install openssl on CentOS or RHEL - name: Install openssl on CentOS or RHEL become: True become_user: root yum: name=openssl state=latest when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'


ssh ansible
3个回答
10
投票
local_action

测试连接。

Ansible 需要确定如何连接到主机,否则会触发 
host unreachable
错误并跳过该主机的剩余任务。
像这样的东西:

- hosts: myservers gather_facts: no # or it will fail on the setup step tasks: - name: Test user local_action: "command ssh -q -o BatchMode=yes -o ConnectTimeout=3 {{ inventory_hostname }} 'echo ok'" register: test_user ignore_errors: true changed_when: false - name: Do useful stuff remote_user: "{{ test_user | success | ternary(omit, 'root') }}" command: echo ok



8
投票
ping

模块(它验证端到端 SSH 连接,不是 ICMP),并使用 playbook 关键字 ignore_unreachable

,这是 Ansible 2.7 中添加的。 
下面的技术将 SSH 测试融入到自己的游戏中,但没有收集事实;接下来的游戏将照常收集事实:

--- ### ## First play: Dynamically configure SSH user ## - hosts: "{{ host_group }}" gather_facts: false # don't try to ssh yet!! vars: ansible_ssh_user: "{{ username }}" tasks: - name: "Test SSH connection" ping: # <-- no args needed ignore_unreachable: true ignore_errors: true changed_when: false register: ssh_test - name: "Fall back to root user?" when: ssh_test.unreachable is defined connection: local set_fact: ansible_ssh_user: root ### ## Next play: Install Stuff ### - hosts: "{{ host_group }}" tasks: - name: Install openssl on Ubuntu or Debian # ...



0
投票
unreachable

的另一个本机解决方案,您可以使用

wait_for_connection
:
--- - name: Juggle SSH user hosts: all gather_facts: false # important! tasks: - name: Try connecting with default settings ansible.builtin.wait_for_connection: timeout: 3 ignore_errors: true register: _ssh_user_test - name: Set SSH user juggling fact ansible.builtin.set_fact: ansible_ssh_user: root when: _ssh_user_test is failed # ... # Run your other tasks here

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