In this lab, you will learn how to create, copy, and delete files and folders on your hosts using the file module in Ansible.
Estimated Time: 30 minutes
The file module in Ansible is used to manipulate files and folders on your hosts. This module requires several arguments:
src: The source path of your file/folder on the ansible machine (C&C).dest: The destination path where the file/folder will be placed on your hosts.owner: The owner user on the hosts (optional).group: The owner group on the hosts (optional).state: Specifies whether to remove or create a folder/file on the hosts.mode: Sets permissions on your files (optional).
The default command template is:
ansible <Pattern> -m file -a "src=<FULL-PATH> dest=<Host-FULL-PATH> state=<absent|directory|file>"-
Create a file on the ansible machine:
cd ~ touch hello.txt nano hello.txt
Write
Hello Worldinhello.txtand save the file. -
Copy the file to the
webservergroup:ansible webservers -m copy -a "src=~/hello.txt dest=~"Check the output for a
CHANGEDstatus, indicating that something on your hosts has changed. -
Log in to each host and verify that the file is there.
To delete a file on your hosts, use the following command:
ansible webservers -m file -a "dest=~/hello.txt state=absent"After running this command, log in to each host and verify that the file is deleted.
-
Create a directory and a file within it on the ansible machine:
cd ~ mkdir test cd test touch hello.txt nano hello.txt
Write
Hello Filein the file, save, and exit. -
Create the directory on the hosts:
ansible webservers -m file -a "dest=~/test state=directory" -
Copy the file to the directory on the hosts:
ansible webservers -m copy -a "src=~/test/ dest=~/test"Log in to each host to verify the presence of the folder and file.
Delete a specific directory from all hosts in the webserver group:
ansible webservers -m file -a "dest=~/test state=absent"Practice your skills by:
- Creating a directory
~/<Your-Name>/<Your-Family>. - Creating two
txtfiles inside the directory with your email and name. - Using Ansible to push these files to your hosts.
Well done! You've successfully learned how to manage files and directories on your hosts using Ansible. 👏