Creating Playbooks
Ad-Hoc Commands
First, we should be sure that ansible is configured correctly, to run commands on a server or a group of servers within the /etc/ansible/hosts
file, run any of the below commands
ansible -m ping hostname
ansible -m ping 134.23.4.5
ansible -a "sudo ls /" hostname
ansible -a "sudo ls /" 134.23.4.5
ansible -a "free -h" hostname
ansible -a "free -h" 134.23.4.5
While the above is an example of running bash commands on remote hosts ad-hoc via the commandline, you can also run ansible modules from the commandline in a similar way -
ansible remotehostname -m fetch -a "src=/home/remoteuser/path/file.txt dest=/home/localuser/"
Here, we grab file.txt
from a remote host and copy it to our local home directory. Where -m
is selecting which module to use and -a
is providing the options that you would specify within a normal playbook via a command. Be sure to enclose any module options after -a
with double quotes or the command will fail. See the Ansible documentation for each module for more information on their arguments.
Creating Playbooks
Ansible allowscan usbe configured to carry out moretedious ad-hocor otherwise common tasks on serversany withinnumber ourof inventoryhosts, as well. For example, if we wantedsee below in the example playbook where Ansible is being used to createbackup aan playbook that carried out a setinstance of tasks, we could do so in a similar format to how we would create / define an Ansible Role - using YAML syntax and defining the same or very similar set of parameters within one file.Bookstacks.
---
- hosts: bookstack
become: yes
tasks:
- name: Backup Bookstack container files
command: tar -cvzf bookstack-backup.tar.gz /home/admin/bookstack
- name: Fetch backup files from remote host
command: scp -P 2222 -i /home/kapak/.ssh/id_rsa /home/admin/bookstack-backup.tar.gz admin@sub.domain.com:/home/admin/backups/bookstack/
Here, we use scp
instead of Ansible's Fetch module to save memory on the small host that runs the BookStack you are viewing. When fetching large files, memory errors can be encountered so here we have worked around the module using an alternative method for transferring our files.
Ad-Hoc Commands
To run commands on a server or a group of servers within the /etc/ansible/hosts file, run any of the below
ansible -m ping hostname
ansible -m ping 134.23.4.5
ansible -a "sudo ls /" hostname
ansible -a "sudo ls /" 134.23.4.5
ansible -a "free -h" hostname
ansible -a "free -h" 134.23.4.5