Chapter3: How to run an Ansible Playbook on Linux target (s); in 5 easy steps

Objective: To run a play (set of tasks) on a remote Linux target host.

We will use a RedHat Enterprise Linux instance created on Amazon EC2, for this exercise.

Prerequisites:

1. You have setup Ansible Control Machine. Refer Chapter-1 otherwise.
2. You have a Linux instance to use as target host. Refer to my blogpost to create one on Amazon EC2 and choose a RHEL AMI (Amazon Machine Image).

Step-1: This step is run on the Control Machine.

We have to first setup trust between Control Machine and Target. Otherwise you cannot reach the target and will see the following error.



On the control machine, generate an SSH key using ssh-keygen. Use the ssh-keygen command. Give the file name id_rsa to save the key in. Your public key will be saved in file id_rsa.pub



Check the content of the public key file id_rsa.pub .



Step-2:  This step is run on the target host.


  • Login to your target Linux host using PuTTY.
  • Open .ssh/authorized_keys file.
  • Copy the public key created on the Control Machine from the id_rsa.pub file.
  • Append the public key to the .ssh/authorized_keys file on the target host and save it.

Step-3: This step is on the Control Machine.

Create an inventory file with the name host_inventory. The content is nothing but the host name of the target. Additional target can be added in the next line as needed.


Step-4:  This step is run on the Control Machine.

Create a YAML playbook; set of tasks to run on the target. In this example, we created a simple playbook to run two shell commands to fetch date and hostname. We named the file non_local-playbook.yml




Step-5: This step is run on the Control Machine.

Run the play using the following command

ansible-playbook  -v  non_local-playbook.yml  -i   host_inventory



Pipe this output to a log file and parse it however you want.
The result you wanted is what is next to stdout.

NOTE: To run the same play on multiple target hosts at the same time, repeat step-2 on target machines. In step3 add the additional target in a separate line. In step4, append additional target hosts after a comma next to the hosts: field.

Comments

Popular posts from this blog

Chapter-2: How to write a simple YAML Playbook to run on Localhost, in 2 easy steps

Chapter1: How to deploy Ansible on a Linux instance, in 3 easy steps