김종명
김종명

Reputation: 101

How can I automatically generate file name with ansible-playbook?

I am using ansible-playbook to generate a package.

This task is started every morning, one time.

But sometimes I have to re-generate package.

At that time, (if i already generate package, and the package is in package directory), I hope to the second package has different name.

My code to generate a name of package is as bellows.

package_file_name: "NLUD_{{lookup('pipe','date +%Y%m%d')}}_0.tar.gz"

Then, the result of package name is "NLUD_%Y%m%d_0.tar.gz"

I hope to make a package which has a name "NLUD_%Y%m%d_1.tar.gz" in second time generation.

Upvotes: 0

Views: 951

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68084

Simply test the existence of the file and change the filename if the file exists. For example

    - set_fact:
        package_file_name: "NLUD_{{ lookup('pipe','date +%Y%m%d') }}_0.tar.gz"

    - stat:
        path: "{{ package_directory }}/{{ package_file_name }}"
      register: result

    - set_fact:
        package_file_name: "NLUD_{{lookup('pipe','date +%Y%m%d')}}_1.tar.gz"
      when: result.stat.exists

Upvotes: 0

mdaniel
mdaniel

Reputation: 33203

I'm pretty sure you can do that with the fileglob lookup:

- block:
  - name: sniff out existing filenames
    set_fact:
     file_suffix: '{{ (
        lookup("fileglob", package_pattern+"*.tar.gz", wantlist=True)
        | length) + 1 }}'
  - name: set the next sequential filename
    set_fact:
      package_file_name: '{{ package_pattern ~ file_suffix ~ ".tar.gz" }}'
  vars:
     package_pattern: NLUD_{{ lookup('pipe','date +%Y%m%d') }}_

Separately, while it might not matter to you, there's no need to shell out to do date formatting, the strftime filter will do that:

vars:
   package_pattern: NLUD_{{ "%Y%m%d" | strftime }}_

Upvotes: 0

Related Questions