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

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

问题描述

我当前正在编写一个Ansible脚本,该脚本应该在运行Debian或CentOS的每台主机上更新openssl.在主机上,我们的SSH密钥存放在我自己的用户根目录下.我想检查我的用户是否存在于主机上,如果不存在,我想与根用户进行身份验证.有可能这样做吗?我使用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天全站免登陆