首页 文章

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

提问于
浏览
1

我试图在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 %}

你能告诉我应该怎么写

3 回答

  • 1

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

    [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']
    

    记住它会为每个主机创建每一行 I think what are you looking for is acctually not looping but getting current host name (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创建的官方模块 . 像这样

    显示清单中的所有主机

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

  • 5

    这些方面的东西应该有效:

    - 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'] }}"
    

相关问题