user63898
user63898

Reputation: 30915

ansible how to file using varible containing the path from previous task

i have task inside ablock that downloads file from s3 which working fine , now i like it to copy it to another destination i like to use the dest value which constructed from variable and use it in the copy task but I'm getting error :

  - name: Handle
                      block:
                            - name: ansible create directory with mode setting example
                              vars:
                                name_dir: "{{ 1000 | random | to_uuid  }}"
                              file:
                                  path: "/home/ec2-user/backup/{{ name_dir }}/"
                                  state: directory

                            - name: Download from s3
                              vars:
                                 obj_name: "foo/xxxx.zip"
                                 file_name: "xxxx.zip"
                              local_action:
                                    module: aws_s3
                                    bucket: pack
                                    object: "{{ obj_name }}"
                                    dest: "/home/ec2-user/backup/{{ name_dir }}/{{ file_name }}"
                                    mode: get
                              register: awss3_dic


                             - name: Copy file to remote
                              copy:
                                src: "{{ awss3_dic.dest }}"
                                dest: "/home/ec2-user/2/"
                                remote_src: yes

                      rescue:
                            - debug:
                                    msg: 'I caught an error, can do stuff here to fix it, :-)'

the error is :

Friday 08 May 2020  06:37:18 +0000 (0:00:00.031)       0:00:03.225 ************
fatal: [localhost]: FAILED! =>
  msg: |-
    The task includes an option with an undefined variable. The error was: 'awss3_dic' is undefined

    The error appears to be in '/home/ec2-user/backup/test7.yml': line 37, column 27, but may
    be elsewhere in the file depending on the exact syntax problem.

    The offending line appears to be:


                            - name: Copy file to remote
                              ^ here

how can i use a variable in the copy src ?

Upvotes: -1

Views: 403

Answers (1)

user2700022
user2700022

Reputation: 509

This is because awss3_dic is not defined anywhere. You will have to define the path in a var & reuse it. Or you can use set_fact for setting it. Since you are already using the same path for an earlier task already , you can choose either of the above. the awss3 is a module in ansible, so you cannot use it like what you did. You can define all vars needed something like this & reuse them where ever needed:

vars:
    name_dir: "{{ 1000 | random | to_uuid }}"
    download_path: "/tmp/{{ name_dir }}"

Upvotes: 1

Related Questions