How to install and configure to use Ansible
A. Install Ansible
1. Why should use Ansible?
-> to automate the server setups. If you have 1-2 server, manually SSH and install packages is fine. However, think about the situation that you have, for e.g. 50 servers to manage.
2. How Ansible work?
-> Ansible work by automatically SSH to the servers that you defined in the hosts file and run scripts to install your desired packages.
3. Best practice:
-> You should have a dedicated manage server that installed Ansible and configure so that SSH is possible from the manage server to your desired server.
4. How to install Ansible?
If you use AMZ Linux 2:
Run below commands:
sudo amazon-linux-extras install epel
sudo yum install ansible
The above 2 commands will install Ansible version 2.9.5.
Test the installation by running:
ansible --version
If you encounter not found error, try finding the ansible bin location by running:
which ansible
For example, if the which command return:
~/.local/bin/ansible
\=> do as below:
nano ~/.bashrc
add this line:
alias ansible=~/.local/bin/ansible
And then:
source ~/.bashrc
If you use Ubuntu:
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible
Test the installation by running:
ansible --version
if you encounter not found error, try finding the ansible bin location by running:
which ansible
\==============
Note: Another way to install ansible is using pip
For e.g., following command will install ansible 4.10:
pip3 install ansible==4.10
\==============
B. Configure SSH
cd ~/.ssh/
mkdir key
nano config
config’s file content:
Host *
User ubuntu
Port 22
TCPKeepAlive yes
identitiesonly yes
identityFile ~/.ssh/key/docker-demo.pem
Copy your .pem key into key folder. Remember to chmod 400 the key.
Now, you can SSH the managed node by:
ssh <private_ip_of_managed_node>
Note: You can use dns instead of IP address by giving alias to your private IP address at /etc/hosts file.
Note:
If you encounter the error:
Bad owner or permissions on /home/ec2-user/.ssh/config
Run the following 2 commands:
chmod 600 ~/.ssh/config
chown $USER ~/.ssh/config
C. Using the Ansible
Advance preparation
- SSH connection to all target servers is possible -SSH connect to all target servers in advance and register in known_hosts.
Confirmation before execution
--i: Specify the target hosts configuration file (verification environment: hosts / stg, production environment: hosts / prd)
--diff: Show the difference before and after execution
--verbose: Detailed view
--check: DryRun
D. Sample project:
You can download sample project below. To generate sample ansible role:
ansible-galaxy init sample