簡體   English   中英

Ansible循環變量

[英]Ansible loop over variables

我正在使用ansible來更新新添加的NIC的配置文件,因為我已經在單獨的yml文件中定義了一些變量

/tmp/ip.yml

#first interface
interface1: eth1
bootproto1: static
ipaddress1: 192.168.211.249
netmask1: 255.255.255.0
gateway: 192.168.211.2
DNS1: 192.168.211.2

#second interface
interface2: eth2
bootproto2: static
ipaddress2: 10.0.0.100
netmask2: 255.0.0.0

劇本

- include_vars: /tmp/ip.yml

- name: configuring interface 
  lineinfile:
    state=present
    create=yes
    dest=/etc/sysconfig/network-scripts/ifcfg-{{interface1}}
    regexp="{{ item.regexp }}"
    line="{{ item.line }}"
  with_items:
     - { regexp: '^BOOTPROTO=.*', line: 'BOOTPROTO={{interface1}}' }
     - { regexp: '^IPADDR=.*', line: 'IPADDR={{ipaddress1}' }
     - { regexp: '^NETMASK=.*', line: 'NETMASK={{netmask1}}' }
     - { regexp: '^GATEWAY=.*', line: 'GATEWAY={{gateway}}' }
     - { regexp: '^PEERDNS=.*', line: 'PEERDNS=no' }
     - { regexp: '^DNS1=.*', line: 'DNS1={{DNS1}}' }
     - { regexp: '^ONBOOT=.*', line: 'ONBOOT={{onboot}}' }
when: bootproto1 == 'static'

- name: configuring for DHCP
  lineinfile:
   state=present
   create=yes
   dest=/etc/sysconfig/network-scripts/ifcfg-{{interface1}}
   regexp="{{ item.regexp }}"
   line="{{ item.line }}"
  with_items:
    - { regexp: '^BOOTPROTO=.*',line: 'BOOTPROTO={{bootproto1}}' }
    - {regexp: '^PEERDNS=.*',line: 'PEERDNS=yes' }
    - { regexp: '^ONBOOT=.*', line: 'ONBOOT={{onboot}}' }
when: bootproto1 == 'dhcp'

類似地重復第二個界面。

即使這種方法適用於2個NIC,這也很難管理,即每增加一個新的NIC我需要修改playbook並更​​新/tmp/ip.yml中的相應變量。

有沒有辦法將變量添加到/tmp/ip.yml,並且可能正在使用某個分隔符將其解析為playbook,而不是每次都插入新的NIC來修改playbook。

這里有很多話要說。 首先,盡量避免像瘟疫這樣的lineinfile 這真的是最后的解決方案。 lineinfile使得編寫一致的和冪等的劇本變得很困難。

現在,由於您正在嘗試填充RH樣式的界面文件,因此很容易實現。

組織你的變量

首先要做的是為變量建立一個合適的結構。 你需要遍歷你的接口,所以你必須使東西“loopable”。 如上所述,擁有interface1interface2 ... interfaceN是不可擴展的。

這是一個建議:

interfaces_ipv4:
  - name: eth0
    bootproto: static
    ipaddress: 192.168.211.249
    netmask: 255.255.255.0
    gateway: 192.168.211.2
    dns: 192.168.211.2
  - name: eth2
    bootproto: static
    ipaddress: 10.0.0.100
    netmask: 255.0.0.0

寫下你的模板

現在您已擁有數據,您需要一個模板來創建操作系統配置文件。

BOOTPROTO={{item.bootproto}}
IPADDR={{item.ipaddress}}
NETMASK={{item.netmask}}
{% if item.gateway is defined %}
GATEWAY={{item.gateway}}
{% endif %}
PEERDNS=no
DNS1={{item.dns}}
ONBOOT={{item.onboot|default('no')}}

我包含了兩個變體:您可以在未設置時跳過輸出行( {% if ... %}構造)或提供默認值(例如{{item.onboot|default('no')}} )。

您的里程可能會有所不同,具體取決於您是否要使用默認值或跳過if結構。

創建一個任務

最后,這是一個為每個接口創建接口配置文件的任務:

- name: Push template
  template: 
    src=/path/to/the/above/template.j2
    dest=/etc/sysconfig/network-scripts/ifcfg-{{item.name}}.cfg
  with_items:
    - "{{ interfaces_ipv4 }}"

這應該做到這一切。

當然,使用此任務的最佳方法是將其添加到某個“網絡”角色,並從劇本中調用它。

祝好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM