Skip to content

Instantly share code, notes, and snippets.

@IvanBayan
Created October 31, 2019 09:28
Show Gist options
  • Save IvanBayan/99e374b5209111d2e28c9156611dbf26 to your computer and use it in GitHub Desktop.
Save IvanBayan/99e374b5209111d2e28c9156611dbf26 to your computer and use it in GitHub Desktop.
An example how to avoid race condition with lineinfile delegated to one host
---
- hosts: all
gather_facts: no
tasks:
- name: Create a virtual machine on given ESXi hostname
vmware_guest:
hostname: "{{ vcenter_address }}"
username: "{{ domain_user }}"
password: "{{ domain_pass }}"
datacenter: "{{ dc }}"
validate_certs: no
folder: Folder
name: "{{ inventory_hostname }}"
template: "{{ core_template }}"
state: present
guest_id: centos64Guest
esxi_hostname: "{{ esxi }}"
datastore: "{{ ds }}"
delegate_to: localhost
register: vm_deploy
- name: Grouping by vm_deploy
group_by:
key: vm_deploy
changed_when: no
# Magic happens below, lineinfile will interate over all hosts grouped by vm deploy task and
# construct lines based on hosts private variables
# Task delegated to one host and should be run once per play
- name: Updating cobler config template (ADD entries)
lineinfile:
line: "{{ (item.split('.'))[0] }} {{ hostvars[item]['ip_private'] }} {{ hostvars[item]['vm_deploy']['instance']['hw_eth0']['macaddress'] }} {{ cobbler_profile }}"
path: "/path/to/cobbler/template-{{ dc }}"
backup: no
register: cobler_config_add
delegate_to: "{{ cobbler[dc] }}"
become: yes
with_items: "{{ groups['vm_deploy'] }}"
run_once: yes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment