Create File in Ansible and copy content using ansible copy



Create File in Ansible and copy content using ansible copy module |File is very necessary for linux operation.You can create file in linux system using shell through command.But when we are going to handle file large no of systems we use Ansible because it is very easier to implement large no of systems.

In this article we learn how to create file in ansible using ansible file module and how ansible copy works and how to create multiple files in ansible.

We are going to implement node1 remote machine via ansible control machine.

Create an empty file 

You can create an empty file using ansible file module.Here we have to defined two aguments one is path and other is state.Normally we create an empty file using touch command. When we are going to create an empty file using ansible  we set the state parameters to ‘touch’  .

---
- hosts: node1
  tasks:
    - name: create blank file
      file:
         path: "/test.txt"          state: touch


create file  ansible,ansible file module,ansible copy
Create file  Ansible



Create multiple files in ansible 


We can create multiple new files running ansible playbook using file and with_items module.
Let’s try an example
We are going to create test1.txt,test2.txt under /
---
- hosts: node1
  tasks:
    - name: create blank file
      file:
         path: "{{item}}"
         state: touch
         mode: 0777
       with_items:
         - test1.txt
         - test2.txt    


Define permission of a file

In the above example we have created  an empty file with default permission .Now we want to change the file defaults permission.So, We have to focused two arguments one is mode and other is owner.

Now we are going to change the default permission of the test.txt file.
We can use the octal form or symbolic form to define the mode argument and in the owner mode we mention the owner name.
---
- hosts: node1
  tasks:
    - name: create blank file
      file:
         path: "/test.txt"
         mode: 0777
         owner: root

Create a File with content using content argument

Normally copy module is used to copy from source file to destination file.In the copy module there is an argument called content to create the file with content.


---
- hosts: node1
  tasks:
    - name: create blank file
      copy:
         dest: "/test.txt"
         content: |
           This is test content


Here dest argument is indicating the absolute location of the file in which the content should be written.If file is exists then ansible check any content is exists or not in the file.if content is exists then it overlap  the whole content.


If this article is helpful to know about Create File in Ansible using ansible file module and copy content using ansible copy module  please share this article.
SHARE

Admin

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment