Ansible Task to Create new file on remote machine, Validate and Copy Content on Remote Machine

In this article I have covered create a new file on remote machine from ansible playbook, Write contend on new file from ansible , Copy file on remote machine using ansible playbook.

We can use file, stat and copy module in Ansbile to create, validate and copy the file respectively in Ansible. These are the ansible “File Module”.

file: Ansible file module used in create a new file, sets attributes of files, symlinks, and directories, or removes files/symlinks/directories.

copy: The Copy ansible module copy the file from local machine to remote server. We can also write content into remote file from variable as well. Refer below example.

stat: Stat module is used to get facts of the remote file. Like if a path exists or not. path is a symlink.

Create a blank file in Ansible Playbook

- name: Create a new file
  file: path=/etc/foo.conf state=touch

Validate file on remote server whether it has been created or not.

- stat: path=/etc/foo.conf
  register: file_path
- debug: msg="File exists"
  when: file_path.stat.exists == true

Write content on remote file.  We can also Copy file on remote machine using ansible playbook you need to pass local file path in src instead of content.

- copy: content="Your content goes here.." dest="/etc/foo.conf"
  when: file_path.stat.exists == true

Combined above task into one playbook.

 # Define file path
 - name: Set remote file path here
   set_fact: remote_file_path=/etc/foo.conf     
 
 # Create a blank file
 - name: Create a new file
   file: path="{{ remote_file_path }}" state=touch

 # Check remote file
 - stat: path="{{ remote_file_path }}"
   register: file_path

 # Write file content in file_content variable
 - set_fact: file_content="Write your file content here"

 # If file exist then copy content in remote file.
 - copy: content="{{ file_content }}" dest="{{ remote_file_path }}"
   when: file_path.stat.exists == true

Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s