2017-06-28 46 views
0

當我使用此代碼時,它的打印主機名和ip地址分兩行顯示。Asible將stdout_line拆分爲數組元素

- name: Store known hosts of 'all' the hosts in the inventory file 
    hosts: localhost 
    connection: local 

    vars: 
    ssh_known_hosts_command: "ssh-keyscan -T 10" 
    ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}" 
    ssh_known_hosts: "{{ groups['all'] }}" 

    tasks: 
    - name: For each host, find the ip 
    shell: 'echo -e "{{ item }}\n`dig +short {{ item }}`"' 
    with_items: "{{ ssh_known_hosts }}" 
    register: ssh_known_host_results 
    ignore_errors: yes 

    - name: print message 
    debug: 
     msg: "{{ item + ' test' }}" 
    with_items: "{{ ssh_known_host_results.results | map(attribute='stdout_lines') | list }}" 

如果我添加邏輯忽略本地主機

時:不項== 'localhost' 的

,其不劈裂主機名和IP地址作爲陣列線,它主機名爲& ip爲一行。

- name: Store known hosts of 'all' the hosts in the inventory file 
    hosts: localhost 
    connection: local 

    vars: 
    ssh_known_hosts_command: "ssh-keyscan -T 10" 
    ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}" 
    ssh_known_hosts: "{{ groups['all'] }}" 

    tasks: 
    - name: For each host, find the ip 
    shell: 'echo -e "{{ item }}\n`dig +short {{ item }}`"' 
    with_items: "{{ ssh_known_hosts }}" 
    when: not item == 'localhost' 
    register: ssh_known_host_results 
    ignore_errors: yes 

    - name: print message 
    debug: 
     msg: "{{ item + ' test' }}" 
    with_items: "{{ ssh_known_host_results.results | map(attribute='stdout_lines') | list }}" 

如何分割數組元素與條件?

感謝 SR

+0

我敢打賭,這是[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。例如,有[dig](http://docs.ansible.com/ansible/playbooks_lookups.html#the-dns-lookup-dig)查找。 –

+0

@KonstantinSuvorov,我的想法是獲取主機名和IP地址,並從know_hosts文件中刪除舊密鑰條目,並將新密鑰添加到已知主機文件。挖看不起這種情況。 – sfgroups

+0

以下是可能的解決方案:爲每個主機運行'ssh-keyscan'命令(獲取當前指紋),循環槽註冊結果並使用'lineinfile'模塊更新known_hosts(如果需要)。 –

回答

0

我會後這個作爲答案,雖然這解決了保持與實際指紋同步know_hosts文件的原始任務,而不是OP的問題「我怎麼可以拆分數組元素與當條件?「:

--- 
- hosts: localhost 
    gather_facts: no 
    tasks: 
    - command: ssh-keyscan -t rsa {{ item }} {{ lookup('dig',item) }} 
     changed_when: false 
     with_items: "{{ groups['all'] | difference(['localhost']) }}" 
     register: current_keys 

    - lineinfile: 
     dest: /tmp/hhh 
     regexp: "^{{ item.split()[0] }}" 
     line: "{{ item }}" 
     with_items: "{{ current_keys.results | map(attribute='stdout_lines') | list }}" 

首要任務遍歷本地主機除外清單中的所有主機,並獲取主機的當前RSA指紋和它的IP地址。

第二個任務確保目標文件中的行和由ssh-keys提取的行匹配。

+0

這有幾個問題,如果dns不是有效的任務失敗,並且如果know_hosts有多行,它保持新密鑰的多行。我的原始腳本適用於2.3.0.0。只有低版本的我們有問題。 – sfgroups