jenkins Ansible known_hosts模块ssh密钥传播问题

8nuwlpux  于 2023-10-17  发布在  Jenkins
关注(0)|答案(2)|浏览(129)

我试图制作一个剧本,将更新一台机器/用户的known_hosts,但我得到了一个错误,我无法理解。

---
- name: Keys
  hosts: adminslaves
  gather_facts: false
  no_log: false
  remote_user: test
  #pre_tasks:
  #  - setup:
  #     gather_subset:
  #      - '!all'
  tasks:
    - name: Scan for SSH host keys.
      shell: ssh-keyscan myhost.mydomain.com 2>/dev/null
      changed_when: False
      register: ssh_scan

      #    - name: show vars
      #      debug:
      #        msg: "{{ ssh_scan.stdout_lines }}"
      #

    - name: Update known_hosts.
      known_hosts:
        key: "{{ item }}"
        name: "{{ ansible_host }}"
        state: present
      with_items: "{{ ssh_scan.stdout_lines }}"

我的错误是"msg": "Host parameter does not match hashed host field in supplied key"}
我认为变量有正确的信息(至少在我调试它时是这样)。
我的最终目标是一个剧本,将添加主机列表的ssh键到Jenkins auth的主机列表中。
感谢任何帮助。

9lowa7mx

9lowa7mx1#

问题是ssh-keyscan myhost.mydomain.com 2>/dev/null的输出通常包含多个键,因此您需要处理它。有一个人出现了同样的错误消息issue,但问题还是出在ssh-key格式上。我更好地理解了检查known_hosts任务使用的code
这里我使用的代码是:用途:

- name: Populate known_hosts
  hosts: spectrum_scale
  tags: set_known_hosts
  become: true
  tasks:
  - name: Scan for SSH keys
    ansible.builtin.shell:
      cmd: "ssh-keyscan {{ hostvars[spectrum_scale].ansible_fqdn }} 
              {{ hostvars[spectrum_scale].ansible_hostname }} 
              {{ hostvars[spectrum_scale].ansible_default_ipv4.address }} 
              2>/dev/null"
    loop: "{{ groups['spectrum_scale'] }}"
    loop_control:
      loop_var: spectrum_scale
    register: ssh_scan

  - name: Set stdout_lines array for ssh_scan
    set_fact:
      ssout: []
  
  - name: Fill ssout
    set_fact:
      ssout: "{{ ssout + ss_r.stdout_lines }}"
    loop: "{{ ssh_scan.results }}"
    loop_control:
      loop_var:
        ss_r
    when: ss_r.stdout_lines is defined

  - name: Add client ssh keys to known_hosts
    ansible.builtin.known_hosts:
      name: "{{ hk.split()[0] }}"
      key: "{{ hk }}"
      state: present
    loop: "{{ ssout }}"
    loop_control:
      loop_var: hk
50few1ms

50few1ms2#

此小剧本将主机密钥分配给指定目标主机/组(TARGETS)上的特定用户(SOME_USER)的known_hosts。所需的密钥类型可以通过keytype变量指定。
这将使用收集的ansible_facts和playbook运行的开始。
回到这个问题,这并没有直接回答它。但我认为它可以增强。你可以例如。修改循环变量,将myhost.mydomain.com添加到目标中,等等。

- hosts: TARGETS
  vars:
    keytype: ed25519
  tasks:
    - ansible.builtin.known_hosts:
        name: "{{ item }}"
        key: "{{ item }} {{ hostvars[item]['ansible_facts']['ssh_host_key_' + keytype + '_public_keytype'] }} {{ hostvars[item]['ansible_facts']['ssh_host_key_' + keytype + '_public'] }}"
        state: present
      when: "item != inventory_hostname"
      loop: "{{ ansible_play_hosts }}"
      become: yes
      become_user: SOME_USER

相关问题