Get started with Ansible - installation and basics.
We start by creating an SSH key into my Digital Ocean account. To create this SSH key, we'd locally run:
cd ~/.ssh ssh-keygen -t rsa -b 4096 -C "email@example.com" -f id_ansible # Get key into Mac's clipboard cat id_ansible.pub | pbcopy
That SSH key will be added to any server I create on Digital Ocean. This will ensure Ansible can log into any server we want to provision.
For this example, I create 3 servers on Digital Ocean.
In my local server I connect to the servers like so:
ssh -o "IdentitiesOnly yes" -i ~/.ssh/id_ansible root@[server-ip-here]
I can see I can connect, so I know the key-pair authentication is working over SSH.
We're using an Ubuntu server (locally, via Vagrant). To install Ansible, run:
# Run this if we don't have the "add-apt-repository" command sudo apt-get install -y software-properties-common # Add Ansible's official repository sudo add-apt-repository -y ppa:ansible/ansible # Update repositories # Install Ansible sudo apt-get install -y ansible # Ensure installed which ansible
You can see how to install Ansible on other distributions here.
Ansible is agentless - we don't need to install an agent on the servers we provision. The servers just need Python and the ability to connect over SSH.
Ansible is inside of
/etc/ansible. Lets move the original out of the way and edit create a new one.
sudo mv /etc/ansible/hosts /etc/ansible/hosts.bak sudo vim /etc/ansible/hosts
/etc/ansible/hosts and make it look like this:
[web] 18.104.22.168 22.214.171.124 126.96.36.199
Now we have our three servers defined as hosts for Ansible to use.
Run Some Commands on Each Host
We'll run some arbitrary commands.
# Run ping as user root on each server ansible all -m ping -u root
We run into an SSH error, it doesn't find the correct key, falling back to password.
Instead, we try the following, which works:
ansible all -m ping -u root --private-key=~/.ssh/id_ansible
Another way we can do this is as follows, which uses the "shell" command. This let's us run any shell command on the servers.
ansible all -m shell -a "ping -c 3 localhost" \ -u root --private-key=~/.ssh/id_ansible
We'll use the "apt" module to install Nginx across each server. This let's us declaratively tell Ansible what we want the desired state to be.
ansible all -m apt -a "pkg=nginx state=latest update_cache=true" \ -u root --private-key=~/.ssh/id_ansible
This will install Nginx on each server!