visit
The main idea is to have the Ansible CLI installed on a machine you have access to, then you'll create a list of servers and IP addresses in what's called an Inventory
file. After which you can use Ansible CLI to run ad-hoc commands
to execute tasks on the servers you listed.
This is where you define the list of hosts (this can be a local instance of a machine, remote servers etc) that you want to manage using Ansible. These files can be in .ini
or .yaml
format. Here's an example that defines a group of webservers:
[webservers]
170.187.144.11
170.187.144.12
170.187.144.13
webservers:
hosts:
170.187.144.11
170.187.144.12
170.187.144.13
Both formats accomplish the same thing, however .yaml
is commonly used in many config files and allows you to give each host a unique name so I'd recommend using that.
To automate a task, you can use scripts that contain specific commands or you can run commands directly in the CLI. The latter is referred to as an ad-hoc command
and allows you to execute simple one-time commands. Using the inventory.ini
file we created above, we can use ad-hoc commands
to do the following:
ansible webservers -m ping --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml
# -m Tells Ansible which module to use, in this case, ping
# --key-file Specifies the SSH private key file to use for connections to the remote hosts.
# -u Indicates that Ansible should connect as the `root` user.
# -i Specifies the inventory file to use.
ansible webservers -m copy -a "src=test.txt dest=/root/" --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml
# -a Specifies the arguments to pass to the module. This module copies files from the local machine on which Ansible is running to the remote hosts specified in the inventory.yaml file.
I've created a docker-compose file that will provision an environment that will allow you to practice what we learned above.
git clone //github.com/perplexedyawdie/ansible-learn.git2.
cd ansible-learn/inventory-files-and-ad-hoc-cmds
docker compose up -d --build
ssh -o StrictHostKeyChecking=no root@localhost -p 2200
# password: test123
5. Create an inventory.yaml
file and populate with hosts
cd ansible_learn
touch inventory.yaml
nano inventory.yaml
# Paste the following in your inventory.yaml file.
# webservers:
# hosts:
# server1:
# server2:
# server3:
ansible webservers -m ping --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml
echo "Hello Mate!!" >> test.txt
ansible webservers -m copy -a "src=test.txt dest=/root/" --key-file /root/.ssh/id_rsa_ansible -u root -i inventory.yaml
ssh -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa_ansible root@server1
ls
cat test.txt
exit
exit
docker compose down
You just learned the basics of Ansible automation! Specifically, how to define the hosts you want to remotely manage and how to execute commands on them. In the next article, we'll look at Playbooks along with task control mechanisms and handlers.