Ansible копирование нескольких файлов
The copy module copies a file from the local or remote machine to a location on the remote machine.
Use the fetch module to copy files from remote locations to the local box.
If you need variable interpolation in copied files, use the template module. Using a variable in the content field will result in unpredictable output.
For Windows targets, use the win_copy module instead.
Notes
The ansible.builtin.copy module recursively copy facility does not scale to lots (>hundreds) of files.
Parameters¶
Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
If dest is a non-existent path and if either dest ends with "/" or src is a directory, dest is created.
If src and dest are files, the parent directory of dest is not created and the task fails if it does not already exist.
The mode is only set on directories which are newly created, and will not affect those that already existed.
For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like 0644 or 01777 )or quote it (like '644' or '1777' ) so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results.
As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, u+rwx or u=rw,g=r,o=r ).
If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to the rsync command line tool.
Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file.
By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted files, which cannot be updated atomically from inside the container and can only be written in an unsafe manner.
This option allows Ansible to fall back to unsafe methods of updating files when atomic operations fail (however, it doesn't force Ansible to perform unsafe writes).
The path to the file to validate is passed in via '%s' which must be present as in the examples below.
Return Values¶
Common return values are documented here , the following are the fields unique to this module:
How can I copy more than a single file into remote nodes by Ansible in a task?
I've tried to duplicate the copy module line in my task to define files but it only copies the first file.
Parameters
attributes
added in 2.3 of ansible.builtin
The attributes the resulting filesystem object should have.
To get supported flags look at the man page for chattr on the target system.
This string should contain the attributes in the same order as the one displayed by lsattr.
The = operator is assumed as default, otherwise + or - operators need to be included in the string.
backup
added in 0.7 of ansible.builtin
Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
checksum
added in 2.5 of ansible.builtin
SHA1 checksum of the file being transferred.
Used to validate that the copy of the file was successful.
If this is not provided, ansible will use the local calculated checksum of the src file.
content
added in 1.1 of ansible.builtin
When used instead of src , sets the contents of a file directly to the specified value.
Works only when dest is a file. Creates the file if it does not exist.
For advanced formatting or if content contains a variable, use the ansible.builtin.template module.
decrypt
added in 2.4 of ansible.builtin
This option controls the autodecryption of source files using vault.
dest
Remote absolute path where the file should be copied to.
If src is a directory, this must be a directory too.
If dest is a non-existent path and if either dest ends with “/” or src is a directory, dest is created.
If dest is a relative path, the starting directory is determined by the remote host.
If src and dest are files, the parent directory of dest is not created and the task fails if it does not already exist.
directory_mode
added in 1.5 of ansible.builtin
When doing a recursive copy set the mode for the directories.
If this is not set we will use the system defaults.
The mode is only set on directories which are newly created, and will not affect those that already existed.
follow
added in 1.8 of ansible.builtin
This flag indicates that filesystem links in the destination, if they exist, should be followed.
force
added in 1.1 of ansible.builtin
Influence whether the remote file must always be replaced.
If yes , the remote file will be replaced when contents are different than the source.
If no , the file will only be transferred if the destination does not exist.
Alias thirsty has been deprecated and will be removed in 2.13.
group
Name of the group that should own the filesystem object, as would be fed to chown.
local_follow
added in 2.4 of ansible.builtin
This flag indicates that filesystem links in the source tree, if they exist, should be followed.
mode
The permissions of the destination file or directory.
For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must either add a leading zero so that Ansible’s YAML parser knows it is an octal number (like 0644 or 01777 ) or quote it (like '644' or '1777' ) so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results.
As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, u+rwx or u=rw,g=r,o=r ).
As of Ansible 2.3, the mode may also be the special string preserve .
preserve means that the file will be given the same permissions as the source file.
When doing a recursive copy, see also directory_mode .
If mode is not specified and the destination file does not exist, the default umask on the system will be used when setting the mode for the newly created file.
If mode is not specified and the destination file does exist, the mode of the existing file will be used.
Specifying mode is the best way to ensure files are created with the correct permissions. See CVE-2020-1736 for further details.
owner
Name of the user that should own the filesystem object, as would be fed to chown.
remote_src
added in 2.0 of ansible.builtin
Influence whether src needs to be transferred or already is present remotely.
If no , it will search for src on the controller node.
If yes it will search for src on the managed (remote) node.
remote_src supports recursive copying as of version 2.8.
remote_src only works with mode=preserve as of version 2.6.
Autodecryption of files does not work when remote_src=yes .
selevel
The level part of the SELinux filesystem object context.
This is the MLS/MCS attribute, sometimes known as the range .
When set to _default , it will use the level portion of the policy if available.
serole
The role part of the SELinux filesystem object context.
When set to _default , it will use the role portion of the policy if available.
setype
The type part of the SELinux filesystem object context.
When set to _default , it will use the type portion of the policy if available.
seuser
The user part of the SELinux filesystem object context.
By default it uses the system policy, where applicable.
When set to _default , it will use the user portion of the policy if available.
src
Local path to a file to copy to the remote server.
This can be absolute or relative.
If path is a directory, it is copied recursively. In this case, if path ends with “/”, only inside contents of that directory are copied to destination. Otherwise, if it does not end with “/”, the directory itself with all contents is copied. This behavior is similar to the rsync command line tool.
unsafe_writes
added in 2.2 of ansible.builtin
Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target filesystem object.
By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target filesystem objecs, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted filesystem objects, which cannot be updated atomically from inside the container and can only be written in an unsafe manner.
This option allows Ansible to fall back to unsafe methods of updating filesystem objects when atomic operations fail (however, it doesn’t force Ansible to perform unsafe writes).
IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
validate
The validation command to run before copying the updated file into the final destination.
A temporary file path is used to validate, passed in through ‘%s’ which must be present as in the examples below.
Also, the command is passed securely so shell features such as expansion and pipes will not work.
For an example on how to handle more complex validation than what this option provides, see Complex configuration validation.
See Also¶
The official documentation on the assemble module.
The official documentation on the fetch module.
The official documentation on the file module.
The official documentation on the synchronize module.
The official documentation on the template module.
The official documentation on the win_copy module.
15 Answers 15
You can use the with_fileglob loop for this:
This approach could help me if I've had all of my files in the same root for copying into remote machine, what about having some files in various directories. For example, I wanna copy 3 files from 3 different directory
Hey, I'm trying to move all the files from my /roles/db/files but I can't get it working with this method. I've tried with_fileglob: - /roles/db/file/* but it won't fine the path
Since Ansible 2.5 the with_* constructs are not recommended, and loop syntax should be used. A simple practical example:
On the page you linked it explicitly says that with_* is not deprecated: “We have not deprecated the use of with_ - that syntax will still be valid for the foreseeable future.” (As of 11/2021) They only recommend it.
Thank you for spotting that - the notice was not there before, it was added at some point in late 2019. Will amend the answer accordingly.
You can use with_together for this purpose:
If you need more than one location, you need more than one task. One copy task can copy only from one location (including multiple files) to another one on the node.
- name: copy file1 copy: src=/file1 dest=/destination/file1 - name: copy file2 copy: src=/file2 dest=/destination/file2
Depends. Simpler and likely cleaner, but can be done using more complex data structures, such as a list of anonymous dictionaries with source and target data, looped with_items. It's the same in any language - you have to make a judgment call. There are cases where a delegation function is more efficient and maintainable than a long series of copy/pasted if statements. I'm that freak that would rather maintain the concise bit of well structured code than a long and tedious list of nearly-identical directives, but I don't assume everyone agrees. Do what's maintainable for you.
Для копирования удаленных файлов на удаленные вы можете использовать модуль синхронизации с delegate_to: source-server ключевым словом ' ':
Этот сценарий может запускаться с вашего компьютера C.
хороший ответ! К сожалению, мне не удалось заставить его работать в среде Vagrant с несколькими виртуальными машинами. Похоже, Бродяга там делает что-то особенное.
Это фактически копирует файлы с serverB на serverA. Если вы хотите скопировать их с serverA на serverB, используйте mode=push (или delegate_to: serverB , но не оба).
@MariusGedminas, вы правы, mode=push следует использовать, но в этой ситуации delegate_to: serverB нельзя использовать, потому что это сделает serverB источник и место назначения.
Как уже указывал ant31, вы можете использовать synchronize для этого модуль. По умолчанию модуль передает файлы между управляющей машиной и текущим удаленным хостом ( inventory_host ), однако это можно изменить с помощью параметра задачи delegate_to (важно отметить, что это параметр задачи , а не модуля).
Вы можете разместить задачу на любом ServerA или ServerB , но вы должны соответствующим образом скорректировать направление передачи (с помощью mode параметра synchronize ).
Ставим задачу на ServerB
При этом используется значение по умолчанию mode: push , поэтому файл передается от delegate ( ServerA ) к текущему удаленному ( ServerB ).
Это может показаться странным, поскольку задача помещена в ServerB (через hosts: ServerB ). Однако следует иметь в виду, что задача на самом деле выполняется на делегированном хосте , которым в данном случае и является ServerA . Так что толкание (от ServerA к ServerB ) - действительно правильное направление. Также помните, что мы не можем просто отказаться от делегирования вообще, поскольку это будет означать, что передача происходит между управляющей машиной и ServerB .
Ставим задачу на ServerA
Используется mode: pull для изменения направления передачи. Опять же, имейте в виду, что задача фактически выполняется на ServerB , поэтому вытягивание - правильный выбор.
Это настолько хороший ответ, что он должен быть частью документации Ansible . Ни один из приведенных здесь примеров не объясняет это так ясно. Спасибо!
Я пробовал это разными способами, но безуспешно Warning: Identity file /Users/myuser/.ssh/id_servers not accessible .
@WilliamTurrell Я обновил свой ответ, чтобы более подробно объяснить направление передачи. Модуль действительно немного сбивает с толку.
Спасибо. Для всех, у кого есть проблема @orotemo, вероятное решение состоит в том, что у вас нет доступа к открытому ключу только между серверами A и B, или, как я обнаружил, вы настроили его работать только в одном направлении - в неправильном. В отсутствие какой-либо пары ключей в вашем каталоге .ssh на сервере A, ansible пытается использовать домашний каталог вашего локального компьютера (который не будет существовать, если это, скажем, Mac, и может иметь другое имя учетной записи)
Если вам нужно синхронизировать файлы между двумя удаленными узлами через ansible, вы можете использовать это:
когда remote_server вам нужно запустить rsync в режиме демона. Простой пример:
This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name copy even without specifying the collections: keyword. However, we recommend you use the FQCN for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.
See Also
The official documentation on the ansible.builtin.assemble module.
The official documentation on the ansible.builtin.fetch module.
The official documentation on the ansible.builtin.file module.
The official documentation on the ansible.builtin.template module.
The official documentation on the ansible.posix.synchronize module.
The official documentation on the ansible.windows.win_copy module.
Return Values
Common return values are documented here , the following are the fields unique to this module:
Attributes the file or directory should have. To get supported flags look at the man page for chattr on the target system. This string should contain the attributes in the same order as the one displayed by lsattr.
Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
SHA1 checksum of the file being transferred. Used to valdiate that the copy of the file was successful.
When used instead of src, sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module.
Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too. If dest is a nonexistent path and if either dest ends with "/" or src is a directory, dest is created. If src and dest are files, the parent directory of dest isn't created: the task fails if it doesn't already exist.
When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which are newly created, and will not affect those that already existed.
the default is yes , which will replace the remote file when contents are different than the source. If no , the file will only be transferred if the destination does not exist.
Mode the file or directory should be. For those used to /usr/bin/chmod remember that modes are actually octal numbers (like 0644 or 01777 ). Leaving off the leading zero will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, u+rwx or u=rw,g=r,o=r ).
Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the range . _default feature works as for seuser.
User part of SELinux file context. Will default to system policy, if applicable. If set to _default , it will use the user portion of the policy if available.
Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to Rsync.
Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just broken in ways that prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done in an unsafe manner.
This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any other choice. Be aware that this is subject to race conditions and can lead to data corruption.
The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the example below. The command is passed securely so shell features like expansion and pipes won't work.
Examples
Attributes
action
Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller
async
Supports being used with the async keyword
bypass_host_loop
Forces a ‘global’ task that does not execute per host, this bypasses per host templating and serial, throttle and other loop considerations
Conditionals will work as if run_once is being used, variables used will be from the first available host
This action will not work normally outside of lockstep strategies
check_mode
Can run in check_mode and return changed status prediction withought modifying target
diff_mode
Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode
platform
Target OS/families that can be operated against
safe_file_operations
Uses Ansbile’s strict file operation functions to ensure proper permissions and avoid data corruption
vault
added in 2.2 of ansible.builtin
Can automatically decrypt Ansible vaulted files
Synopsis
The copy module copies a file from the local or remote machine to a location on the remote machine.
Use the ansible.builtin.fetch module to copy files from remote locations to the local box.
If you need variable interpolation in copied files, use the ansible.builtin.template module. Using a variable in the content field will result in unpredictable output.
For Windows targets, use the ansible.windows.win_copy module instead.
This module has a corresponding action plugin .
Notes¶
The copy module recursively copy facility does not scale to lots (>hundreds) of files.
Examples¶
Читайте также: