12

How can I pass a relative path so that Ansible can copy files from node/keys and copy them to a server?

The playbook is ansible/playbook.

My directory structure is:

├── ansible
│   ├── inventory
│   └── playbook
├── node
│   ├── keys
│   ├── index.js
│   ├── node_modules
│   ├── package-lock.json
│   └── utils
└── shell
    ├── data.json
    ├── create-data.sh
    ├── destory.sh
    └── firewall-rules.sh

Below is the playbook:

- hosts: all
  vars:
    source: "{{ source }}"
    destination: /home/ubuntu

  tasks: 

    - name: Copy files
      copy: 
        src:  "{{ source }}"
        dest: "{{ destination }}"

That's how I run:

ansible-playbook -i inventory/inventory.yaml playbook/crypto-generate.yaml
 --extra-vars "source=../node/keys"

I am trying to pass a relative path.

alex
  • 6,818
  • 9
  • 52
  • 103
TechChain
  • 8,404
  • 29
  • 103
  • 228

2 Answers2

32

I am using {{ playbook_dir }} to construct full path,see special ansible variables

- name: Copy files
  copy: 
    src:  "{{ playbook_dir }}/../../node/keys"
    dest: "{{ destination }}"
ozkolonur
  • 1,430
  • 1
  • 15
  • 22
-6

You can use absolute paths with src that avoids the problems of not knowing where is the root folder.

Local path to a file to copy to the remote server. This can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to the rsync command line tool.

https://docs.ansible.com/ansible/latest/modules/copy_module.html

Istvan
  • 7,500
  • 9
  • 59
  • 109
  • I don't want to have strict absolute path because i can put this script in any machine – TechChain Sep 12 '19 at 06:18
  • You do not have to. You can construct the absolute path very easily everywhere. – Istvan Sep 12 '19 at 09:10
  • But in that case i need to change ansible script everytime if i move my code. In assible how can i get i do that ? – TechChain Sep 12 '19 at 09:12
  • you can combine pwd + relative path without changing the code – Istvan Sep 12 '19 at 11:36
  • 2
    As Istvan says, like `ansible-playbook -i inventory/inventory.yaml playbook/crypto-generate.yaml --extra-vars "source=$(pwd)/../node/keys"`. – TNT Aug 02 '20 at 16:07