Ansible-Playbook

使用 ansible 使用者模組創建使用者和 sshkey

  • February 7, 2021

我想創建一些本地和遠端使用者並為各個使用者生成 ssh 密鑰對並將它們傳輸到遠端伺服器,但似乎本地使用者 - ansible - 執行 ansible-playbook 無權訪問 /home/USERNAME/.ssh/id_rsa.pub

TASK [copy ssh key to destination users] ***************************************************************************************************
task path: /home/ansible/project1/setup-user.yaml:21
Read vars_file 'vars/users.yaml'
Read vars_file 'vars/groups.yaml'
[WARNING]: Unable to find '/home/zahr1/.ssh/id_rsa.pub' in expected paths (use -vvvvv to see paths)
File lookup using None as file
fatal: [localhost]: FAILED! => {
   "msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /home/zahr1/.ssh/id_rsa.pub"
}
[WARNING]: Unable to find '/home/zahr1/.ssh/id_rsa.pub' in expected paths (use -vvvvv to see paths)
File lookup using None as file
fatal: [ansible1]: FAILED! => {
   "msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /home/zahr1/.ssh/id_rsa.pub"
}

如果您讓我知道解決方案,我將不勝感激。

您可以將公鑰直接複製到您的劇本中。例如:

- name: Set authorized key
 ansible.posix.authorized_key:
   user: zahr1
   state: present
   key: "ssh-ed25519 AAAAA.....0 zahr1@localhost"

您還可以指定多個鍵。

- name: Set authorized key
 ansible.posix.authorized_key:
   user: zahr1
   state: present
   key: "{{ item }}"
 loop:
   - "ssh-ed25519 AAAAA.....1 zahr1@localhost"
   - "ssh-rsa AAAAA.....2 zahr1@localhost"
   - "ssh-dsa AAAAA.....3 zahr1@localhost"

請注意,這ansible.posix.authorized_key適用於 Ansible 2.10 及更高版本(請參閱其文件,因為它必須與 分開安裝ansible-galaxy)。舊版本的 Ansible 將使用現已棄用的authorized_key.

引用自:https://serverfault.com/questions/1035449