如何在ansible中循环主机名或IPS

sri*_*ath 1 ansible ansible-playbook

我试图在ubuntu 14.04中使用ansible playbook设置和配置起搏器.

截至目前,我只是在1节点测试它.因此在hosts文件中我只保留了该节点的信息

[hostname]
1.2.3.4   ansible_ssh_private_key_file=/home/ubuntu/test.pem
Run Code Online (Sandbox Code Playgroud)

在剧本Yaml文件我试图安装以及配置起搏器

- 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 .
Run Code Online (Sandbox Code Playgroud)

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

假设在[hostname]部分下有超过1个条目有任何方式在ansible我可以在我的YAML文件中循环它们

我正在尝试使用sed命令来替换IP.但是,请你帮忙解决如何循环或打印Ips的问题.

我试过这样的

- hosts: all
  sudo: yes
  tasks:
    - debug: msg = "{{ ansible_hostname }}"
    - name: Test
      task: {% for host in groups['app_servers'] %}
            {{host}}
            {% endfor %}
Run Code Online (Sandbox Code Playgroud)

你能告诉我应该怎么写

maq*_*que 6

很抱歉让您对我的评论感到困惑,假设您有库存文件

    [ALL]
host1.com
host2.com
Run Code Online (Sandbox Code Playgroud)

你的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']
Run Code Online (Sandbox Code Playgroud)

请记住它会为每个主机创建每一行 我认为你在寻找的是实际上没有循环而是获得当前主机名(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 }}"
Run Code Online (Sandbox Code Playgroud)


Bru*_*e P 6

沿着这些思路的东西应该有效:

- debug: msg="host is {{ item }}"
  with_items:  groups['app_servers']
Run Code Online (Sandbox Code Playgroud)

这将为您提供清单中定义的每个主机的名称。如果您希望由 Ansible 事实(或主机的任何其他事实)提供 FQDN,那么您需要执行以下操作:

- debug: msg="host is {{ hostvars[item]['inventory_hostname'] }}"
  with_items:  "{{ groups['app_servers'] }}"
Run Code Online (Sandbox Code Playgroud)


小智 5

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

显示清单中的所有主机

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