如何在 ansible 中循环遍历主机名或 IP

How to loop over hostnames or IPs in ansible

我正在尝试使用 Ubuntu 14.04 中的 Ansible 剧本设置和配置起搏器。

到目前为止,我只是在一个节点上测试它。因此在主机文件中我只保留了该节点的信息

[hostname]
1.2.3.4   ansible_ssh_private_key_file=/home/ubuntu/test.pem

我在 playbook YAML 文件中尝试安装和配置 pacemaker

- hosts: all
  sudo: yes
  tasks:
    - name: install pacemaker
      apt: name=pacemaker state=present
    - name: install corosync
      apt: name=corosync state=present
    - name: install fence-agents
      apt: name=fence-agents state=present
    #- copy: src=corosync_start dest=/etc/default/corosync
    #- shell: update-rc.d -f pacemaker remove
    #- shell: update-rc.d pacemaker start 50 1 2 3 4 5 . stop 01 0 6 .

正在我的节点中正确安装。但是对于配置,我需要编辑 /etc/corosync/corosync.conf,我需要在其中指定我的主机地址来代替 bindnetaddress.

假设我在 [hostname] 部分下有多个条目 - Ansible 中有没有什么方法可以在我的 YAML 文件中循环遍历它们?

我正在尝试使用 sed 命令替换 IP。你能解释一下如何循环或打印 IP 吗?

我这样试过

- hosts: all
  sudo: yes
  tasks:
    - debug: msg = "{{ ansible_hostname }}"
    - name: Test
      task: {% for host in groups['app_servers'] %}
            {{host}}
            {% endfor %}

抱歉让您误会了我的评论, 假设您有库存文件

    [ALL]
host1.com
host2.com

您的 yaml 文件应如下所示(使用 with_items)

- hosts: all
  sudo: yes
  tasks:
    - name: install pacemaker
      apt: name=pacemaker state=present
    - name: install corosync
      apt: name=corosync state=present
    - name: install fence-agents
      apt: name=fence-agents state=present
    - copy: src=corosync_start dest=/etc/default/corosync
    - lineinfile: dest=/etc/selinux/config line="my host {{ item }}"
      with_items: groups['ALL']

记住它会为每个主机创建每一行 我想你要找的实际上不是循环而是获取当前主机名 (ansible_hostname):

 - hosts: all
      sudo: yes
      gather_facts: yes
      tasks:
        - name: install pacemaker
          apt: name=pacemaker state=present
        - name: install corosync
          apt: name=corosync state=present
        - name: install fence-agents
          apt: name=fence-agents state=present
        - copy: src=corosync_start dest=/etc/default/corosync
        - lineinfile: dest=/etc/selinux/config line="my host {{ ansible_hostname }}"

按照这些思路应该可行:

- debug: msg="host is {{ item }}"
  with_items:  groups['app_servers']

这将为您提供清单中定义的每个主机的名称。如果你想要由 Ansible 事实(或主机的任何其他事实)提供的 FQDN,那么你想做这样的事情:

- debug: msg="host is {{ hostvars[item]['inventory_hostname'] }}"
  with_items:  "{{ groups['app_servers'] }}"

你可以使用ansible创建的这个官方模块。 像这样

显示清单中的所有主机

- debug: msg: "{{ item }}" with_inventory_hostnames: - all 参考Link
http://docs.ansible.com/ansible/latest/playbooks_loops.html#looping-over-the-inventory