0

I want to use the "date" command output as an environment variable.

Suppose

- tasks:
   - name: Getting start date
     shell: date +%d%b%Y:%H:%M
     register: start_date
   - debug:
       vars: start_date.stdout
     environment: 
     start_date_env:  start_date.stdout

 - name: Echo my_env_var 
   shell: echo $start_date_env
   register: some
 - debug:
     var: some.stdout

O/P

changed: [host1]

cmd: date +%d%b%Y:%H:%M

stdout: 05Aug2018:09:30

TASK [Echo my_env_var] ***********************************************************************************************************************

cmd: echo $start_date_env
ok: [host1] => {
"some.stdout": ""

I want to run date command in the above mentioned format on the remote host, then save the variable possibly as environment on the target host. This is because I've to use this variable to grab some data at the end of execution of 3-4 playbooks.. the data will depend upon start_time of playbooks and end_time of playbook. Basically two environment variable start_time and end_time which I can use in the end

In short, is it possible to set output of one command executed on host as environment variable one the same host in ansible

2
  • can you provide more info. Commented Aug 5, 2018 at 12:20
  • Also, ansible gather_fact provides a date time info. ansible_date_time.date You could use that to simplify things. The only caveat is that gather-fact must be set to true. Commented Aug 24, 2018 at 16:18

1 Answer 1

3

You have almost all the necessary code, but you're were not using environment at the correct place

 - hosts: localhost
   tasks:
    - name: Getting start date
      shell: date +%b%Y%H%M
      register: start_date

    - debug:
        var: "{{ start_date.stdout }}"

    - name: Echo my_env_var
      shell: echo $start_date_env
      environment:
        start_date_env: start_date.stdout
      register: some
    - debug:
        var: "{{ some.stdout }}"

Note I have also to correct the indentation which was incorrect and replace vars by var in first debug task. As a general advice use ansible-playbook --syntax-check to validate your playbook.

Last thing: it's better to enclose ansible variable in "{{ }}"

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, i'm getting the error now:FAILED! => {"msg": "template error while templating string: unexpected char u'A' at 4. String: {{05Aug2018:20:01}}"}
The value of date +%d%b%Y:%H:%M is not a good example to register a varible, it contains digitals at the begining and : in the middle, changed to date +%b%Y%H%M works fine

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.