Search code examples
ansible

how to set runtime global var in ansible-playbook


I wanted to set the global var "file_time_stamp" with runtime value of timestamp which will used across the ansible playbook. Any information on doing this would be very useful.

I am taking backup of db and restoring in docker container in Linux_system I am running playbook from linux_system as follow:

---
# global variables
file_time_stamp: "{{ now(utc=true,fmt='%Y-%m-%d_%H-%M-%S') }}"
- name: Dump db
  hosts: windows_server
  gather_facts: false
  tasks:
    - ansible.windows.win_shell: C:\xampp\mysql\bin\mysqldump.exe -h 127.0.0.1 -uroot -pmy-secret-pw my_repo > C:\Users\Administrator\Documents\mobile_{{ file_time_stamp }}.sql
- name: Copy the recent db dump for testing
  hosts: windows_server
  gather_facts: false
  tasks:
    - name: fetch file
      fetch: src=C:\Users\Administrator\Documents\mobile_{{ file_time_stamp }}.sql dest=/root/mobile_{{ file_time_stamp }}.sql flat=yes
- hosts: linux_system
  gather_facts: false
  tasks:
    - shell: docker exec -i some-mariadb1 mysql -u root --password=my-secret-pw  --database=my_repo < /root/mobile_{{ file_time_stamp }}.sql

Solution

  • There are two solutions for this case.

    • Using set_fact

    https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html

    This action allows setting variables associated to the current host. These variables will be available to subsequent plays during an ansible-playbook run via the host they were set on. Set cacheable to true to save variables across executions using a fact cache. Variables will keep the set_fact precedence for the current run, but will used ‘cached fact’ precedence for subsequent ones.

    - name: Evaluate
      tasks:
        - set_fact: file_time_stamp="{{ now(utc=true,fmt='%Y-%m-%d_%H-%M-%S') }}"
    
    - name: Some job
      hosts: windows_server
      tasks:
        - shell: echo {{file_time_stamp}} 
    
    - name: Another job
      hosts: linux_system
      tasks:
        - shell: echo {{file_time_stamp}} 
    
    • Using group_vars

    https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html#tips-on-where-to-set-variables

    Set common defaults in a group_vars/all file.