copy file and run a particular command using ansible?

9.5k Views Asked by At

I need to copy one file into lot of servers and then after copying execute a particular command. Below are the steps I need to do for each machine.

  • copy file into a server.
  • execute a command (sudo restart tree) after copying.
  • sleep for few seconds

And repeat above steps for all the machines.

So I decided to use ansible for this. I am able to copy files but I am not sure how can I execute command after copying and then sleep.

I have a hosts.txt file which will contain all the machines line by line.

I will login into machineA which will have my function.py file and hosts.txt file and from that machine I will run below ansible command.

david@machineA:~$ ansible -i hosts.txt -m copy -a "src=function.py dest=/treepot/function.py owner=goldy" -u david --ask-pass --sudo -U root --ask-sudo-pass all

With the use of above command, it will copy function.py file but I want to execute sudo restart tree command as well after copying that file on each server. So basically

  • copy file to machineB.
  • then execute the command (sudo restart tree)
  • after that sleep for few seconds and then do the same thing for other machines

Can I do this with the use of ansible? I am running ansible 1.5.4.

1

There are 1 best solutions below

4
dormi330 On BEST ANSWER

i suggest use ansible-playbook. here is my example, copy a docker image to 4 hosts, and load it then delete the tar file, maybe it help

cat /etc/ansible/hosts
#------------centos-----------  ip is ok(instead of hostname)
[centos]
centos-1
centos-2
centos-3
centos-4

[centos:vars]
ansible_user="root"

write a playbook

cat load-tar.yaml
- hosts: centos

  tasks:
    - name: copy-image
      copy: src=./elasticsearch.tar dest=/root/elasticsearch.tar

    - name: start docker
      shell: systemctl start docker

    - name: load-image
      shell: docker load < /root/elasticsearch.tar

    - name: delete-file
      file: path="/root/elasticsearch.tar" state=absent

and run it

ansible-playbook load-tar.yaml