Skip to main content

Scripting Administration Tasks with Ansible

Hands-On Lab

 

Photo of Rob Marti

Rob Marti

Linux Training Architect I in Content

Length

00:30:00

Difficulty

Intermediate

Ansible's ad hoc commands aren't typically used for automation, but they can be powerful tools for running a command across an inventory and getting the desired results. In this lab we'll expand on how to use shell scripting with ad hoc commands to speed up administration tasks.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Scripting Administration Tasks with Ansible

Introduction

Ansible's ad hoc commands aren't typically used for automation, but they can be powerful tools for running a command across an inventory and getting the desired results. In this lab we'll expand on how to use shell scripting with ad hoc commands to speed up administration tasks.

Scenario

One of the tasks that our admin team does periodically is to copy all of /var/log/messages from a remote server and pull it to a local machine for analysis. Rather than doing it manually we'd like to have Ansible do it.

We have to write a script that compresses /var/log/messages with tar on a remote server and then copies that tar file to /tmp/messages/ on the Ansible host.

Logging In

Use the credentials provided on the hands-on lab page to get into Server1 to begin with. Since we need root privileges, let's just run sudo -i right off and become root.

Write the Script

The script (we'll call it messages.sh could look something like to this:

for i in webserver1 dbserver1 adminserver1;
   do ssh ansible@$i "sudo tar -czf messages.tar.gz /var/log/messages";
done

ansible -m fetch -a "src=/home/ansible/messages.tar.gz dest=/tmp/messages" all

But there are thousands of ways to accomplish this with a combination of Bash and Ansible. As long as we write something that archives and compresses the log file, then delivers it to the right directory, we've accomplished the task.

Execute the Script

Let's make the script executable by running chmod +x messages.sh. Now run it (./messages.sh) and see what happens.

Conclusion

We should see output from our three tar commands, then output from the Ansible side of things (the fetching). That means we've succeeded. Congratulations!