如何使用Ansible将ssh公钥上传为asauthorized_key

时间:2020-01-09 10:39:49  来源:igfitidea点击:

如何使用Ansible将ssh公钥以asauthorized_key的形式上载到列表文件中保存的多个Linux或Unix服务器上?
要为特定用户帐户添加或删除SSH授权密钥,请使用authorized_key模块。

本快速教程介绍了如何创建Ansible PlayBook,该Ansible PlayBook将公共ssh密钥添加到多个Unix或Linux服务器以安全登录。

步骤1:创建主机列表文件

您需要告诉Ansible您将使用哪些主机:

$ cat my_ssh_hosts

输出示例:

server1.theitroad.local
server2.theitroad.local
server3.theitroad.local

步骤2:建立剧本(Playbook)

创建一个名为upload_ssh_keys.yml的文件,如下所示:

--
- hosts: all
  remote_user: Hyman
  tasks:
          # upload ssh key                
          - authorized_key:
                  user: Hyman
                  state: present
                  manage_dir: yes
                  key: "{{ lookup('file', '/path/to/your/www_id_rsa.pub') }}"
# vim:ft=ansible:

上面的代码会将公钥文件(/path/to/your/www_id_rsa.pub)放置到所有服务器列出的my_ssh_hosts文件中。
确保为根帐户设置ssh密钥。

第3步:运行剧本(Playbook)

语法为:

$ ansible-playbook -i my_ssh_hosts upload_ssh_keys.yml

另一个例子

在此示例中,创建了一个名为Hyman的新用户。
为用户Hyman和ssh服务器添加的下一个ssh密钥配置为使用ssh-setup.j2模板删除基于密码的登录。

文件:ssh-setup.yml

--
- hosts: cluster
  tasks:
          # create users for us
          # note user Hyman added to sudo group 
          # on many system you may need to use wheel 
          # user in sudo or wheel group can sudo
          - user:
                  name: Hyman
                  comment: ""
                  shell: /bin/bash
                  groups: sudo
                  append: yes
                  generate_ssh_key: yes
                  ## run command 'mkpasswd --method=sha-512' to create your own encrypted password ##
                  password: $gF1EHgeUSSwDT3$xgw22QBdZfNe3OUjJkwXZOlEsL645TpacwiYwTwlUyah03.Zh1aUTTfh7iC7Uu5WfmHBkv5fxdbJ2OkzMAPkm/
                  ssh_key_type: ed25519
          # upload ssh key                
          - authorized_key:
                  user: Hyman
                  state: present
                  manage_dir: yes
                  key: "{{ lookup('file', '/home/Hyman/.ssh/id_ed25519.pub') }}"
          # configure ssh server
          - template:
                  src: ssh-setup.j2
                  dest: /etc/ssh/sshd_config
                  owner: root
                  mode: '0600'
                  validate: /usr/sbin/sshd -t -f %s
                  backup: yes
          # restart sshd
          - service:
                  name: sshd
                  state: restarted

文件:ssh-setup.j2

以下将禁用root登录和密码登录。
只有名为Hyman的用户可以使用公共密钥通过ssh登录(您需要发出sudo -i命令来获取root shell):

Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
UsePrivilegeSeparation sandbox
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 120
PermitRootLogin {{ sshd_permitroot_login }}
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
LogLevel VERBOSE
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM {{ sshd_use_pam }}
PasswordAuthentication {{ sshd_password_authentication }}
ChallengeResponseAuthentication {{ sshd_challenge_response_authentication }}
{% for nip in ansible_all_ipv4_addresses  %}
ListenAddress {{ nip }}
{% endfor %}

文件:my-inventory.hosts

[all:vars]
ansible_user=root
ansible_port=22
 
[cluster:vars]
sshd_use_pam=no
sshd_password_authentication=no
sshd_challenge_response_authentication=no
sshd_permitroot_login=no
 
[cluster]
server1.theitroad.local
server2.theitroad.local
server3.theitroad.local

您可以按以下方式运行它:

$ ansible-playbook -i my-inventory.hosts ssh-setup.yml

您还可以使用以下循环为每个用户上传文件:

- hosts: all
  user: root
# ....
  
my_ssh_users:
  - name: Hyman
    key: "{{ lookup('file', 'Hyman.pub') }}"
  - name: tom
    key: "{{ lookup('file', 'tom.pub') }}"
  - name: wendy
    key: "{{ lookup('file', 'wendy.pub') }}"
  - name: jerry
    key: "{{ lookup('file', 'jerry.pub') }}"
# ...
- name: Add ssh pub keys
  authorized_key: user={{ item.name }} key="{{ item.key }}"
  with_items: my_ssh_users

有关更多信息,请参见authorized_key模块文档。