Ansible:检查我的用户是否存在于远程主机上,否则使用 root 用户与 ssh 连接 [英] Ansible: Check if my user exists on remote host, else use root user to connect with ssh

查看:42
本文介绍了Ansible:检查我的用户是否存在于远程主机上,否则使用 root 用户与 ssh 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently writting an Ansible script which should update openssl on every host running Debian or CentOS. On the hosts our SSH-Keys are deposited for my own user or root. I want to check if my user is existing on the host, if not I want to authenticate with the root user. Is there a possibility to do this? I tried it with a bash command but I want to check if my user exists before I'm running the tasks. Maybe there are other solutions to my problem but I don't know them. Running this playbook throws a syntax error. My Script looks like this right now:

---
- 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'

推荐答案

可以先用local_action测试连接.
Ansible 需要确定如何连接到主机,否则会触发 host unreachable 错误并跳过该主机的剩余任务.
像这样:

You can test the connection with local_action first.
Ansible need to know how to connect to the host for sure, otherwise it will trigger host unreachable error and skip remaining tasks for that host.
Something like this:

- 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

这篇关于Ansible:检查我的用户是否存在于远程主机上,否则使用 root 用户与 ssh 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆