Sudhir Jangam
Sudhir Jangam

Reputation: 776

Ansible copy file using command syntax

The assignment is as follows:

Lets create a file touch afile.txt, prior to creating tasks

Create a playbook test.yml to

copy afile.txt from your control machine to host machine at /home/ubuntu/ location as afile_copy.txt and debug the above task to display the returned value Execute your playbook (test.yml) and observe the output

I did following

  1. Created the afile_copy.txt using touch
  2. created the playbook as follows:

- name: copy files
  hosts: all
  tasks: 
    - name: copy file
      command: cp afile.txt /home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output

When I run the playbook using the command ansible-playbook -i myhosts test.yml it fails with the error message

stderr: cp: cannot stat 'afile.txt' : no such file or directory

The afile.txt is present in directory /home/scrapbook/tutorial

Upvotes: 0

Views: 4179

Answers (4)

DivyaSharma
DivyaSharma

Reputation: 1

---
- name: copy files
  hosts: all
  tasks: 
    - name: copy file
      copy: 
        src: afile.txt 
        dest: /home/ubuntu/afile_copy.txt
      register: output
    - debug: var=output

Upvotes: 0

Tiny
Tiny

Reputation: 743

Copy module should be used instead of command module

- name: copy files
  hosts: all
  tasks: 
    - name: copy file
      copy: src=afile.txt dest=/home/ubuntu/afile_copy.txt
      register:output
    - debug: var=output

Upvotes: 0

CSE Spy
CSE Spy

Reputation: 1

1)first execute the ad-hoc command for copy:

ansible all -i myhosts -m copy -a "src=afile.txt dest=/home/ubuntu/"

2) After execute the above command,execute this playbpook:

  • hosts: all
    tasks:

    • stat: path=/home/ubuntu/afile_copy.txt

      register: st

    • name: rename

      command: mv afile.txt /home/ubuntu/afile_copy.txt

      when: not st.stat.exists

      register: output

    • debug: var=output

Upvotes: 0

error404
error404

Reputation: 2833

You should use copy module instead of command module. command module executes on the remote node.

Upvotes: 1

Related Questions