2016-09-26 62 views
4

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

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

回答

3

您可以首先测试与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 
+1

你能解释一下这段代码的作用吗?我想了解它的意义,不想在没有知识的情况下复制和粘贴这个文件 – princexzijvd

+0

嗯...什么部分?首先,我们在localhost上执行'ssh'命令来测试是否可以用当前用户连接到有问题的主机。将结果注册到'test_user'变量。忽略错误(因为如果我们无法与当前用户连接,命令将失败)。然后,根据我们测试的成功/失败情况,我们将'remote_user'设置为'root',如果'success'(当前用户存在),不要设置'remote_user'(使用'omit'关键字);如果失败(当前用户不存在),将'remote_user'设置为'root'。 –

+0

很酷,这个工程! gather_facts:上面的no禁止在远程主机上收集关于操作系统的事实,但是我需要知道哪些操作系统在远程主机上为程序包管理器运行。如何收集远程操作系统而不收集每一个事实?编辑:只为了我知道,你能解释你写的'三元'东西吗? – princexzijvd