我尝试在远程主机上运行初始剧本,即设置SSH公钥。问题是,如果没有SSH,我将无法连接。我尝试了类似的方法,但是它不起作用。
- hosts: remote_host
become: yes
become_user: mongod
become_method: sudo
become_exe: "sudo su - "
tasks:
- name: Add public ssh keys
lineinfile:
path: /home/mongod/.ssh/authorized_keys
owner: mongod
group: mongod
mode: '0600'
state: present
line: "{{ item }}"
loop:
- "ssh-rsa AAAAB3NzaC1yc2E...= domscheit@ansible_host"
请注意,sudo su - mongod
是我可以以用户domscheit
身份运行的 only 命令。我没有用户mongod
的密码,因此无法直接将其用于连接。上面的剧本返回类似FAILED! => {"msg": "Missing sudo password"}
实际上我找到了解决方法:
- hosts: remote_host
tasks:
- name: Add public ssh-key to authorized_keys
shell: |
sudo su - mongod <<< "mkdir --mode=700 /home/mongod/.ssh"
sudo su - mongod <<< "echo ssh-rsa AAAAB3Nza...= domscheit@ansible_host >> /home/mongod/.ssh/authorized_keys"
sudo su - mongod <<< "chmod 600 /home/mongod/.ssh/authorized_keys"
args:
executable: /bin/bash
它正在工作,但是应该有一个更好的解决方案。它创建[WARNING]: Consider using 'become', 'become_method', and 'become_user' rather than running sudo
设置了公共ssh密钥后,我可以使用--user mongod
继续实际的剧本。
答案 0 :(得分:0)
就像@chelmertz提到的那样,您不需要(甚至您不应该)通过cmd或其他方式回显SSH密钥。为此,确实有一个authorized_key
模块。它会注意适当的特权,而不会保护特权,因此您的密钥不仅会添加,而且会按预期工作。
使用仅mongod
为用户become: yes
添加ssh键的任务来运行剧本:
- hosts: remote_host
become: yes
tasks:
- name: Set authorized key taken from file
authorized_key:
user: mongod
state: present
key: "{{ lookup('file', '/path/to/your/pub/key/id_rsa.pub') }}"