3.1. Ansible basics on Ubuntu¶
To install Ansible you can simply update your system and install it through apt.
1 2 3 4 5
$ apt update -y $ apt dist-upgrade --fix-broken --fix-missing -y $ apt autoclean $ apt autoremove $ apt install ansible
It’s recommendable to add a user for this specific purpose where the ansible host is installed, and avoid making it an LDAP/AD user, it could give you problems!
To add it do
$ adduser ansible $ adduser ansible sudo
Next you’ll want to set-up an SSH Key to be able to access all the servers you wish to maintain with Ansible Scripting. Beware, you’ll need to execute the commands as the ansible user but with the -K argument to become a sudo user on the remote node.
This means you do need to add a sudoers file to allow for this and the same ansible user on each client node. For this it’s recommendable to do it on a VM/CT template before extensive deployments.
Add the ansible user to the client nodes you’ll be using Ansible with.
$ adduser ansible
Add the following sudoers file on the nodes you’ll be using Ansible with.
$ echo "ansible ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/ansible $ chmod 0440 /etc/sudoers.d/ansible $ visudo -c
You might want to restrict ansible’s sudo capabilities!
If you wish to restrict ansible to a specific command/s then you can do that from the sudoers file, here is an example:
$ echo "ansible ALL=(ALL) NOPASSWD: /full/path/to/command" > /etc/sudoers.d/ansible
The visudo output should be the following
/etc/sudoers: parsed OK /etc/sudoers.d/README: parsed OK /etc/sudoers.d/ansible: parsed OK
Now lets go back to the Ansible HOST node.
Generate the SSH Key pair
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
$ ssh-keygen # Generating public/private rsa key pair. # Enter file in which to save the key (/home/ansible/.ssh/id_rsa): /home/ansible/testraa # Enter passphrase (empty for no passphrase): # Enter same passphrase again: # Your identification has been saved in /home/ansible/.ssh/id_rsa # Your public key has been saved in /home/ansible/.ssh/id_rsa.pub # The key fingerprint is: # SHA256:dThXE01tCUb7l+gvsYGMvMEsWh1oW0ifBOYfHCxjsLE ansible@ct102-ansible # The key's randomart image is: # +---[RSA 3072]----+ # | o.oo. .+=++| # | *=.o.....o+| # | Eo.Bo= o. . | # | +.*.+ o .| # | . S.+ .. o.| # | + B o.o .| # | o . o .+ | # | . . o. | # | .. | # +----[SHA256]-----+
And now copy it to the client nodes
$ ssh-copy-id node02 $ ssh-copy-id node03 $ ssh-copy-id node04
After this we can go to the /etc/ansible/hosts.cfg file and add the clients
1 2 3 4 5 6 7 8 9 10 11
[proxmoxservers] #node02 192.168.0.2 [linuxservers] #node03 192.168.0.3 #node04 192.168.0.4
You can have different groups of nodes, useful for different update scripts and deployments.
To execute a script do:
$ ansible-playbook scriptname.yml -K
If you wish to apply the script to only one group of servers, or specify the groups you can do:
$ ansible-playbook scriptname.yml -K -l servergroup