Ansible: ¿Cómo copiar archivos, directorios o secuencias de comandos desde el host local al host remoto?
Publicado: 2019-02-24 Como parte del departamento de gestión de TI, la gente se ocupa de lots of scripts
y herramientas de línea de comandos. Estoy seguro de que se enfrenta a situaciones cotidianas en las que tiene que copiar archivos o scripts a miles de hosts remotos.
La gente del departamento de TI no solo inicia sesión en cada thousands of hosts
y ejecuta el script manualmente. Y es por eso que Ansible entra en escena. Ansible es una solución de administración de TI muy poderosa disponible para nosotros sin costo alguno.
En este tutorial, repasaremos los pasos para copiar archivos a un host remoto usando Ansible.
¿Qué vamos a hacer?
Copie el archivo crunchify.txt
desde la ubicación /opt/ashah/
al directorio de destino del host remoto 192.66.129.83
/opt/ashah/
.
Paso 1
Instale Ansible en Linux Ubuntu o macOS. Siga los tutoriales para repasar los pasos detallados.
Paso 2
Comprendamos algunos conceptos básicos y la ubicación del archivo para este tutorial:
- Ubicación del archivo de configuración: /etc/ansible/ansible.cfg
- Archivo de secuencia de comandos: /opt/ashah/crunchify.yml
- archivo de hosts: /opt/ashah/hosts
- archivo para copiar: /opt/ashah/crunchify.txt (archivo de prueba)
Paso 3
contenido del archivo crunchify.yml
.
1 2 3 4 5 6 7 8 |
root @ localhost : / opt / ashah # cat crunchify.yml --- - hosts : crunchify - group tasks : - name : copy file to remote host copy : src : / opt / ashah / crunchify . txt dest : / opt / ashah |
Etapa 4
hosts
el contenido del archivo. Asegúrese de cambiar la dirección IP a su host remoto.
1 2 3 4 |
root @ localhost : / opt / ashah # cat hosts #crunchify-group as a sample [ crunchify - group ] 192.66.129.83 |
Paso-5
Cree el archivo crunchify.txt
con el contenido a continuación.
1 2 3 4 |
root @ localhost : / opt / ashah # cat crunchify.txt This is sample example copying file to remote location using Ansible . More ansible tutorials at https : //crunchify.com/tag/ansible/ |
Paso-6
Ejecute este comando para copiar el archivo al host remoto:
-
Command
: ansible-playbook -b -vvv -u root crunchify.yml -kkkk –extra-vars “crunchify-group” -i hosts
entendamos todos los parámetros:
- -b : ejecuta operaciones con convertida (igual que —become).
- -vvv: modo detallado (-vvv para obtener más información, -vvvv para habilitar la depuración de conexiones).
- -u : conectarse como este usuario (predeterminado=Ninguno).
- -kkkk: solicita la contraseña de conexión.
- –extra-vars: establece variables adicionales como clave=valor o YAML/JSON, si el nombre del archivo se antepone con @.
- -i: especifique la ruta del host de inventario o la lista de hosts separados por comas.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
root @ localhost : / opt / ashah # ansible-playbook -b -vvv -u root crunchify.yml -kkkk --extra-vars "crunchify-group" -i hosts Using / etc / ansible / ansible . cfg as config file SSH password : / opt / ashah / hosts did not meet host_list requirements , check plugin documentation if this is unexpected / opt / ashah / hosts did not meet script requirements , check plugin documentation if this is unexpected Parsed / opt / ashah / hosts inventory source with ini plugin PLAYBOOK : crunchify . yml * ************************************************************************************************************************ 1 plays in crunchify . yml PLAY [ crunchify - group ] ********************************************************************************************************************************* TASK [ Gathering Facts ] ************************************************************************************************************************ < 192.66.129.83 > ESTABLISH SSH CONNECTION FOR USER : root < 192.66.129.83 > SSH : EXEC sshpass - d9 ssh - C - o ControlMaster = auto - o ControlPersist = 60s - o User = root - o ConnectTimeout = 10 - o ControlPath =/ root / . ansible / cp / 5fca43321f 192.66.129.83 '/bin/sh -c ' "'" 'echo ~root && sleep 0' "'" '' < 192.66.129.83 > ( 0 , '/root\n' , '' ) < 192.66.129.83 > ESTABLISH SSH CONNECTION FOR USER : root < 192.66.129.83 > SSH : EXEC sshpass - d9 ssh - C - o ControlMaster = auto - o ControlPersist = 60s - o User = root - o ConnectTimeout = 10 - o ControlPath =/ root / . ansible / cp / 5fca43321f 192.66.129.83 '/bin/sh -c ' "'" '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1550966284.57-6253496643791 `" && echo ansible-tmp-1550966284.57-6253496643791="` echo /root/.ansible/tmp/ansible-tmp-1550966284.57-6253496643791 `" ) && sleep 0' "'" '' < 192.66.129.83 > ( 0 , 'ansible-tmp-1550966284.57-6253496643791=/root/.ansible/tmp/ansible-tmp-1550966284.57-6253496643791\n' , '' ) Using module file / usr / lib / python2 . 7 / dist - packages / ansible / modules / system / setup . py < 192.66.129.83 > PUT / root / . ansible / tmp / ansible - local - 32435HXzj7o / tmpjFxUXp TO / root / . ansible / tmp / ansible - tmp - 1550966284.57 - 6253496643791 / AnsiballZ_setup . py < 192.66.129.83 > SSH : EXEC sshpass - d9 sftp - o BatchMode = no - b - - C - o ControlMaster = auto - o ControlPersist = 60s - o User = root - o ConnectTimeout = 10 - o ControlPath =/ root / . ansible / cp / 5fca43321f '[192.66.129.83]' < 192.66.129.83 > ( 0 , 'sftp> put /root/.ansible/tmp/ansible-local-32435HXzj7o/tmpjFxUXp /root/.ansible/tmp/ansible-tmp-1550966284.57-6253496643791/AnsiballZ_setup.py\n' , '' ) < 192.66.129.83 > ESTABLISH SSH CONNECTION FOR USER : root < 192.66.129.83 > ESTABLISH SSH CONNECTION FOR USER : root < 192.66.129.83 > SSH : EXEC sshpass - d9 ssh - C - o ControlMaster = auto - o ControlPersist = 60s - o User = root - o ConnectTimeout = 10 - o ControlPath =/ root / . ansible / cp / 5fca43321f 192.66.129.83 '/bin/sh -c ' "'" 'rm -f -r /root/.ansible/tmp/ansible-tmp-1550966284.57-6253496643791/ > /dev/null 2>&1 && sleep 0' "'" '' < 192.66.129.83 > ( 0 , '' , '' ) ok : [ 192.66.129.83 ] TASK [ deploy topology ] ******************************************************************************************************************************************** ok : [ 192.66.129.83 ] = > { "changed" : false , "checksum" : "289b0c36372210c92bf028f2a19d57333af4d63c" , "dest" : "/opt/ashah/crunchify.txt" , "diff" : { "after" : { "path" : "/opt/ashah/crunchify.txt" } , "before" : { "path" : "/opt/ashah/crunchify.txt" } } , "gid" : 0 , "group" : "root" , "invocation" : { "module_args" : { "_diff_peek" : null , "_original_basename" : "crunchify.txt" , "access_time" : null , "access_time_format" : "%Y%m%d%H%M.%S" , "attributes" : null , "backup" : null , "content" : null , "delimiter" : null , "dest" : "/opt/ashah" , "directory_mode" : null , "follow" : true , "force" : false , "group" : null , "mode" : null , "modification_time" : null , "modification_time_format" : "%Y%m%d%H%M.%S" , "owner" : null , "path" : "/opt/ashah/crunchify.txt" , "recurse" : false , "regexp" : null , "remote_src" : null , "selevel" : null , "serole" : null , "setype" : null , "seuser" : null , "src" : null , "state" : "file" , "unsafe_writes" : null } } , "mode" : "0644" , "owner" : "root" , "path" : "/opt/ashah/crunchify.txt" , "size" : 21 , "state" : "file" , "uid" : 0 } PLAY RECAP * ******************************************************************************************************************************************************* 192.66.129.83 : ok = 2 changed = 0 unreachable = 0 failed = 0 |
Eso es todo. Ha copiado correctamente el archivo.

¿Cómo verificar si el archivo se copia en un nuevo host remoto?
Simplemente inicie sesión en el host remoto y verifique la ubicación /opt/ashah
y verá el archivo crunchify.txt
¿Cómo copiar el contenido de un directorio a otro directorio?
Simplemente cambie el valor src
y desc
del archivo crunchify.yml
. Aquí hay un archivo crunchify.yml actualizado.
1 2 3 4 5 6 7 8 |
root @ localhost : / opt / ashah # cat crunchify.yml --- - hosts : crunchify - group tasks : - name : copy all files from folder to remote host copy : src : / opt / ashah / dest : / opt / ashah / |
Todos los archivos de la carpeta /opt/ashah/
se copiarán en hosts remotos ahora.
Avíseme si tiene alguna pregunta sobre cómo copiar el archivo a una ubicación remota usando Ansible.