Ansible playbook удалить файл
Alternatively, remove files, symlinks or directories.
Many other modules support the same options as the file module - including copy , template , and assemble .
For Windows targets, use the win_file module instead.
Parameters¶
Should be preserve when no modification is required, YYYYMMDDHHMM.SS when using default time format, or now .
Default is None meaning that preserve is the default for state=[file,directory,link,hard] and now is default for state=touch .
Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the path file and create symlink to the src file in place of it).
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 ).
Should be preserve when no modification is required, YYYYMMDDHHMM.SS when using default time format, or now .
Default is None meaning that preserve is the default for state=[file,directory,link,hard] and now is default for state=touch .
Relative paths are relative to the file being created ( path ) which is how the Unix command ln -s SRC DEST treats relative paths.
If absent , directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if diff is declared, you will see the files and folders deleted listed under path_contents . Note that absent will not cause file to fail if the path does not exist as the state did not change.
If directory , all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions.
If file , without any other options this works mostly as a 'stat' and will return the current state of path . Even with other options (i.e mode ), the file will be modified but will NOT be created if it does not exist; see the touch value or the copy or template module if you want that behavior.
If touch (new in 1.4), an empty file will be created if the path does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).
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).
See Also¶
The official documentation on the assemble module.
The official documentation on the copy module.
The official documentation on the stat module.
The official documentation on the template module.
The official documentation on the win_file module.
Examples¶
Status¶
This module is guaranteed to have backward compatible interface changes going forward. [stableinterface]
Red Hat Support¶
More information about Red Hat’s support of this module is available from this Red Hat Knowledge Base article.
Authors¶
Ansible Core Team
If you notice any issues in this documentation, you can edit this document to improve it.
The below code only deletes the first file it gets inside the web dir. I want to remove all the files and folders inside the web directory and retain the web directory. How can I do that?
Note: I've tried rm -rf using command and shell, but they don't work. Perhaps I am using them wrongly.
Any help in the right direction will be appreciated.
I am using ansible 2.1.0.0
19 Answers 19
Note: this will delete the directory too.
The OP (and myself) want a solution that will delete the contents of the folder BUT NOT the folder itself. This solution deletes the contents AND the folder itself.
Has anyone had the above code fail on them with artifact_path being null? This feels like it could be susceptible to one of those great rm -rf / moments in history
@ted-k42 I'd do something like this just to be safe: when: artifact_path is defined and artifact_path != ""
If you don't have the luxury of removing the whole directory and recreating it, you can scan it for files, (and directories), and delete them one by one. Which will take a while. You probably want to make sure you have [ssh_connection]\npipelining = True in your ansible.cfg on.
The first task is the most elegant solution I've seen. Note the comments elsewhere that there's a long-running feature request to add state=empty
Using shell module (idempotent too):
If there are dot/hidden files:
Cleanest solution if you don't care about creation date and owner/permissions:
Note that this might change your permissions/owner unless you set the explicitly during creation moment.
This is actually the fastest and most readable answer in this post, even if it's not "native Ansible". You can use rm -rf << path >>/.[!.]* << path >>/* if you want to get really fancy and delete files with leading dots too.<>
@Ocab19 rm -rf [variable]/* is a risky operation. I do not recommend it. What if [variable] is null. That becomes rm -rf /*. Although it is prevented for many servers, it could cause a disaster.
I really didn't like the rm solution, also ansible gives you warnings about using rm. So here is how to do it without the need of rm and without ansible warnings.
Thanks! For cleaning out a directory when some items inside it might be directories, or start with a . , I needed to add file_type: any and hidden: true to the find: . excludes was also handy.
try the below command, it should work
It’s dangerous to use ls ’ output to get filenames because it doesn’t correctly print filenames with special characters such as newlines.
That's what I come up with:
First, we're getting directory listing with find , setting
- file_type to any , so we wouldn't miss nested directories and links
- hidden to yes , so we don't skip hidden files
- also, do not set recurse to yes , since it is not only unnecessary, but may increase execution time.
Then, we go through that list with file module. It's output is a bit verbose, so loop_control.label will help us with limiting output (found this advice here).
But I found previous solution to be somewhat slow, since it iterates through the content, so I went with:
- get directory properties with the stat
- delete directory
- recreate directory with the same properties.
That was enough for me, but you can add attributes as well, if you want.
Created an overall rehauled and fail-safe implementation from all comments and suggestions:
thanks for pointing this out. I had this piece of code taken out of one of my playbooks and made it more generic in terms of naming but forget to replace two variable names
Good stuff, but I think the state in the last task needs to be set to "directory" rather than "present".
You should use your stat result to preserve permissions: owner from pw_name, group from gr_name, and mode from mode.
tried owner: dir_to_delete.stat.pw_name, group: dir_to_delete.stat.gr_name mode: dir_to_delete.stat.mode but it fails on me with my current Ansible version :(
Using file glob also it will work. There is some syntax error in the code you posted. I have modified and tested this should work.
Note though, with synchronize you should be able to sync your files (with delete) properly anyway.
Below code worked for me :
There is an issue open with respect to this.
For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.
Here is a sample playbook:
I have written an custom ansible module to cleanup files based on multiple filters like age, timestamp, glob patterns, etc.
It is also compatible with ansible older versions. It can be found here.
Here is an example:
I want to make sure that the find command only deletes everything inside the directory and leave the directory intact because in my case the directory is a filesystem. The system will generate an error when trying to delete a filesystem but that is not a nice option. Iam using the shell option because that is the only working option I found so far for this question.
Edit the hosts file to put in some variables:
And create a playbook:
This will delete all files and directories in the COGNOS_HOME variable directory/filesystem. The "-mindepth 1" option makes sure that the current directory will not be touched.
I need to create an Ansible playbook to delete the *.web files in a specific directory only if the files exists.
OS : cent OS, Redhat 5x, 6x.
I have tried the following with no success:
Sorry, It was my error. I have multiple requirements like mv , cp and rm *.web only if files exists. I have validated mv and cp *web and it was failed and aborting with no such file or directory. Just noticed rm is silently completing without error.
3 Answers 3
@bruce-p's answer gives a deprecation warning with Ansible 2.0+, but the new with_fileglob gives another option:
EDIT: As noted below, that won't work; here's an example of "the fancy way":
This will not work since with_fileglob only matches files on the system which is running ansible, not the target host.
Hmm, you're right! @bruce-p's remark "If you really want to get fancy you could use the find module to locate all the files that match your pattern and then invoke the rm command (or better yet use the file module and set state=absent) using a with_items loop to loop over what find returns." is the clean way to do this, I guess -- edited to include an example of that.
The stat module does not work with wildcards, so the first task will not do what you expect. Most Ansible modules do not support * , ? , etc. wildcards in their parameters unless explicitly documented that they do. The reason for this is that wildcard expansion is typically handled by your login shell (bash, zsh, etc), so unless the application explicitly supports it then it won't recognize them.
Here's an easy way to verify this:
The output of this is:
Note that when you specify a single file it returns the results for that file, but when you specify a wildcard it basically returns nothing.
As @udondan implied in his answer, you can just do something like this:
Since rm will silently complete without error if there are 0 matches.
If you really want to get fancy you could use the find module to locate all the files that match your pattern and then invoke the rm command (or better yet use the file module and set state=absent ) using a with_items loop to loop over what find returns.
This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name file 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.
Synopsis
Set attributes of files, symlinks or directories.
Alternatively, remove files, symlinks or directories.
Many other modules support the same options as the file module - including ansible.builtin.copy , ansible.builtin.template , and ansible.builtin.assemble .
For Windows targets, use the ansible.windows.win_file module instead.
Parameters
access_time
added in 2.7 of ansible.builtin
This parameter indicates the time the file’s access time should be set to.
Should be preserve when no modification is required, YYYYMMDDHHMM.SS when using default time format, or now .
Default is None meaning that preserve is the default for state=[file,directory,link,hard] and now is default for state=touch .
access_time_format
added in 2.7 of ansible.builtin
When used with access_time , indicates the time format that must be used.
Based on default Python format (see time.strftime doc).
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.
follow
added in 1.8 of ansible.builtin
This flag indicates that filesystem links, if they exist, should be followed.
Previous to Ansible 2.5, this was no by default.
force
Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the path file and create symlink to the src file in place of it).
group
Name of the group that should own the filesystem object, as would be fed to chown.
mode
The permissions the resulting filesystem object should have.
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 mode is not specified and the destination filesystem object does not exist, the default umask on the system will be used when setting the mode for the newly created filesystem object.
If mode is not specified and the destination filesystem object does exist, the mode of the existing filesystem object will be used.
Specifying mode is the best way to ensure filesystem objects are created with the correct permissions. See CVE-2020-1736 for further details.
modification_time
added in 2.7 of ansible.builtin
This parameter indicates the time the file’s modification time should be set to.
Should be preserve when no modification is required, YYYYMMDDHHMM.SS when using default time format, or now .
Default is None meaning that preserve is the default for state=[file,directory,link,hard] and now is default for state=touch .
modification_time_format
added in 2.7 of ansible.builtin
When used with modification_time , indicates the time format that must be used.
Based on default Python format (see time.strftime doc).
owner
Name of the user that should own the filesystem object, as would be fed to chown.
path
aliases: dest, name
Path to the file being managed.
recurse
added in 1.1 of ansible.builtin
Recursively set the specified file attributes on directory contents.
This applies only when state is set to directory .
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
Path of the file to link to.
This applies only to state=link and state=hard .
For state=link , this will also accept a non-existing path.
Relative paths are relative to the file being created ( path ) which is how the Unix command ln -s SRC DEST treats relative paths.
state
If absent , directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if diff is declared, you will see the files and folders deleted listed under path_contents . Note that absent will not cause file to fail if the path does not exist as the state did not change.
If directory , all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions.
If file , with no other options, returns the current state of path .
If file , even with other options (such as mode ), the file will be modified if it exists but will NOT be created if it does not exist. Set to touch or use the ansible.builtin.copy or ansible.builtin.template module if you want to create the file if it does not exist.
If hard , the hard link will be created or changed.
If link , the symbolic link will be created or changed.
If touch (new in 1.4), an empty file will be created if the file does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).
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.
Attributes
check_mode
Can run in check_mode and return changed status prediction withought modifying target
diff_mode
permissions and ownership will be shown but file contents on absent/touch will not.
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
See Also
The official documentation on the ansible.builtin.assemble module.
The official documentation on the ansible.builtin.copy module.
The official documentation on the ansible.builtin.stat module.
The official documentation on the ansible.builtin.template module.
The official documentation on the ansible.windows.win_file module.
Examples
Return Values
Common return values are documented here , the following are the fields unique to this module:
Ansible, без сомнения, лучший инструмент автоматизации инфраструктуры, который используется ведущими 500 компаниями по всему миру.
На Crunchify мы опубликовали множество учебных пособий по Ansible. Пожалуйста, взгляните на Ansible Archive для всех подробных уроков. Вот лучшие 3 урока.
- Как скопировать файл, каталог или скрипт с локального хоста на удаленный хост?
- Как порождать виртуальные машины Amazon EC2 с помощью Ansible?
- Как выполнить команды на удаленных хостах и получить результат команды (log) обратно ?
В этом уроке мы рассмотрим 3 разных совета, которые я использую в повседневной жизни.
Как удалить и заново создать файл с помощью Ansible?
Шаг 1
Убедитесь, что вы правильно настроили Ansible на Mac или Linux .
Шаг 2
Создать файл crunchify-delete-recreate-ansible.yml
Шаг 3
открыто hosts файл и положить ниже содержание:
Шаг 4
Бежать Ansible playbook ,
ВНИМАНИЕ : проведение скрипт , который загрузка libcrypto в небезопасный способ. это потерпит неудачу в будущая версия MacOS. Установите значение LIBRESSL_REDIRECT_STUB_ABORT = 1 в окружающей среды в заставить это в ошибку.
настроенный путь поиска модуля знак равно [ u '/Users/crunchify/.ansible/plugins/modules' , u '/ usr / share / ansible / plugins / modules' ]
версия на питоне знак равно 2.7.16 (по умолчанию , июль 14 2019 , 03 : 47 : 49 ) [ GCC 4.2.1 Совместимый Apple LLVM 11.0.0 ( лязг — 1100.0.32.4 ) ( — macos10 . 15 — objc — s
/ Пользователи / crunchify / Документы / анзибль / хозяева не соответствовать требованиям host_list , проверьте документацию плагина, если этот является неожиданный
/ Пользователи / crunchify / Документы / анзибль / хозяева не соответствовать требованиям сценария , проверьте документацию плагина, если этот является неожиданный
Успешно разобран / Users / crunchify / Documents / ansible / хост инвентаризации источника с плагином ini
путь к задаче : / Users / crunchify / Документы / анзибль / crunchify — удалить — воссоздать — анзибль. yml : 2
localhost > EXEC / bin / sh — с '(umask 77 && mkdir -p ` echo /Users/crunchify/.ansible/tmp/ansible-tmp-1567010309.76-127517206399779 ` && echo ansible-tmp-1567010309.76-127517206399779 = ` echo /Users/crunchify /tmp/ansible-tmp-1567010309.76-127517206399779 `) && sleep 0 '
Использование файла модуля / Библиотека / Python / 2.7 / site — пакеты / ansible / modules / system / setup . ру
localhost > ПОЛОЖИЛ / Пользователи / crunchify / . ansible / tmp / ansible — local — 36562FsxMwP / tmp5SGRSa TO / Пользователи / crunchify / . ansible / tmp / ansible — tmp — 1567010309.76 — 127517206399779 / AnsiballZ_setup . ру
localhost > EXEC / bin / sh — с 'chmod u + x /Users/crunchify/.ansible/tmp/ansible-tmp-1567010309.76-127517206399779/ /Users/crunchify/.ansible/tmp/ansible-tmp-1567010309.76-127517206399779/AnsiballZ_setup.py && 0'
localhost > EXEC / bin / sh — с 'python /Users/crunchify/.ansible/tmp/ansible-tmp-1567010309.76-127517206399779/AnsiballZ_setup.py && sleep 0'
localhost > EXEC / bin / sh — с 'rm -f -r /Users/crunchify/.ansible/tmp/ansible-tmp-1567010309.76-127517206399779/> / dev / null 2> & 1 && sleep 0'
путь к задаче : / Users / crunchify / Документы / анзибль / crunchify — удалить — воссоздать — анзибль. yml : 8
localhost > EXEC / bin / sh — с '(umask 77 && mkdir -p ` echo /Users/crunchify/.ansible/tmp/ansible-tmp-1567010310.35-144146434104750 ` && echo ansible-tmp-1567010310.35-144146434104750 = ` echo /Users/crunchify/ /tmp/ansible-tmp-1567010310.35-144146434104750 `) && sleep 0 '
Использование файла модуля / Библиотека / Python / 2.7 / site — пакеты / ansible / modules / files / file . ру
localhost > ПОЛОЖИЛ / Пользователи / crunchify / . ansible / tmp / ansible — local — 36562FsxMwP / tmpvL0NpJ TO / Пользователи / crunchify / . ansible / tmp / ansible — tmp — 1567010310.35 — 144146434104750 / AnsiballZ_file . ру
localhost > EXEC / bin / sh — с 'chmod u + x /Users/crunchify/.ansible/tmp/ansible-tmp-1567010310.35-144146434104750/ /Users/crunchify/.ansible/tmp/ansible-tmp-1567010310.35-144146434104750/AnsiballZ_file.py && sleep 0'
localhost > EXEC / bin / sh — с 'python /Users/crunchify/.ansible/tmp/ansible-tmp-1567010310.35-144146434104750/AnsiballZ_file.py && sleep 0'
localhost > EXEC / bin / sh — с 'rm -f -r /Users/crunchify/.ansible/tmp/ansible-tmp-1567010310.35-144146434104750/> / dev / null 2> & 1 && sleep 0'
Читайте также: