Ansible:为新系统添加SSHKEY

前言:考虑到Root密码在playbook中明文配置是不安全的,建议在Kickstart中为新系统添加SSHKey,本文仅作为演示。


1、配置Inventory,默认/etc/ansible/hosts,添加如下配置:

#定义host组

[hostname]
web[1:9].fun.com

[hostname:vars]
ansible_ssh_user="fun"
ansible_ssh_pass="123456"
ansible_sudo_pass="123456"


2、Playbook #使用root通过SSH的密码认证方式登录新系统,添加非特权用户 fun 并赋予sudo 权限;

---
  - hosts: all
    remote_user: root
    vars:
      ansible_ssh_user: "root"
      ansible_ssh_pass: "123456"
    tasks:
      - name: Add user #添加非特权用户
        user:
          name: "fun"
          password: "$6$yGmnJC/I$Ix8k0M5xwiRTYRlkSUMc8UtE7NlzFYpvCEs9GKS/0GcseX5FS9eU.5GSLvcZA/4pzBekgFWAD/vepMQuI2Sl."

      - name: Modify sudoers  #修改sudoers文件为用户添加sudo权限
        lineinfile:
          path: "/etc/sudoers"
          line: "fun ALL=(ALL) ALL"

ps:

由于密码认证方式的限定,可能出现报错信息,需要修改部分配置:

错误:Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host.

修改配置文件:/etc/ansible/ansible.cfg

host_key_checking = False


3、Playbook #将用户 fun 的公钥导入新系统

---
  - hosts: all
    become: yes
    tasks:
      - name: Auth
        authorized_key:
          user: fun
          key:  "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
ps:

利用ssh-keygen生成公钥:

$ ssh-keygen
连续3次回车,将在 ~/.ssh/目录下生成id_rsa.pub公钥







你可能感兴趣的:(ansible)