11

In ansible, I would like to manipulate files/directories/archive that are composed or to composed like this:

How would I do that. It seem Ansible is not able to handler that. (I doubt). So, what I do wrong ?

Ex:

- name: create file with a date in name
  file: path=/path/somefile.`date +%y_%m_%d`

- name: unzip a file
  unarchive: path=/path/zomezip.`date +%y_%m_%d`.tar.gz bla bla....

3 Answers 3

21

Set a variable, then use it with Ansible's Jinja2 templating system (it looks like you're trying to do PHP with the dot operator and the backticks)

vars:
    date: "{{ lookup('pipe', 'date +%Y%m%d-%H%M') }}"
tasks:
  - name: create file with a date in name
    file: path="/path/somefile{{ date }}"

Or use the lookup itself in the templates:

  - name: create file with a date in name
    file: path="/path/somefile{{ lookup('pipe', 'date +%Y%m%d-%H%M') }}"
3
  • Yeah ! This is exactly what I was looking for ! Thank`s a lot !
    – yield
    Oct 13, 2015 at 16:26
  • 1
    one problem I had with this approach: the var seems to be more like a macro than a thing that executes once and caches. using it multiple times during one run and I got different answers. (this was from a var in a playbook)
    – tenpn
    Feb 21, 2017 at 11:39
  • 1
    @tenpn for that you would have to set fact (store into variable) like: - set_fact: my_time: "{{ lookup('pipe', 'date +%Y%m%d-%H%M') }}"
    – jhutar
    Jun 29, 2017 at 8:45
19

Starting with 2.4, you can also use the strftime filter (doc):

# Display year-month-day
{{ '%Y-%m-%d' | strftime }}

# Display hour:min:sec
{{ '%H:%M:%S' | strftime }}

# Use ansible_date_time.epoch fact
{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}

# Use arbitrary epoch value
{{ '%Y-%m-%d' | strftime(0) }}          # => 1970-01-01
0

You could try..

vars: 
  - a_timestamp: "{{ timestamp.stdout }}"

tasks:
  - name: Get a timestamp
    command: date +%Y%m%d%H%M%S
    register: timestamp

then add the variable where needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.