使用 ansible 用户模块创建用户和 sshkey

使用 ansible 用户模块创建用户和 sshkey

我想创建一些本地和远程用户,并为相应的用户生成 ssh 密钥对,然后将它们传输到远程服务器,但运行 ansible-playbook 的本地用户 - ansible - 似乎无权访问 /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"
}

如果您能告诉我解决方案我将非常感激。

答案1

你可以将公钥直接复制到你的剧本中。例如:

- 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

答案2

Ansible authorized_key 似乎不使用 become_user,因此无法访问用户的 .ssh 文件夹。解决方案:将文件复制<user>/.ssh/id_rsa.pub到某个/tmp位置(作为 root/become_user),然后使用 authorized_keys 在 /tmp 文件夹中查找。以下是执行此工作的临时命令。在 playboook 中添加带有复制模块的任务。(首先,export PASS=mysecret除非您想用并输入 5 次密码替换-e额外的参数)-k

首先在 ansible 控制主机上创建新用户并生成新的 ssh 密钥

ansible localhost -m user -a "name=${a_new_user} generate_ssh_key=true"  \
-b -e "ansible_become_pass=${PASS}"

在所有主机上也创建此用户

ansible all -m user -a "name=${a_new_user}" -b -e  \
"ansible_become_pass=${PASS}"

将刚刚创建的公钥复制到authorized_key命令可以访问的位置

sudo cp -p /home/${a_new_user}/.ssh/id_rsa.pub /tmp/

现在,authorized_key 可以在 authorized_key 文件中添加所有主机上的公钥,但现在在 /tmp 文件夹中查找

ansible all -m authorized_key -a "user=${a_new_user} \
key={{ lookup('file', '/tmp/id_rsa.pub') }}" -b \
-e "ansible_user_passwd=${PASS}"

确保新添加的用户可以无需密码进行 sudo

ansible all -m lineinfile -a "path=/etc/sudoers state=present \
line='${a_new_user} ALL=(ALL) NOPASSWD: ALL' \
validate='/usr/sbin/visudo -cf %s'" -b \
-e "ansible_become_pass=${PASS}"

相关内容