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

问题描述 投票:1回答:3

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

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

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

在剧本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 .

在我的节点中正确安装。但是对于配置,我需要编辑/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 %}

你能告诉我应该怎么写

ansible ansible-playbook
3个回答
6
投票

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

    [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 }}"

3
投票

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

show all the hosts in the inventory

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


1
投票

沿着这些方向的东西应该有效:

- 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'] }}"
© www.soinside.com 2019 - 2024. All rights reserved.