The ability to convert an ad hoc command into a play is a skill that serves as a bridge from the simplicity of the command line to the power of the playbook.
In this exercise, you will take the ad hoc command used in the section called “Guided Exercise: Executing Ad Hoc Commands”, convert it into a simple play in a playbook, and run it using the ansible-playbook command.
Outcomes
You should be able to:
Translate an ad hoc command into a simple play in a playbook.
Verify the YAML syntax of the playbook.
Run the play.
This exercise assumes you know how to set the value of variables to support connection and authentication, as described in the the section called “Lab: Deploying Ansible” exercise.
Open a terminal window on the workstation VM.
If you use the Vim text editor, configure it to automatically translate the Tab key into two spaces.
White space is significant to YAML, and it expects files to be structured in increments of two spaces.
Adding this line to ~/.vimrc may make that easier:
autocmd FileType yaml setlocal ai ts=2 sw=2 et
For an overview of how to use the Vim text editor, see Appendix C, Editing Files with Vim.
Procedure 2.2. Instructions
Change to the ~/proj/ directory created in Lab 1.
Create a file named iosping1.yml with the following content:
---
- name: A reachability test
hosts: cs01
tasks:
- name: Test reachability to 172.25.250.9
ios_ping:
dest: 172.25.250.9
It is assumed that the [defaults] section of your ansible.cfg file contains the line gathering = explicit.
If it does not, you should include the line gather: False at the top of the play: after hosts and before tasks, for instance.
Check the syntax of the playbook you created.
[student@workstation proj]$ansible-playbook --syntax-check iosping1.ymlplaybook: iosping1.yml
Use the ansible-playbook command to run the play in your playbook.
The SSH password for cs01 is student.
[student@workstation proj]$ansible-playbook iosping1.ymlSSH password:studentPLAY [A reachability test] ***************************************************** TASK [Test reachability to 172.25.250.9] *************************************** ok: [cs01] PLAY RECAP ********************************************************************* cs01 : ok=1 changed=0 unreachable=0 failed=0
Use a text editor to create a file named vyos-sh-conf1.yml with the following content:
---
- name: Show the running config of a VyOS system
hosts: spine01
tasks:
- name: execute the command
vyos_command:
commands:
- sh conf com
register: result
- name: show result
debug:
var: result
Use the ansible-playbook command to run the play in your playbook.
The SSH password for spine01 is vyos.
[student@workstation proj]$ansible-playbook vyos-sh-conf1.ymlSSH password:vyos...output omitted
This concludes the guided exercise.