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

pri*_*jvd 8 ssh ansible

我正在编写一个Ansible脚本,它应该在运行Debian或CentOS的每个主机上更新openssl.在主机上,我们的SSH密钥是为我自己的用户 root 用户存放的.我想检查我的用户是否存在于主机上,如果不是,我想要与root用户进行身份验证.有可能这样做吗?我尝试使用bash命令,但我想在运行任务之前检查我的用户是否存在.也许我的问题有其他解决方案,但我不知道.运行此playbook会引发语法错误.我的脚本现在看起来像这样:

---
- 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'
Run Code Online (Sandbox Code Playgroud)

Kon*_*rov 8

您可以先测试连接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
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下这段代码的作用吗?我想了解它的含义,不想在没有知识的情况下复制并粘贴它 (2认同)
  • 嗯...什么部分?首先,我们在 localhost 上执行 `ssh` 命令来测试是否可以使用当前用户连接到有问题的主机。将结果注册到 `test_user` 变量。如果有错误,请忽略(因为如果我们无法与当前用户连接,命令将失败)。然后我们根据测试的成功/失败将后续任务的`remote_user`设置为`root`:如果`success`(当前用户存在),则不要设置`remote_user`(使用`omit`关键字);如果 `failure`(当前用户不存在),将 `remote_user` 设置为 `root`。 (2认同)

小智 5

测试 SSH 连接的一种更原生、更优雅的方法是使用 Ansible ping模块(它验证端到端 SSH 连接,而不是ICMP),并使用ignore_unreachable在 Ansible 2.7 中添加的 playbook 关键字。

下面的技术在没有收集事实的情况下将 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
      # ...
Run Code Online (Sandbox Code Playgroud)