Ssh
設置 AuthorizedKeysFile 時如何通過 Ansible 添加 ssh 密鑰?
當我的/etc/ssh/sshd_config將AuthorizedKeysFile設置為*/etc/ssh/authorized_keys/%u時,如何讓 Ansible 填充正確的文件?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/root@backup.pub') }}" - name: nagios@host key : "{{ lookup('file', '../group_vars/pubkeys/root@nagios.pub') }}"
從文件中:
path: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 }}"
準備此功能有幾個步驟。首先,獲取參數的值。可能有更多選項,例如預設情況下
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
預設情況下,模組getent將數據庫密碼儲存在字典getent_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']