[greg@control ansible]$ vim /home/greg/ansible/lv.yml --- - name: 创建和使用逻辑卷 hosts: all tasks: - block: - name: Create a logical volume of 1500m lvol: vg: research lv: data size: 1500m - name: Create a ext4 filesystem on /dev/research/data filesystem: fstype: ext4 dev: /dev/research/data rescue: - debug: msg: Could not create logical volume of that size - name: Create a logical volume of 800m lvol: vg: research lv: data size: 800m when: ansible_facts['lvm']['vgs']['research'] is defined - debug: msg: Volume group does not exist when: ansible_facts['lvm']['vgs']['research'] is undefined [greg@control ansible]$ ansible-playbook lv.yml
[greg@control ansible]$ vim /home/greg/ansible/partition.yml --- - name: 创建和使用分区 hosts: all tasks: - block: - name: Create a new primary partition with a size of 1500MiB parted: device: /dev/vdb number: 1 state: present part_end: 1500MiB - name: Create a ext4 filesystem on /dev/vdb1 filesystem: fstype: ext4 dev: /dev/vdb1 - name: Mount /data mount: path: /data src: /dev/vdb1 fstype: ext4 state: mounted when: inventory_hostname in groups.prod rescue: - debug: msg: Could not create partition of that size - name: Create a new primary partition with a size of 800MiB parted: device: /dev/vdb number: 1 state: present part_end: 800MiB when: ansible_facts['devices']['vdb'] is defined - debug: msg: this disk is not exist when: ansible_facts['devices']['vdb'] is undefined [greg@control ansible]$ ansible-playbook partition.yml
使用魔法变量
最常用的有四个:
hostvars
包含受管主机的变量,可以用于获取另一台受管主机的变量的值。
group_names
列出当前受管主机所属的所有组。
groups
列出清单中的所有组和主机。
inventory_hostname
包含清单中配置的当前受管主机的主机名称。
ansible localhost -m debug -a 'var=hostvars["localhost"]'