burning web fuel
burning web fuel

Reputation: 21

Is it possible to assign constant vars in Ansible playbook?

I want to execute some script on remote via Ansible and get result file from remote to host.

I wrote a playbook like below:

---
- name : script deploy
  hosts: all
  vars:
      timestamp: "{{ lookup('pipe', 'date +%Y%m%d%H%M%S') }}"
  become: true
  tasks:
    - name: script deployment
      script: ./exe.sh {{ansible_nodename}}_{{ timestamp }}
      args:
        chdir: /tmp

exe.sh successfully executed on remote and redirect result to output file like remote_20170806065817.data

Script execution takes a few seconds, and I tried to fetch result file after execution done.

But {{timestamp}} is re-evaluated and changed when I fetch it.

So fetch cannot find script-execution result file name.

What I want is assign immutable (constant) value in my playbook.

Is there any workaround?

Upvotes: 1

Views: 484

Answers (1)

techraf
techraf

Reputation: 68609

Ansible uses lazy evaluation, so variables are evaluated at the moment of their use.

You should set the fact, which will be evaluated once:

---
- name : script deploy
  hosts: all
  become: true
  tasks:
    - set_fact:
        timestamp: "{{ lookup('pipe', 'date +%Y%m%d%H%M%S') }}"

    - name: script deployment
      script: ./exe.sh {{ansible_nodename}}_{{ timestamp }}
      args:
        chdir: /tmp

Upvotes: 2

Related Questions