Skip to main content

Lab 005: Ansible File Module



Requirements

The Nautilus DevOps team is working to test several Ansible modules on servers in Stratos DC. Recently they wanted to test the file creation on remote hosts using Ansible. Find below more details about the task:

  • Create an inventory file ~/playbook/inventory on jump host and add all app servers in it.
  • Create a playbook ~/playbook/playbook.yml to create a blank file /opt/nfsshare.txt on all app servers.
  • The /opt/nfsshare.txt file permission must be 0777.
  • The user/group owner of file /opt/nfsshare.txt must be tony on app server 1, steve on app server 2 and banner on app server 3.

Note: Validation will try to run the playbook using command ansible-playbook -i inventory playbook.yml, so please make sure the playbook works this way without passing any extra arguments.


Prerequisites

  • Access to jump host with Ansible installed
  • SSH access to all app servers with correct credentials

Steps

# 1. Go to the playbook directory
cd ~/playbook/

# 2. Create the inventory file and add app servers
cat > inventory <<EOF
stapp01 ansible_host=172.16.238.10 ansible_ssh_pass=******* ansible_user=tony
stapp02 ansible_host=172.16.238.11 ansible_ssh_pass=******* ansible_user=steve
stapp03 ansible_host=172.16.238.12 ansible_ssh_pass=******* ansible_user=banner
EOF

# 3. Create the playbook.yml
cat > playbook.yml <<EOF
- name: Create blank file in the App Servers
hosts: stapp01, stapp02, stapp03
become: yes
tasks:
- name: Create the file and set properties
file:
path: /opt/nfsshare.txt
owner: "{{ ansible_user }}"
group: "{{ ansible_user }}"
mode: "0777"
state: touch
EOF

# 4. Run the playbook
ansible-playbook -i inventory playbook.yml

Verification

To verify the file was created with correct permissions and ownership:

# On each app server
ls -l /opt/nfsshare.txt
# Should show -rwxrwxrwx and correct owner/group (tony, steve, banner)

Resources

thor@jump_host ~/playbook$ ansible all -a "ls -lsd /opt/nfsshare.txt" -i inventory

stapp02 | CHANGED | rc=0 >>
0 -rwxrwxrwx 1 steve steve 0 Jun 24 04:23 /opt/nfsshare.txt
stapp01 | CHANGED | rc=0 >>
0 -rwxrwxrwx 1 tony tony 0 Jun 24 04:23 /opt/nfsshare.txt
stapp03 | CHANGED | rc=0 >>
0 -rwxrwxrwx 1 banner banner 0 Jun 24 04:23 /opt/nfsshare.txt