Reputation: 71
I am having troubles when setting a variable with a timestamp in ansible to use it through my playbook. What I want to achieve is to have the release folder name in two servers and a new db tagged with the same timestamp.
I am defining these variables in a file called common.yml in /ansibleproject/vars/.
timestamp: "{{lookup('pipe', 'date +%Y%m%d%H%M%SZ')}}"
release_name: '{{ repo_tag }}_{{timestamp}}'
new_db_name: '{{release_name}}'
Then, on a task file I am creating the dirs like this:
- name: "Create new release folder"
file: path={{new_release_path}} state=directory mode=2775 owner=deployment group=deployment
become: yes
And on a separate task file I am creating the db like this:
- name: "Prepare db user rights"
shell: echo "CREATE DATABASE \`{{new_db_name}}\` CHARACTER SET utf8 COLLATE utf8_general_ci; " > db_create.sql
when: inventory_hostname == groups['app'][0]
- name: "Create new database for new release"
shell: mysql -h {{mysql_server}} -u{{mysql_username}} -p{{mysql_password}} < db_create.sql
when: inventory_hostname == groups['app'][0]
The folder is created with the same timestamp on the two servers I am deploying:
drwxrwsr-x 2 deployment deployment 4096 Mar 14 16:36 test_20170314173640Z/
but the db name has a different timestamp.
mysql> show databases;
+---------------------------------------------------------------+
| Database |
+---------------------------------------------------------------+
| information_schema |
| dummy |
| mysql |
| performance_schema |
| test_20170314173819Z |
+---------------------------------------------------------------+
I was reading about "set_fact" to set a timestamp, but that seems to work on a host basis.
Is there any way to have it consistent on both servers and on the db?
Regards,
Upvotes: 3
Views: 12027
Reputation: 68339
This is expected behaviour, because variables are templated when used, but not when "defined" (they are not defined actually).
So date +%Y%m%d%H%M%SZ
is executed for each task (at different time of cause).
If you need consistency, use set_fact
to make persistent fact:
- set_fact:
timestamp: "{{ lookup('pipe', 'date +%Y%m%d%H%M%SZ') }}"
After this timestamp
is a plain string with result of pipe, and not Jinja expression as it is in your case.
You can make this fact for every host or only for localhost
and access it as hostvars['localhost'].timestamp
from other hosts.
Upvotes: 8