Playbooks against Remote Hosts
Connect to remote Linux and Windows hosts using Ansible playbooks.
Let’s look at how you can codify the ad-hoc command to connect to the Linux instance or virtual machine.
Connect to remote Linux host#
You will learn how to convert the following ad-hoc command to an Ansible playbook:
Create the playbook#
Create the playbook in these steps:
- Create a
ping.yml
file. - Add the
hosts
line to use the host pattern ofall
.
- Create a
vars
list and define the connection variables. Replace<Password>
with your password.
Defining the variables in the playbooks prevents you from defining them at run time.
At the moment, the password
is in cleartext. This is obviously bad. Ansible has a feature that allows you to encrypt variables, which will be covered later.
- Add a
tasks
list.
Run the playbook#
The final form of the ping.yml
file looks like the one below. You can execute the playbook by clicking on the Run
button.
/
- ping.yml
Once the environment is set up, execute the following command in the terminal:
Replace <Public IP Address>
with the address of the Linux remote host. Ensure that there is a ,
at the end of the IP address to indicate that this is a host list.
Add a prompt#
The ping.yml
playbook can be used to ping any Linux host by providing a different host list. However, since the username and password are hardcoded in the playbook, that user must exist on every host with the same password.
To increase the repeatability of the playbook, you can use vars_prompt
to prompt for the username and password.
- Create a playbook called
ping_prompts.yml
. - Add a
vars_prompt
for the ssh user and ssh password.
- Update
vars
with the variables defined by the prompts.
Ansible variables are enclosed in double-quotes and curly braces "{{ var }}"
.
- Review and execute the final form below by clicking on the
Run
button.
/
- ping_prompts.yml
Once the environment is set up, execute the following command in the terminal:
- When prompted, enter the username and password.
Default username
The username isansible
by default.
An added benefit of using a vars_prompt
for the password is that you are far less likely to commit a password to source control, which would be bad.
Try it now#
Practice converting Windows ad-hoc ping command to a playbook.
Convert to a Windows ping playbook#
The command to connect to the remote Windows host is given below. Write your code in the win_ping.yml
file.
Solution
The solution to this challenge is provided in theSolution
directory. Try it yourself first and compare your solution with the provided solution.
/
- win_ping.yml
In this lesson, we introduced vars
and vars_prompt
and converted the ad-hoc commands to playbooks to make them repeatable.