5

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
john
  • 11,311
  • 40
  • 131
  • 251

1 Answers1

3

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
dormi330
  • 1,273
  • 11
  • 18
  • How it will look like in my case? I am very new to ansible things so I don't know much. – john Jan 18 '17 at 20:15
  • http://docs.ansible.com/ansible/playbooks.html . it worth learning if you use ansible – dormi330 Jan 19 '17 at 01:36
  • sure but if you can help me explain with my answer, it will help me understand better. I will go through the link as well but there will be lot of things that now I don't need to understand as a beginner. – john Jan 19 '17 at 02:35
  • yaml file, host: centos means this will apply to centos group defined in /etc/ansible/hosts. tasks will execute one by one to all hosts in group. each task has a name( like copy-image), and a module to like (copy: src=xx,des=xx). – dormi330 Jan 19 '17 at 02:50