ansible使用各主機不同變量

首先需要創建host_vars.yml文件(可以根據需要建在任意位置)

/home/ops/ansible/vars/host_vars.yml

---
# vars file for node_exporter
hosts:
  - busi: zhudong
    machines:
      - ip: '10.96.19.'
        dc: jiangsu
      - ip: '12.76.242.'
        dc: shanxi1
      - ip: '11.84.27.'
        dc: chongqing
      - ip: '1.1.238.'
        dc: guangxi

一、只使用playbook

playbook.yml

---
- hosts: all
  remote_user: root
  gather_facts: no
  vars_files:
    - "/home/ops/ansible/vars/host_vars.yml"
  serial:
    - "10%"                       # 第一次執行10%,成功後再同時執行20%,最後100%
    - "20%"
    - "100%"
  tasks:
    - name: set fact
      set_fact:
        ip: "{{item.1.ip}}"
        dc: "{{item.1.dc}}"
        busi: "{{item.0.busi}}"
	  # 判斷字符串是否包含用“in”,精確匹配用“==”
      when: ("{{item.1.ip}}" in "{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}")
      with_subelements:
        - "{{hosts}}"
        - machines
	# 變量ip、dc、busi可以直接在模板或下邊的task中使用
    - name: send the telegraf config
      template:
        src: "{{ telegraf_conf_template }}"
        dest: /tmp/telegraf.conf
        owner: root
        group: root
        mode: 0644
    - name: create expoters folder
      file:
        path: /tmp/{{dc}}
        state: directory

二、在roles中使用

playbook.yml

---
- hosts: all
  remote_user: root
  gather_facts: no
  vars_files:
    - "/home/ops/ansible/vars/host_vars.yml"
  serial:
    - "10%"                       # 第一次執行10%,成功後再同時執行20%,最後100%
    - "20%"
    - "100%"
  roles:
    - roles/test

roles/install.yml

---
- name: set fact
  set_fact:
    ip: "{{item.1.ip}}"
    dc: "{{item.1.dc}}"
    busi: "{{item.0.busi}}"
  when: ("{{item.1.ip}}" in "{{ (ansible_ssh_host|default(ansible_host))|default(inventory_hostname) }}")
  with_subelements:
    - "{{hosts}}"
    - machines

- debug:
    msg: "busi: {{item.0.busi}}
          dc: {{item.1.dc}}
          ip: {{item.1.ip}}"
  with_subelements:
    - "{{hosts}}"
    - machines

- name: send the telegraf config
  template:
    src: "{{ telegraf_conf_template }}"
    dest: /tmp/telegraf.conf
    owner: root
    group: root
    mode: 0644
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章