[ssh_known_hosts] Use LDAP to deploy ssh_known_hosts

certbot_on_virtu
_benjamin 2021-02-18 14:36:34 +01:00 committed by Benjamin Graillot
parent 009e7b42cb
commit f4dd6fe242
2 changed files with 26 additions and 5 deletions

View File

@ -104,6 +104,23 @@ class LookupModule(LookupBase):
result.append(cn.decode('utf-8'))
return result
def ssh_keys(self, host):
"""
Retrieve SSH keys of a host
query('ldap', 'ssh_keys', HOST)
"""
host_query_id = self.base.search(f"cn={host},ou=hosts,{self.base_dn}", ldap.SCOPE_BASE)
host_result = self.base.result(host_query_id)[1][0][1]
result = []
if 'description' not in host_result:
return result
for description in host_result['description']:
description = description.decode('utf-8')
key, value = description.split(':', 1)
if key in {'ecdsa-sha2-nistp256', 'ssh-ed25519', 'ssh-dss', 'ssh-rsa'}:
result.append(f'{key} {value}')
return result
def subnet_ipv4(self, subnet):
"""
Retrieve used IP addresses on a subnet
@ -132,6 +149,8 @@ class LookupModule(LookupBase):
result = self.all_cn(*terms[1:])
elif terms[0] == 'subnet_ipv4':
result = self.subnet_ipv4(*terms[1:])
elif terms[0] == 'ssh_keys':
result = self.ssh_keys(*terms[1:])
elif terms[0] == 'group':
query_id = self.base.search(f"ou=group,{self.base_dn}", ldap.SCOPE_SUBTREE, "objectClass=posixGroup")
result = self.base.result(query_id)

View File

@ -1,7 +1,9 @@
{% for host in groups["server"] | sort %}
{% for keytype in ['ecdsa', 'rsa', 'ed25519'] %}
{% if 'ssh_host_key_{}_public'.format(keytype) in hostvars[host]['ansible_facts'].keys() %}
{{ query('ldap', 'all_cn', hostvars[host]['ansible_facts']['hostname']) | join(',') }},{{ query('ldap', 'all_ip', hostvars[host]['ansible_facts']['hostname']) | join(',') }} ssh-{{ keytype }} {{ hostvars[host]['ansible_facts']['ssh_host_key_{}_public'.format(keytype)] }} root@{{ hostvars[host]['ansible_facts']['hostname'] }}
{% endif %}
{{ ansible_header | comment }}
{% set hosts = query('ldap', 'query', 'ou=hosts,dc=crans,dc=org', 'one', 'objectClass=device') %}
{% for host, device in hosts.items() | sort(attribute='0') %}
{% set cns = query('ldap', 'all_cn', hosts[host].cn[0]) | sort %}
{% set ips = query('ldap', 'all_ip', hosts[host].cn[0]) | sort %}
{% for key in query('ldap', 'ssh_keys', hosts[host].cn[0]) | sort %}
{{ cns | join(',') }},{{ ips | join(',') }} {{ key }} root@{{ hosts[host].cn[0] }}
{% endfor %}
{% endfor %}