![](/img/trans.png)
[英]Ansible-Inventory AWS_EC2 plugin how to show hostnames and private ips
[英]How to loop over hostnames or IPs in ansible
我正在嘗試在 Ubuntu 14.04 中使用 Ansible playbook 設置和配置起搏器。
到目前為止,我只是在一個節點上測試它。 因此在主機文件中我只保留了該節點的信息
[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 在其中我需要指定我的 Host 地址來代替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 }}"
你可以使用 ansible 創建的這個官方模塊。 像這樣
- debug: msg: "{{ item }}" with_inventory_hostnames: - all
參考鏈接
http://docs.ansible.com/ansible/latest/playbooks_loops.html#looping-over-the-inventory
沿着這些路線的東西應該工作:
- 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'] }}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.