当设置了 AuthorizedKeysFile 时,如何通过 Ansible 添加 ssh 密钥?

当设置了 AuthorizedKeysFile 时,如何通过 Ansible 添加 ssh 密钥?

当我的/etc/ssh/sshd_config授权密钥文件设置SSH 密钥对? Ansible 似乎忽略了设置并将密钥放在$HOME/.ssh/authorized_keys

剧本

---
- hosts: all
  vars:
  vars_files:
    - ../group_vars/ssh_root_authorized_keys.yml
  gather_facts: false

  tasks:
    - name: Set up multiple authorized keys
      authorized_key:
        user: root
        state: present
        key: '{{ item.key }}'
      with_items: "{{ root_auth_keys }}"

ssh_root_authorized_keys.yml

root_auth_keys:
  - name: backup@host
    key : "{{ lookup('file', '../group_vars/pubkeys/[email protected]') }}"

  - name: nagios@host
    key : "{{ lookup('file', '../group_vars/pubkeys/[email protected]') }}"

答案1

来自文档

路径:authorized_keys 文件的备用路径

  tasks:
    - name: Set up multiple authorized keys
      authorized_key:
        user: root
        state: present
        key: '{{ item.key }}'
        path: '/etc/ssh/authorized_keys/root'
      with_items: "{{ root_auth_keys }}"

答案2

准备此功能有几个步骤。首先,获取参数的值。可能还有更多选项,例如默认

shell> sudo sshd -T | grep authorizedkeysfile
authorizedkeysfile .ssh/authorized_keys .ssh/authorized_keys2

例如,获取第一个

    - shell: sshd -T | grep authorizedkeysfile
      register: result
      become: true
    - set_fact:
        AuthorizedKeysFile: "{{ (result.stdout|split)[1] }}"

给出

  AuthorizedKeysFile: .ssh/authorized_keys

参数 AuthorizedKeysFile 可能包含%u%h。请参阅授权密钥文件的位置

%h 将被替换为正在验证的用户的主目录,%u 将被替换为用户的登录名

准备主目录的数据库

    - getent:
        database: passwd

默认情况下,模块盖特恩存储数据库密码在字典里获取密码. Home 是第四个属性,例如

    - debug:
        var: getent_passwd['root'][4]

给出

  getent_passwd['root'][4]: /root

现在,根据数据

    auth_keys:
      root: [key1, key2, key3]

您可以测试功能

    - shell: sshd -T | grep authorizedkeysfile
      register: result
      become: true
    - set_fact:
        AuthorizedKeysFile: "{{ (result.stdout|split)[1] }}"
    - getent:
        database: passwd
    - debug:
        msg: |
          path: {{ _path }}
          keys: {{ item.value }}
      loop: "{{ auth_keys|dict2items }}"
      vars:
        _user: "{{ item.key }}"
        _home: "{{ getent_passwd[item.key][4] }}"
        _akf: "{{ AuthorizedKeysFile|regex_replace('%u', _user)|
                                     regex_replace('%h', _home) }}"
        _path: "{{ (_akf.0 == '/')|ternary(_akf, [_home, _akf]|join('/')) }}"

给出

  msg: |-
    path: /root/.ssh/authorized_keys
    keys: ['key1', 'key2', 'key3']

如果更改参数

shell> sudo sshd -T | grep authorizedkeysfile
authorizedkeysfile /etc/ssh/authorized_keys/%u

该游戏将获取授权密钥文件的正确位置

  msg: |-
    path: /etc/ssh/authorized_keys/root
    keys: ['key1', 'key2', 'key3']

相关内容