Ansible
Steps to get started with Ansible
Key generation and installation
1. Enable SSH
The server you wish to control with Ansible need to have SSH enabled.
2. Create another ssh key for ansible:
From the server you wish to manage Ansible create a new SSH key:
ssh-keygen -t ed25519 -f ~/.ssh/ansible -C "ansible"
I like to use the newest algorithm ed25519 instead of the default RSA and give it a specific filename. Beware, that you might re-rewrite another key you have if you don’t give it unique name.
When prompted to protect our key with a password, we will just press enter (no key), so ansible can login without any prompt.
3. Copy your ansible ssh-key to your servers
ssh-copy-id -i ~/.ssh/ansible.pub myserver1
Repeat this command for all your servers.
Note that if you want to manually choose which key to use when you login you can specify it with the command
ssh -i ~/.ssh/ansible myserver1
4. Install ansible
A great thing about ansible is that you only need to install it on the server that will manage the rest (and not on the servers you wish to remotely manage).
Depending on your Linux distribution this can be:
sudo apt install ansible
or
sudo pacman -S ansible
or
pip3 install ansible
5. Create and enter your Ansible folder
This can be a standard folder or optionally a git repository to store your Ansible data.
mkdir ~/ansible && cd ~/ansible
6. Create inventory file on my ansible git repository
The default file for you inventory is /etc/ansible/hosts
. I instead prefer to keep it in my ansible folder so I have it in my git repository.
vim hosts
This inventory file should have the ips/names of the servers you will manage with a username if they require it.
Example:
testimonia.local
x6.local
pi@pi4.local
Test Ansible by running your first command
This command will ping all hosts in my inventory file I just created.
ansible all --key-file ~/.ssh/ansible -i hosts -m ping
Other useful commands
ansible all --list-hosts
ansible all -m gather_facts
ansible all -m apt -a update_cache=true --become --ask-become-pass
ansible all -m apt -a name=vim --become --ask-become-pass
ansible home_servers -a "cat /etc/os-release"
ansible-playbook task.yml
Sidenote
If you get an error signing the commit with GPG:
export GPG_TTY=$(tty)
Ansible-Vault
Create a ~/.vault_key
file and do a chmod 600 ~/.vault_key
to protect it.
ansible-vault encrypt --vault-password-file ~/.vault_key myfile
ansible-vault decrypt --vault-password-file ~/.vault_key myfile
ansible-vault edit --vault-password-file ~/.vault_key myfile
ansible-vault view --vault-password-file ~/.vault_key myfile