penglongli / blog

18 stars 1 forks source link

Ansible 推送公钥 #39

Open penglongli opened 6 years ago

penglongli commented 6 years ago

使用 Ansible 推送公钥到远程主机,使用到了 ansible 的 authorized_key 模块。 详情参见文档: http://docs.ansible.com/ansible/latest/authorized_key_module.html

步骤

新建 inventory 文件

# cat inventory
[server]
114.67.232.12

[server:vars]
# New client's user/pass
ansible_ssh_user=root
ansible_ssh_pass=123456

我们在上述的 [server] 组增加了一个远程主机 IP:114.67.232.12

新建 playbook.yml 文件

# cat playbook.yml
---
- hosts: server

  tasks:
    - name: PermitRootLogin
      lineinfile:
        dest: /etc/ssh/sshd_config
        state: present
        regexp: '.*PermitRootLogin.*'
        line: 'PermitRootLogin yes'
    - name: Push ssh_key
      authorized_key:
        user: root                                             # 远程主机用户
        key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"   # 本机公钥路径

playbook.yml 文件中我们增加了两个 task:

新建 ansible.cfg 文件

# cat ansible.cfg
[defaults]
host_key_checking=false

在完成上述步骤后,执行:

# ansible-playbook -i inventory playbook.yml

示例代码: https://github.com/penglongli/ansible-sample/tree/master/sample-3