Nishant Singh Nishant Singh - 1 year ago 89
Bash Question

How to extract file name from shell command from a ansible play

I am taking a db dump as follows:

- name: create backup of the EMS database
  shell: " mysqldump --single-transaction --triggers --routines --events --hex-blob --complete-insert -h {{groups.db_name[0]}} -u {{ db_user }} -p{{ db_password }} {{ db_name }} > {{ vars.inventory_dir }}/../{{ db_name}}_backup-{{ ansible_date_time.iso8601 }}.sql"
  register: db_backup

now if you notice the shell command at the end i dump the mysql with a date-time appended as
{{ db_name}}_backup-{{ ansible_date_time.iso8601 }}.sql

How can i use only this dynamic part in my next play ?

Answer Source

I suggest you first store the filename as a fact:

- set_fact:
    mysql_dump_file: "{{ db_name }}_backup-{{ ansible_date_time.iso8601 }}.sql"

Then in the dump task and all following tasks where you need the filename you use that fact: {{ mysql_dump_file }}

- name: create backup of the EMS database
  shell: "mysqldump --single-transaction --triggers --routines --events --hex-blob --complete-insert -h {{ groups.db_name[0] }} -u {{ db_user }} -p{{ db_password }} {{ db_name }} > {{ vars.inventory_dir }}/../{{ mysql_dump_file }}"
  register: db_backup