Asible将stdout_line拆分为数组元素

时间:2017-06-28 15:55:47

标签: ansible

当我使用此代码时,它的打印主机名和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 }}"
    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

  

when:not item =='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

1 个答案:

答案 0 :(得分: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 }}"

第一个任务循环遍历清单中除localhost之外的所有主机,并获取主机的当前rsa指纹及其IP地址。

第二个任务确保目标文件中的行和ssh-keyscan提取的行匹配。