是否有一种方法可以忽略由Ansible做出的SSH真实性检查?例如,当我刚刚安装了一个新服务器时,我必须回答这个问题:
GATHERING FACTS ***************************************************************
The authenticity of host 'xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx)' can't be established.
RSA key fingerprint is xx:yy:zz:....
Are you sure you want to continue connecting (yes/no)?
我知道这通常是一个坏主意,但我将它合并到一个脚本中,该脚本首先在我的云提供商创建一个新的虚拟服务器,然后自动调用我的ansible playbook来配置它。我希望在脚本执行过程中避免任何人为干预。
将所有主机的host_key_checking更改为false是一个非常糟糕的主意。
你唯一想要忽略它的时候,是在“第一次接触”的时候,这本剧本将实现:
---
- name: Bootstrap playbook
# Don't gather facts automatically because that will trigger
# a connection, which needs to check the remote host key
gather_facts: false
tasks:
- name: Check known_hosts for {{ inventory_hostname }}
local_action: shell ssh-keygen -F {{ inventory_hostname }}
register: has_entry_in_known_hosts_file
changed_when: false
ignore_errors: true
- name: Ignore host key for {{ inventory_hostname }} on first run
when: has_entry_in_known_hosts_file.rc == 1
set_fact:
ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
# Now that we have resolved the issue with the host key
# we can "gather facts" without issue
- name: Delayed gathering of facts
setup:
因此,我们只在known_hosts文件中没有主机密钥时关闭主机密钥检查。
忽视检查是一个坏主意,因为它使你容易受到中间人的攻击。
我通过只添加每台机器的密钥一次并在Ansible中实际设置ok/更改状态来改善nikobelia的答案:
- name: Accept EC2 SSH host keys
connection: local
become: false
shell: |
ssh-keygen -F {{ inventory_hostname }} ||
ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
register: known_hosts_script
changed_when: "'found' not in known_hosts_script.stdout"
然而,Ansible在脚本运行之前就开始收集事实,这需要SSH连接,所以我们必须禁用这个任务或手动将它移到后面:
- name: Example play
hosts: all
gather_facts: no # gather facts AFTER the host key has been accepted instead
tasks:
# https://stackoverflow.com/questions/32297456/
- name: Accept EC2 SSH host keys
connection: local
become: false
shell: |
ssh-keygen -F {{ inventory_hostname }} ||
ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
register: known_hosts_script
changed_when: "'found' not in known_hosts_script.stdout"
- name: Gathering Facts
setup:
我一直无法解决的一个问题是,即使它只添加了一个键,它也会将所有内容标记为已更改。如果有人可以贡献一个修复,那将是伟大的!