Blog

Ansible Playbook copy file from local to remote

Photo by Gianluca Cinnante on Unsplash

Ansible is an open source IT automation project sponsored by Red Hat. Its a simple way to automate routine IT tasks. Recently I was working on a hadoop cluster and had to copy multiple files to multiple hosts. Ansible playbook comes to rescue . Although it took me few hours to understand the concept however it is worth the knowledge.

So here is my script ansible_copy.yaml

--- 
- 
  become: true
  hosts: all
  name: "My first play to copy files"
  tasks: 
    - 
      copy: 
        dest: /tmp/test.txt
        group: root
        mode: 272
        owner: root
        src: /home/ansiblescripts/test.txt
      name: "Example copying file with owner and permissions"


Next I created the yaml file and the inventory.txt which contains all the hostnames . Then i ran the playbook command which copied /home/ansiblescripts/test.txt file from my local host to all the remote hosts mentioned in inventory.txt . The file is copied as root owner in root group with 272 permission.

#Created a inventory.txt file which contains list of all the hosts where i wanted to copy the file
$ cat inventory.txt
dev.localhost.com
qa.loacalhost.com
$>ansible-playbook -i inventory.txt /home/ansiblescripts/ansible_copy.yaml --user=himanshu -k --become-user=root --ask-become-pass

If you are a complete beginner then let me tell you first you need to install ansible on your system . I prefer a linux host where i keep all my scripts and run them for testing purpose.

Here are steps to install ansible

#Check if ansible is already installed
$>which ansible
#It ansible doesn't exist then proceed forwad
$>su - root
$>cd /opt
$>mkdir ansible
$>cd ansible
$>yum -y install ansible
$>Installed:
  ansible.noarch 0:2.9.27-1.el7
#If the installation fails in the end with error something like
#GPG key retrieval failed: [Errno 14] curl#37 - "Couldn't open file /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7"
#Then do the below steps
$>cd /etc/yum.repos.d
$>vi epel.repo
#edit the two lines below 
#1) gpgcheck = 0
#2) #gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 <this variable needs to be commented
#Now run the yum install command
$>which ansible
  /bin/ansible

Leave a Reply