Introduction
Ansible?
- It is an open source configuration management tool created using python. Perform activities on remote servers from single point.
- It contains a list of tasks (plays) in an order they should get executed against a set of host/hosts based on the configuration specified. Playbooks are written in YAML, in an easy human-readable syntax
- It is an agent less application, communication between controller and nodes is done through SSH which comes by default in linux o/s so no additional client software required as compare to puppet, chef and salt. Only requirement is to have passwordless ssh connectivity between controller and nodes.
- Suppose an organization have hundreds of application servers, web servers, database servers and lot of networking devices. If it need to upgrade, patching, installing some application software or on hardware devices defining routing table, port configuration, security allow / deny then it will take lot of time and efforts to perform manually on each device, these operations or task can be done through automation. It can be done either scripting (shell or python) and a user wrote a script but this script will be difficult to understand for other users. In ansible it is easy to understand and implement.
- Other Configutaion management tools - Ansible, chef, puppet, salt etc
- Ansible is use for
- configuration management: patching include update/upgrade o/s, applications, runtime (java) etc
- network automation: manageme/patching firewall, switches, routers, gateways etc..
- provisioning: create infrastructure (ec2, storage etc), most widely used is Terraform(IaC)
- deployment (using CICD tools to deploy application)
- You can consider ansible ad-hoc commands as shell commands and a playbook as a shell script.
- Click here for comprehensive guide.
Ansible has 3 important files:
- Host/inventory file: Contains the entry of the nodes that need to be managed (/etc/ansible/hosts).
- Ansible.cfg file: Located by default at /etc/ansible/ansible.cfg, it has the necessary privilege escalation options and the location of the Hosts/inventory file.
- Main file: A playbook that has modules that perform various tasks on a host listed in an inventory/host file.
- code
- code
Controller & Nodes:
- Ansible is installed only on one machine called controller, the remote servers that ansible tries to configure are called as manged nodes.
- Ansible controller runs on linux o/s only while nodes could be linux or windows or Mac.
- Controller machine required Python 2.4 or higher and ansible software.
- Node machines are required only python.
- you can perform task on nodes with three ways.
- Adhoc commands
- Playbook
- Roles
- colour code: yellow=changed, green=not changed, red=fail change.
Advantages:
- Provisioning of servers: Performing operations like installing patches, updating software, can be done easily and quickly.
- Time and Resource saving: We are require less number of admin for configuring servers and can be done in less time.
- Disaster recovery quickly: In case of natural calamity when an entire data center can be lost we can use Configuration Management tools for creating replica data center with the similar configuration.
- Handling snowflake servers: After certain time each server in a datacenter start behaving like snowflake, that mean each server can be run slightly different hardware or software configuration, CM tools can capture these information and store it in files known as setup files and these setup files can be later used for configuring similar servers. like template
- Idempotent: Bring all remote servers into a desired state. suppose out of 4 servers one is running 4 application, another 3 and another one each so ansible can bring all 4 servers in a desired state of 4 application running on each server.
- code
Ansible vs shell_script vs python
- Installing java through automation can be achieved with shell script or python or Ansible as it is a small program.
- Installing oracle will be tideous and there will be lot of stages involved, shell scripting will not be an easy task so use python as it is platform independent which can be executd on linux or windows machines. Must have python knowledge. you need to login to each node to install.
- Installation through Ansible is easier compare to shell script and pythong, you only login to controller node and run adhoc command or playbook.
- Python over ansible can be used through the API like jira and github.
- code
code
code
Installation Controller & Node
VMware - CentOS
- Method 1:
- Create 3 Centos vm (1 controller, 2 worker)
- All VMs communicate with each other
- Setup network on Controller VM if it is not configured during installation
- [root@controller ~]#nmcli connection add con-name controller ifname ens33 type ethernet autoconnect yes
- [root@controller ~]#nmcli connection show
- [root@controller ~]#nmcli connection up controller
- [root@controller ~]#ifconfig
- [root@controller ~]#ping 192.168.171.50
- setup hostname:
- [root@controller ~]#hostnamectl set-hostname controller
- [root@controller ~]#hostname
- DNS setup:
- [root@controller ~]#vim etc/hosts (make entry 192.168.171.50 controller & 192.168.171.51 worker1 & 192.168.171.52 worker2) save it
- [root@controller ~]ping controller (ping with hostname )
- configure the above steps on worker1 & worker2
- Install SSH:
- ssh installed by default in most of the linux O/S.
- Ansible is agentless as there is no furhter application/plugins/add on are required for connection like in puppet.
- puppet has agent based communication where puppet will not use ssh rather it use its own tool to make conneciton.
- check ssh installed: $rpm -qa | grep openssh or $sudo systemctl status sshd
- install ssh on CentOS:
- $sudo yum –y install openssh-server openssh-clients
- $sudo systemctl start sshd
- Install ssh on ubuntu:
- $sudo apt install -y openssh-server
- connect to worker1: $ssh worker1/192.168.171.51 (click yes to make conneciton with sha key)
- When any task is pushed from controller to worker node it has to use any username, root user usually not used. user privilege depend upon users.
- root user: set password
- Install Ansible on controller only:
- $yum install epel-release
- $yum install python3-pip
- $yum install ansible* -y
- $ansible --version
- Inventory: information of nodes are stored in this file, when controller perform any task it reads its inventory file to get worker node information.
- you will define worker node ip username and password in inventory file.
- the location of inventory file can be seen in config file, the location of config file can get through $ansible --version (/etc/ansible/ansible.cfg)
- $vim /etc/ansible/ansible.cfg (location of inventory = /etc/ansible/hosts)
- $vim /etc/ansible/hosts (enter the details of nodes, 192.168.171.51 & 192.168.171.52)
- check hosts:
- $ansible 192.168.171.51 --list-hosts or
- $ansible all --list-hosts
- in the above ips are mentioned one by one, you can make a group and add them
- [ansible-clients] write all ips in the lines below
- check with group ID: $ansible web-server --list-hosts
- define username and password in hosts file
- [ansible-clients]
- 192.168.171.51 ansible_ssh_user=root ansible_ssh_pass=Trustu786
- 192.168.171.52 ansible_ssh_user=root ansible_ssh_pass=Trustu786
- Normal User: add users on controller
- $adduser harry $passwd harry
- $adduser natasha $passwd natasha
- $adduser sarah $passwd sarah
- Login with any user
- check user permission for the folder /etc/ansible/ansible.cfg
- $getfacl /etc/ansible/ansible.cfg
- Create a folder on user home directory for harry, natasha, sarah $mkdir /home/harry/harry_inventory
- $vim abc
- [web]
- 192.168.171.51 (save and exit)
- Set permission to users for /etc/ansible/ansible.cfg to make changes
- $setfacl -m u:harry:rwx /etc/ansible/ansible.cfg
- $setfacl -m u:natasha: rwx /etc/ansible/ansible.cfg
- $setfacl -m u:sarah: rwx /etc/ansible/ansible.cfg
- user can change location of hosts file in ansible.cfg
- $vim /etc/ansible/ansible.cfg (change location of inventory = /home/harry/myinventory/abc ) remove #
- user can login with its credentials and work. $ansible web --list-hosts
- Enable Password based authentication:
- $sudo vi /etc/ssh/sshd_config (PasswordAuthentication yes), save & exit
- $sudo service sshd restart (ubuntu)
- $sudo systemctl restart sshd.service (centos)
- Create a usere and give admin/root rights
- $adduser ansible
- $sudo visudo (add line (ansible ALL=(ALL:ALL) NOPASSWD:ALL))
- Enable Passwordless authentication to nodes
- $ssh-keygen (This Step is to create SSH Key for your user logged in. The Generated SSH Key file would be placed in Home Directory of the current user under .ssh directory
- $ls ~/.ssh (id_rsa & id_rsa.pub) copy public id to nodes so it can login to nodes withouts password.
- $ssh-copy-id username@IP
- $ssh ip (no username & password required)
- $cd ~/.ssh
- $ls authorized keys
- Method 2:
- install from EPEL in CentOS
- [root@dlp ~]# yum --enablerepo=epel -y install ansible openssh-clients
- or
- [root@ansible-server ~]# sudo yum install epel-release & [root@ansible-server ~]# sudo yum install -y ansible
- Set worker nodes for management
- edit this file /etc/ansible/hosts and add IP's of worker nodes.
- 192.168.171.51 ansible_ssh_user=root ansible_ssh_pass=Trustu786
- 192.168.171.52 ansible_ssh_user=root ansible_ssh_pass=Trustu786
VMWare - Ubuntu
-
- Method 1: Install Ansible on CentOS
- Step1: update system
- Step2: Install EPEL Repository
- Step3: Install Ansible on CentOS
- Step4: Configure SSH Access
- Step5: Add worker nodes in hosts file
- Step6: Test connection with worker nodes.
- Installing Ansible & python on Centos
- Step 1: update CentOS:
- Step 2: Install epel repository:
- $sudo yum install epel-release (Ansible is not available in the default CentOS repositories. Therefore, we need to install the EPEL (Extra Packages for Enterprise Linux) repository, which contains the Ansible package.)
- $sudo yum repolist (check epel repository is installed, You should see the EPEL repository listed in the output)
- Step 3: Install Ansible
- $sudo yum install ansible
- $ansible --version (it will give version, location of ansible.cfg file which contain location of hosts file)
- Step 4: Configure SSH Access & Passwordless Authentication:
- Ansible communicates with remote servers using SSH. Therefore, we need to ensure that SSH access is properly configured on our CentOS system. To do this, we need to generate an SSH key pair and copy the public key to the remote servers we want to manage.
- There are two types of authentication (password and passworless using key)
- Passwordless Authentication: $ssh-keygen (This command will generate a public-private key pair in the ~/.ssh directory)
- It can be achieved with two ways, copy the public key to remote system or provide password one time.
- copy the public key to remote/worker nodes. $ssh-copy-id user@remote-server (Replace “user” with your username on the remote server and “remote-server” with the IP address or hostname of the remote server)
- copy the public key to remote/workernodes in EC2 instance. $ssh-copy-id -f "-f IdentityFile <PATH to PEM FILE>" ubuntu@publicIP
- ssh-copy-id: This is the command used to copy your public key to a remote machine.
- -f: This flag forces the copying of keys, which can be useful if you have keys already set up and want to overwrite them.
- "-o IdentityFile ": This option specifies the identity file (private key) to use for the connection. The -o flag passes this option to the underlying ssh command.
- ubuntu@PublicIP: This is the username (ubuntu) and the IP address of the remote server you want to access.
- Password based authentication: Go to the file /etc/ssh/ and edit sshd_config and remove # before passwordauthentication yes.
- password based authentication in EC2 instance: login to ec2 and go to vim /etc/ssh/sshd_config.d/60-cloudimg-settings.conf and change PasswordAuthentication yes
- $sudo systemctl restart sshd (in Centos)
- $sudo systemctl restart ssh (in ubuntu)
- $ssh user@IP (system will not ask for password and login to worker node)
- Step 5: Add worker nodes in the hosts file
- Install python on all nodes.
- edit the file /etc/ansible/hosts and add (worker1 ansible_host=192.168.171.51 ansible_user=abdul) or run the command
- $echo worker1 ansible_host=192.168.171.51 ansible_user=abdul >> /etc/ansible/hosts (worker1 is node hostname, worker1 IP address, abdul is a user in worker1, it will be added in /etc/ansible/hosts file)
- Group the worker nodes
- edit the file /etc/ansible/hosts and add
- [web]
- worker1 ansible_host=192.168.171.51 ansible_user=abdul
- worker2 ansible_host=192.168.171.52 ansible_user=abdul
- Step 6: Test Ansible connection with worker nodes:
- $ansible all -m ping (it will ping all the worker nodes defined in host file)
- $ansible web -m ping (it will ping nodes of web group defined in host file)
- Method1: Install Ansible on Ubuntu
- $pip install ansible (ubuntu: it will install python and ansible together)
- Method 2:
- Step1: Create controller and worker nodes Insatances/VM (1Controller, 3 nodes), ping each other with hostname.
- Network Setup to get an IP with dhcp and internet access on instances or linux machines.
- $nmcli connection add con-name controller ifname ens33 type ethernet autoconnect yes
- $nmcli connection show
- $nmcli connection up ansible-controller
- $ifconfig
- Step2: Set hostname:
- $sudo hostnamectl set-hostname controller (add in local host file /etc/hosts if there is no DNS)
- Set the hostname on all nodes.
- Step3: enable password based authentication (perform in all controller and nodes)
- $sudo vi /etc/ssh/sshd_config (PasswordAuthentication yes)
- $sudoservice sshd restart
- Step4: Create a user (ansible) with admin rights. (optional), if you create user with admin right then following commands can run without using sudo.
- $adduser ansible
- $sudo visudo add (ansible ALL=(ALL:ALL) NOPASSWD:ALL) (ansible gets sudo permissoins)
- logout and login with ansible user with password.($exit, $su ansible)
- ansible@ip:$cd ~ (home directory of ansible)
- ansible@ip:~$sudo apt-get update (should not ask for password as user ansible added in sudo permission)
- on windows based lab setup, open powershell as an administrator and run c:\choco install git -y (it will install terminal for git which gives linux capability from windows or on google search git for windows & install)
- Step5: Install python 2 ( By default in every linux machine python 3 is installed, check with #python3 --version, if you use python --version it will check for python 2). Ansible can work on python 3 but need to install some patches.
- $sudo apt-get update
- $sudo apt-get -y dist-upgrade (it will upgrade to older version of apt repository)
- $sudo apt-get install -y python2.7 python-pip
- Step6: Login into ansible server and enable passwordless authentication to node
- #ssh deveops@controllerPublicIP (.pem file not required as we enable password authentication ) enter password.
- #ssh-keygen
- #ls ~/.ssh/ (id_rsa id_rsa.pub) copy public id to nodes so it can login to node withou password.
- #ssh-copy-id ansible@nodesprivateIPorpublicIP (now you can login to node with ip address only)
- #ssh nodeprivateIP (no username and password required) #cd ~/.ssh #ls authorized keys (it is stored ansible controller details)
- Step8: Install Ansible on controller. visit https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html
- $ sudo apt-get install software-properties-common
- $ sudo apt-add-repository --yes --update ppa:ansible/ansible (this will upgrade to the latest version of ansible)
- $ sudo apt-get update
- $ sudo apt install ansible -y
- if controller is centos#yum install ansible* -y ( if you get an error: No package ansible available, nothing to do, then install #yum install epel-release)
- #python --version,
- #ansible --version
Nodes:
- Step7: Login to nodes and create user and enable password based authentication (give admin rights) and install only python2.7
- $sudo apt-get update
- $sudo apt-get -y dist-upgrade (it will upgrade to older version of apt repository)
- $sudo apt-get install -y python2.7 python-pip
Communication between controller and workers are though SSH. By default in all linux softwares SSH package is installed, you do not need to install any Addons on worker nodes as it uses SSH for communication and SSH is installed by default. In case of puppet it does not use SSH but rather it uses it own tool to make connection with worker nodes.
#rpm -qa | grep openssh (to check SSH is intalled in centos and redhat)
- Inventory: information of nodes are stored in this file, when controller perform any task it reads its inventory file to get worker node information.
- you will define worker node ip username and password in inventory file.
- the location of inventory file can be seen in config file, the location of config file can get through $ansible --version (/etc/ansible/ansible.cfg)
- $vim /etc/ansible/ansible.cfg (location of inventory = /etc/ansible/hosts)
- $vim /etc/ansible/hosts (enter the details of nodes, 192.168.171.51 & 192.168.171.52)
- check: $ansible 192.168.171.51 --list-hosts or $ansible all --list-hosts
- in the above ips are mentioned one by one, you can make a group and add them
- [ansible-clients] write all ips in the lines below
- check with group ID: $ansible web-server --list-hosts
- define username and password in hosts file
- [ansible-clients]
- 192.168.171.51 ansible_ssh_user=root ansible_ssh_pass=Trustu786
- 192.168.171.52 ansible_ssh_user=root ansible_ssh_pass=Trustu786
- Normal User: add users on controller
- $adduser harry $passwd harry
- $adduser natasha $passwd natasha
- $adduser sarah $passwd sarah
- Login with any user
- check user permission for the folder /etc/ansible/ansible.cfg
- $getfacl /etc/ansible/ansible.cfg
- Create a folder on user home directory for harry, natasha, sarah $mkdir /home/harry/harry_inventory
- $vim abc
- [web]
- 192.168.171.51 (save and exit)
- Set permission to users for /etc/ansible/ansible.cfg to make changes
- $setfacl -m u:harry:rwx /etc/ansible/ansible.cfg
- $setfacl -m u:natasha: rwx /etc/ansible/ansible.cfg
- $setfacl -m u:sarah: rwx /etc/ansible/ansible.cfg
- user can change location of hosts file in ansible.cfg
- $vim /etc/ansible/ansible.cfg (change location of inventory = /home/harry/myinventory/abc ) remove #
- user can login with its credentials and work. $ansible web --list-hosts
- Method 3:
- step1: $ sudo apt update
- Step2: $ sudo apt install software-properties-common
- Step3: $ sudo apt-add-repository ppa:ansible/ansible
- Step4: $ sudo apt update & $ sudo apt install ansible
- code
Docker Installation - CentOS
- using shell command and run script
- Docker Install with playbook
-
---
- name: Install docker
gather_facts: No
hosts: default
tasks:
- name: Install yum utils
yum:
name: yum-utils
state: latest
- name: Install device-mapper-persistent-data
yum:
name: device-mapper-persistent-data
state: latest
- name: Install lvm2
yum:
name: lvm2
state: latest
- name: Add Docker repo
get_url:
url: https://download.docker.com/linux/centos/docker-ce.repo
dest: /etc/yum.repos.d/docer-ce.repo
become: yes
- name: Enable Docker Edge repo
ini_file:
dest: /etc/yum.repos.d/docer-ce.repo
section: 'docker-ce-edge'
option: enabled
value: 0
become: yes
- name: Enable Docker Test repo
ini_file:
dest: /etc/yum.repos.d/docer-ce.repo
section: 'docker-ce-test'
option: enabled
value: 0
become: yes
- name: Install Docker
package:
name: docker-ce
state: latest
become: yes
- name: Start Docker service
service:
name: docker
state: started
enabled: yes
become: yes
- name: Add user vagrant to docker group
user:
name: vagrant
groups: docker
append: yes
become: yes
- code
code
code
code
code
Other Configuration
Inventory:
Custom Inventory:
- #mkdir myinventory, #cd myinventory #vim /custominventory (enter nodes IP addresses or groups and IP)
- #ansible all --list-hosts -i /myinventory/custominventory (you need to define path for custom inventory, change default path /etc/ansible/ansible.cfg to custom path.
- If you do not mentions inventory file then it will take default inventory file.
Normal User creation and access
- Create normal user on ansible-controller and login with a user.
- Inventory file for user is default and user does not have permission to change.
- Create config file for every user.
- Set custom inventory folder and file for users.
- Copy inventory file
- Amend file
- Set environment varilable, If a user cannot set environment varilable then copy config file in its home folder.
- code
- code
skip host key to access nodes:
- if you login with root/user in controller then ansible will look same user in all nodes to run the task on nodes. it will prompt for host key verification by finger print confirmation, if you got many nodes then you need to confirm the "yes" for every node, in SSH it generates finger print first time.
- $ansible --version (to check ansible which configuration file is reading for logged in user)
- $vi /etc/ansible/ansible.cfg (default) (search /host_key checking, #host_key checking = false, remove comment) run the command host key verification not perform. Get an error of public key and it assumes that it is a passwordless communication. perform passwordless
- #ansible web -m command -a "uptime" -k (-k will prompt to enter password) or can generate key with ssh-keygen
- $ssh-keygen on controller and copy id_rsa.pub in all nodes, can do with automation
- ~$ ls .ssh /#ls (id_rsa id_rsa.pub)
- #ssh-copy-id -i root@node1IP (repeat for other nodes)
- enter passwords.
- $ssh node_IP (will not prompt for username/password)
- code
code
code
code
Ansible Adhoc-command & Modules:
- consider ansible ad-hoc commands as shell commands and a playbook as a shell script. script where multiple commands and instructions can be given.
- if module is not available for any task then can perform through command module and enter command in syntax.
- $ansible 'all/group_name/ipaddress' -i 'path_of_inventory_file' -m 'module_name' -a 'argument', if you do not define -m then it will consider it as command module by default
- $ansible all -i /etc/ansible/hosts -m "command" -a 'ls -la' (all = all nodes, -i = inventory file, -m = module, command=command module, -a = argument, command should be in quote)
- $ansible-doc -l (list of all modules)
- $ansible-doc copy (details of copy module)
- some adhoc command examples
- Modules:
command/ansible.builtin.command & raw module
- Execute linux commands if there is no specific module is available in ansible.
- Execute a command as root user (sudo) host: In the earlier versions of ansible there is an option named as sudo (deprecated), Since ansible 2.0 there are two new options named as become and become_user
- $ansible all -m shell -a "cat /etc/passwd|grep -i abdul" -b -K
- -b is the option for become and by default it will become root user
-K is to tell ansible to ask for SUDO password
- Execute a command as a different user (sudo su): In this example, we are going to create a new directory inside a directory /home/abdul/binaries which is owned by abdul user
- $ansible all -m file -a "path=/home/abdul/binaries state=directory mode=0755" -b –become-user=abdul
- List hosts:
- $ansible all --list-hosts (it will list all hosts defined in inventory file)
- $ansible --version (you can view location of config file: /etc/ansible/ansible.cfg)
- $vim /etc/ansible/ansible.cfg (check location of inventory file: /etc/ansible/hosts)
- Memory Usage:
- $ansible all -a 'free' (it will display memory usage in all nodes)
- $ansible all -a 'free -m'
- Physical Memory allocated to the host: using two commands
- $ansible all -m shell -a "cat /proc/meminfo|head -3"
- Check free disk space:
- list nfs mounts:
- we are using the shell module and executing df -h -T to display the mount
- $ansible web -m shell -a 'df -h -T
- we are using the shell module and executing df -h -T to display the type of mount and filtering only nfs type mounts with the help of grep command.
- $ansible web -m shell -a 'df -h -T|grep -i nfs'
- Date Display
- reboot nodes
- uptime
- $ansible all -a 'uptime'
- $ansible all -m command -a 'uptime'
- $ansible all -m shell -a 'uptime'
- Display memory, cpu and OS distribution and version:
- we have used Ansible setup module with filter to select necassary attributes of a system.
- To know more about what other ansible_facts or variables you can possibly use in this filter. read article.
- ansible web -m setup -a 'filter=ansible_distribution,ansible_distribution_version,ansible_memfree_mb,ansible_memtotal_mb,ansible_processor_cores*,ansible_architecture' 2>/dev/null
- check listening ports:
- To check the list of open ports you can use netstat or ss commands over the Ansible shell module but the preferred way is to use the ansible community plugin listen_ports_facts module.
- $ansible web -m listen_ports_facts
- $ansible web -m listen_ports_facts -i prod-ansible-hosts
- create file
- $ansible all -a 'touch file1'
- $ansible all -m file -a "path=/tmp/testfile state=touch mode=0755"
- list files
- Change ownership of a file:
- $ansible all -m file -a "path=/tmp/testfile group=stargroup owner=testuser1" -b
- Create a Directory with 755 permission:
- $ansible all -m file -a "path=/home/abdul/oracle state=directory mode=0755" -b
- Copy file - Local to remote
- The following ad hoc command with copy module copies the file from Src location on the local control machine to the specified location on the remote server
- $ansible web -m copy -a "src=/root/roles/testrole1/files/index.html dest=/var/www/html owner=testuser1 group=stargroup mode=0644" (copies index.html from root/roles/testrole1/files/ folderto /var/www/html folder.
- Copy Directory - local to remote
- ansible web -m copy -a "src=/root/data dest=/root owner=testuser1 group=stargroup mode=0644 " -b
- Create a user group:
- $ansible all -m group -a "name=stargroup state=present"
- to delete change state=absent
- Create a user
- $ansible all -m user -a "name=testuser1 group=stargroup createhome=yes" -b (stargroup is already exist)
- multiple commands use
- $ansible all -m raw -a 'ls;date;uptime'
- Download a file from URL:
- To download a file from URL in ansible ad hoc. You can either invoke linux commands like CURL or WGET but the preferred way is to use the get_url module of Ansible.
- $ansible web -m get_url -a "url=https://nodejs.org/dist/v14.17.4/node-v14.17.4-linux-x64.tar.xz dest=/tmp mode=0755"
- read more about get_url module in our dedicated article
- Install package using yum module:
- $ansible all -m yum -a "name=httpd state=installed" (install Apache)
- $ansible all -m yum -a "name=httpd state=latest" (Install Apache with latest version)
- $ansible all -m yum -a "name=httpd state=absent" (Remove Apache)
- $ansible all -m service -a "name=httpd state=started enabled=yes" (start and enable httpd service)
- $ansible all -m service -a "name=httpd state=stop enabled=yes" (stop httpd service)
- Install and configure python Django application server:
- These are set of commands you have to execute to install the Django application server and Mysql libraries. Here we are using easy_install which is an ansible module it helps to find the easy installation option from ansible galaxy
- $ ansible app -s -m yum -a "name=MySQL-python state=present"
$ ansible app -s -m yum -a "name=python-setuptools state=present"
$ ansible app -s -m easy_install -a "name=django"
- Managing Cron Job and Scheduling:
- # Run the job every 15 minutes
$ ansible multi -m cron -a "name='daily-cron-all-servers' minute=*/15
job='/path/to/minute-script.sh'"
- # Run the job every four hours
$ ansible multi -m cron -a "name='daily-cron-all-servers' hour=4
job='/path/to/hour-script.sh'"
- # Enabling a Job to run at system reboot
$ ansible multi -m cron -a "name='daily-cron-all-servers' special_time=reboot
job='/path/to/startup-script.sh'"
- # Scheduling a Daily job
$ ansible multi -m cron -a "name='daily-cron-all-servers' special_time=daily
job='/path/to/daily-script.sh'"
- # Scheduling a Weekly job
$ ansible multi -m cron -a "name='daily-cron-all-servers' special_time=weekly
job='/path/to/daily-script.sh'"
- reboot the system:
- $ansible all -b -B 1 -P 0 -m shell -a "sleep 5 && reboot"
- $ansible all -m reboot -a reboot_timeout=3600 -u abdul -b
- -m - represents the module
-a - additional parameter to the reboot module to set the timeout to 3600 seconds
-u - remote SSH user
-i - inventory file
-b - to instruct ansible to become root user before executing the task
- check the service status:
- $ansible web -m service -a "name=httpd"
- $ansible web -m service -a "name=httpd" -u abdul
- $ansible web -m service -a "name=httpd" -i /home/abdul/inventory/ansible_hosts -u vagrant
- stop, start, restart nginx service:
- Simple way to restart any service with Ansible adhoc command is to use Shell module with the actual service or systemctl command
- $ansible web -m shell -a "service nginx restart" -b
- $ansible web -m shell -a "systemctl restart nginx" -b
- You can also use Ansible's built in systemd module otherwise like this.
- $ ansible web -m systemd -a "name=nginx state=reloaded"
$ ansible web -m systemd -a "name=nginx state=restarted"
$ ansible web -m systemd -a "name=nginx state=started"
$ ansible web -m systemd -a "name=nginx state=stopped"
-
- name: Return motd to registered var
ansible.builtin.command: cat /etc/motd
register: mymotd
# free-form (string) arguments, all arguments on one line
- name: Run command if /path/to/database does not exist (without 'args')
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name creates=/path/to/database
# free-form (string) arguments, some arguments on separate lines with the 'args' keyword
# 'args' is a task keyword, passed at the same level as the module
- name: Run command if /path/to/database does not exist (with 'args' keyword)
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name
args:
creates: /path/to/database
# 'cmd' is module parameter
- name: Run command if /path/to/database does not exist (with 'cmd' parameter)
ansible.builtin.command:
cmd: /usr/bin/make_database.sh db_user db_name
creates: /path/to/database
- name: Change the working directory to somedir/ and run the command as db_owner if /path/to/database does not exist
ansible.builtin.command: /usr/bin/make_database.sh db_user db_name
become: yes
become_user: db_owner
args:
chdir: somedir/
creates: /path/to/database
# argv (list) arguments, each argument on a separate line, 'args' keyword not necessary
# 'argv' is a parameter, indented one level from the module
- name: Use 'argv' to send a command as a list - leave 'command' empty
ansible.builtin.command:
argv:
- /usr/bin/make_database.sh
- Username with whitespace
- dbname with whitespace
creates: /path/to/database
- name: Run command using argv with mixed argument formats
ansible.builtin.command:
argv:
- /path/to/binary
- -v
- --debug
- --longopt
- value for longopt
- --other-longopt=value for other longopt
- positional
- name: Safely use templated variable to run command. Always use the quote filter to avoid injection issues
ansible.builtin.command: cat {{ myfile|quote }}
register: myoutput
shell/ansible.builtin.shell:
- Execute shell commands on targets: click for more details.
- $ansible all -m shell -a 'curl -fsSL https://get.docker.com -o get-docker.sh' (This example downloads the script from https://get.docker.com/ and runs it to install the latest stable release of Docker on Linux:)
- $ansible all -m shell -a 'sh get-docker.sh' or $ansible all -m shell -a "sudo sh ./get-docker.sh --dry-run" (to view the progress)
-
- name: Execute the command in remote shell; stdout goes to the specified file on the remote
ansible.builtin.shell: somescript.sh >> somelog.txt
- name: Change the working directory to somedir/ before executing the command
ansible.builtin.shell: somescript.sh >> somelog.txt
args:
chdir: somedir/
# You can also use the 'args' form to provide the options.
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist
ansible.builtin.shell: somescript.sh >> somelog.txt
args:
chdir: somedir/
creates: somelog.txt
# You can also use the 'cmd' parameter instead of free form format.
- name: This command will change the working directory to somedir/
ansible.builtin.shell:
cmd: ls -l | grep log
chdir: somedir/
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
ansible.builtin.shell: cat < /tmp/*txt
args:
executable: /bin/bash
- name: Run a command using a templated variable (always use quote filter to avoid injection)
ansible.builtin.shell: cat {{ myfile|quote }}
# You can use shell to run other executables to perform actions inline
- name: Run expect to wait for a successful PXE boot via out-of-band CIMC
ansible.builtin.shell: |
set timeout 300
spawn ssh admin@{{ cimc_host }}
expect "password:"
send "{{ cimc_password }}\n"
expect "\n{{ cimc_name }}"
send "connect host\n"
expect "pxeboot.n12"
send "\n"
exit 0
args:
executable: /usr/bin/expect
delegate_to: localhost
ping
- we are going to test the remote nodes or hosts and make sure they respond back using Ansible's default SSH channel.
- You can make sure that the hosts are accessible from the ansible server by issuing a ping command on all hosts. ssh key-based authentication is setup.
- $ansible all -m ping (ping to all worker nodes)
- $ansible web -m ping
- ansible multi -m ping -i ansible_hosts – user=vagrant (defined inventory file and user)
- Do not have SSH key-based authentication, then enter the user name and password while invoking the command as shown below.
- $ansible web -m ping -i ansible_hosts –user=root --ask-vault-pass
user or ansible.builtin.user
- Manage user accounts: ansible.builtin.user
- This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name user even without specifying the collections keyword. However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.user for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.
-
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
ansible.builtin.user:
name: johnd
comment: John Doe
uid: 1040
group: admin
-
- name: Create a user 'johnd' with a home directory
ansible.builtin.user:
name: johnd
create_home: yes
-
- name: Remove the user 'johnd'
ansible.builtin.user:
name: johnd
state: absent
remove: yes
-
- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
ansible.builtin.user:
name: jsmith
generate_ssh_key: yes
ssh_key_bits: 2048
ssh_key_file: .ssh/id_rsa
-
- name: Added a consultant whose account you want to expire
ansible.builtin.user:
name: james18
shell: /bin/zsh
groups: developers
expires: 1422403387
-
- name: Starting at Ansible 2.6, modify user, remove expiry time
ansible.builtin.user:
name: james18
expires: -1
-
- name: Set maximum expiration date for password
ansible.builtin.user:
name: ram19
password_expire_max: 10
-
- name: Set minimum expiration date for password
ansible.builtin.user:
name: pushkar15
password_expire_min: 5
-
- name: Set number of warning days for password expiration
ansible.builtin.user:
name: jane157
password_expire_warn: 30
- code
group/ansible.builtin.group
- Add or remove groups
-
- name: Create group "stargroup" exists
ansible.builtin.group:
name: stargroup
state: present
- name: Ensure group "docker" exists with correct gid
ansible.builtin.group:
name: docker
state: present
gid: 1750
- code
copy/ansible.builtin.copy
- The copy module copies a file from the local/remote machine to a location on the remote machine. Use the [fetch] module to copy files from remote locations to the local box. click here for more details.
- $ansible all -m copy -a "src=/etc/passwd dest=/tmp" (copies passwd file to /tmp folder in destination)
- $ansible all -m copy -a "src=/etc/group dest=/tmp owner=kubernetes" (while copying the group file in the destination in changes the owner to kubernetes, the user kubernetes must exist in the destination)
- $id kubernetes (find out user kubernetes exist)
-
- name: Copy file with owner and permissions
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Copy file with owner and permission, using symbolic representation
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
- name: Another symbolic mode example, adding some permissions and removing others
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u+rw,g-wx,o-rwx
- name: Copy a new "ntp.conf" file into place, backing up the original if it differs from the copied version
ansible.builtin.copy:
src: /mine/ntp.conf
dest: /etc/ntp.conf
owner: root
group: root
mode: '0644'
backup: yes
- name: Copy a new "sudoers" file into place, after passing validation with visudo
ansible.builtin.copy:
src: /mine/sudoers
dest: /etc/sudoers
validate: /usr/sbin/visudo -csf %s
- name: Copy a "sudoers" file on the remote machine for editing
ansible.builtin.copy:
src: /etc/sudoers
dest: /etc/sudoers.edit
remote_src: yes
validate: /usr/sbin/visudo -csf %s
- name: Copy using inline content
ansible.builtin.copy:
content: '# This file was moved to /etc/other.conf'
dest: /etc/mine.conf
- name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf
ansible.builtin.copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: yes
- name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf
ansible.builtin.copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: no
fetch
- fetch module to copy files from remote locations to the local box.
- code
- code
synchronize
file/ansible.builtin.file
- The file module manages the file and its properties.
- $ansible-doc file
- $ansible all -m
-
- name: Change file ownership, group and permissions
ansible.builtin.file:
path: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Give insecure permissions to an existing file
ansible.builtin.file:
path: /work
owner: root
group: root
mode: '1777'
- name: Create a symbolic link
ansible.builtin.file:
src: /file/to/link/to
dest: /path/to/symlink
owner: foo
group: foo
state: link
- name: Create two hard links
ansible.builtin.file:
src: '/tmp/{{ item.src }}'
dest: '{{ item.dest }}'
state: hard
loop:
- { src: x, dest: y }
- { src: z, dest: k }
- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
ansible.builtin.file:
path: /etc/foo.conf
state: touch
mode: u=rw,g=r,o=r
- name: Touch the same file, but add/remove some permissions
ansible.builtin.file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
- name: Touch again the same file, but do not change times this makes the task idempotent
ansible.builtin.file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
modification_time: preserve
access_time: preserve
- name: Create a directory if it does not exist
ansible.builtin.file:
path: /etc/some_directory
state: directory
mode: '0755'
- name: Update modification and access time of given file
ansible.builtin.file:
path: /etc/some_file
state: file
modification_time: now
access_time: now
- name: Set access time based on seconds from epoch value
ansible.builtin.file:
path: /etc/another_file
state: file
access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'
- name: Recursively change ownership of a directory
ansible.builtin.file:
path: /etc/foo
state: directory
recurse: yes
owner: foo
group: foo
- name: Remove file (delete file)
ansible.builtin.file:
path: /etc/foo.txt
state: absent
- name: Recursively remove directory
ansible.builtin.file:
path: /etc/foo
state: absent
- code
stat
debug/ansible.builtin.debug
- The debug module prints statements during execution and can be useful for debugging variables or expressions without having to halt the playbook. click here for more details.
-
- name: Print the gateway for each host when defined
ansible.builtin.debug:
msg: System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}
when: ansible_default_ipv4.gateway is defined
- name: Get uptime information
ansible.builtin.shell: /usr/bin/uptime
register: result
- name: Print return information from the previous task
ansible.builtin.debug:
var: result
verbosity: 2
- name: Display all variables/facts known for a host
ansible.builtin.debug:
var: hostvars[inventory_hostname]
verbosity: 4
- name: Prints two lines of messages, but only if there is an environment value set
ansible.builtin.debug:
msg:
- "Provisioning based on YOUR_KEY which is: {{ lookup('ansible.builtin.env', 'YOUR_KEY') }}"
- "These servers were built using the password of '{{ password_used }}'. Please retain this for later use."
- code
apt (package management)
yum or ansible.builtin.yum (package management)
- You can Install, upgrade, downgrades, removes, and lists packages and groups with the yum package manager.
- This module only works on Python 2. If you require Python 3 support see the dnf module.
- This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name yum even without specifying the collections keyword. However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.yum for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.
- Requirements: yum must be available on the host that executes this module.
-
- name: Install the latest version of Apache
ansible.builtin.yum:
name: httpd
state: latest
-
- name: Install Apache >= 2.4
ansible.builtin.yum:
name: httpd>=2.4
state: present
-
- name: Remove the Apache package
ansible.builtin.yum:
name: httpd
state: absent
-
- name: Install the latest version of Apache from the testing repo
ansible.builtin.yum:
name: httpd
enablerepo: testing
state: present
-
- name: Install one specific version of Apache
ansible.builtin.yum:
name: httpd-2.2.29-1.4.amzn1
state: present
-
- name: Install a list of packages nginx, postgresql, postgresql-server (suitable replacement for 2.11 loop deprecation warning)
ansible.builtin.yum:
name:
- nginx
- postgresql
- postgresql-server
state: present
-
- name: Install a list of packages with a list variable
ansible.builtin.yum:
name: "{{ packages }}"
vars:
packages:
- httpd
- httpd-tools
-
- name: Upgrade all packages
ansible.builtin.yum:
name: '*'
state: latest
-
- name: Upgrade all packages, excluding kernel & foo related packages
ansible.builtin.yum:
name: '*'
state: latest
exclude: kernel*,foo*
-
- name: Install the nginx rpm from a remote repo
ansible.builtin.yum:
name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
-
- name: Install nginx rpm from a local file
ansible.builtin.yum:
name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
-
- name: Install the 'Development tools' package group
ansible.builtin.yum:
name: "@Development tools"
state: present
-
- name: Install the 'Gnome desktop' environment group
ansible.builtin.yum:
name: "@^gnome-desktop-environment"
state: present
-
- name: List ansible packages and register result to print with debug later
ansible.builtin.yum:
list: ansible
register: result
-
- name: Install package with multiple repos enabled
ansible.builtin.yum:
name: sos
enablerepo: "epel,ol7_latest"
-
- name: Install package with multiple repos disabled
ansible.builtin.yum:
name: sos
disablerepo: "epel,ol7_latest"
-
- name: Download the nginx package but do not install it
ansible.builtin.yum:
name:
- nginx
state: latest
download_only: true
- code
git/ansible.builtin.git
- The git module manages git checkouts of repositories to deploy files or software.
-
- name: Git checkout
ansible.builtin.git:
repo: 'https://foosball.example.org/path/to/repo.git'
dest: /srv/checkout
version: release-0.22
- name: Read-write git checkout from github
ansible.builtin.git:
repo: git@github.com:mylogin/hello.git
dest: /home/mylogin/hello
- name: Just ensuring the repo checkout exists
ansible.builtin.git:
repo: 'https://foosball.example.org/path/to/repo.git'
dest: /srv/checkout
update: no
- name: Just get information about the repository whether or not it has already been cloned locally
ansible.builtin.git:
repo: 'https://foosball.example.org/path/to/repo.git'
dest: /srv/checkout
clone: no
update: no
- name: Checkout a github repo and use refspec to fetch all pull requests
ansible.builtin.git:
repo: https://github.com/ansible/ansible-examples.git
dest: /src/ansible-examples
refspec: '+refs/pull/*:refs/heads/*'
- name: Create git archive from repo
ansible.builtin.git:
repo: https://github.com/ansible/ansible-examples.git
dest: /src/ansible-examples
archive: /tmp/ansible-examples.zip
- name: Clone a repo with separate git directory
ansible.builtin.git:
repo: https://github.com/ansible/ansible-examples.git
dest: /src/ansible-examples
separate_git_dir: /src/ansible-examples.git
- name: Example clone of a single branch
ansible.builtin.git:
repo: https://github.com/ansible/ansible-examples.git
dest: /src/ansible-examples
single_branch: yes
version: master
- name: Avoid hanging when http(s) password is missing
ansible.builtin.git:
repo: https://github.com/ansible/could-be-a-private-repo
dest: /src/from-private-repo
environment:
GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password
# or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password
- code
replace
service
- After installing a package, you need a module to start it. The service module enables you to start, stop, and reload installed packages; click here for more details.
-
- name: Start service httpd, if not started
ansible.builtin.service:
name: httpd
state: started
- name: Stop service httpd, if started
ansible.builtin.service:
name: httpd
state: stopped
- name: Restart service httpd, in all cases
ansible.builtin.service:
name: httpd
state: restarted
- name: Reload service httpd, in all cases
ansible.builtin.service:
name: httpd
state: reloaded
- name: Enable service httpd, and not touch the state
ansible.builtin.service:
name: httpd
enabled: yes
- name: Start service foo, based on running process /usr/bin/foo
ansible.builtin.service:
name: foo
pattern: /usr/bin/foo
state: started
- name: Restart network service for interface eth0
ansible.builtin.service:
name: network
state: restarted
args: eth0
- code
include
uri
get_url
docker_container
docker_login
docker_image
setup
lineinfile/ansible.builtin.lineinfile
- The lineinfile module manages lines in a text file.
-
# NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Ensure SELinux is set to enforcing mode
ansible.builtin.lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=enforcing
- name: Make sure group wheel is not in the sudoers configuration
ansible.builtin.lineinfile:
path: /etc/sudoers
state: absent
regexp: '^%wheel'
- name: Replace a localhost entry with our own
ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '^127\.0\.0\.1'
line: 127.0.0.1 localhost
owner: root
group: root
mode: '0644'
- name: Replace a localhost entry searching for a literal string to avoid escaping
ansible.builtin.lineinfile:
path: /etc/hosts
search_string: '127.0.0.1'
line: 127.0.0.1 localhost
owner: root
group: root
mode: '0644'
- name: Ensure the default Apache port is 8080
ansible.builtin.lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: '^Listen '
insertafter: '^#Listen '
line: Listen 8080
- name: Ensure php extension matches new pattern
ansible.builtin.lineinfile:
path: /etc/httpd/conf/httpd.conf
search_string: '<FilesMatch ".php[45]?$">'
insertafter: '^\t<Location \/>\n'
line: ' <FilesMatch ".php[34]?$">'
- name: Ensure we have our own comment added to /etc/services
ansible.builtin.lineinfile:
path: /etc/services
regexp: '^# port for http'
insertbefore: '^www.*80/tcp'
line: '# port for http by default'
- name: Add a line to a file if the file does not exist, without passing regexp
ansible.builtin.lineinfile:
path: /tmp/testfile
line: 192.168.1.99 foo.lab.net foo
create: yes
# NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes
- name: Ensure the JBoss memory settings are exactly as needed
ansible.builtin.lineinfile:
path: /opt/jboss-as/bin/standalone.conf
regexp: '^(.*)Xms(\d+)m(.*)$'
line: '\1Xms${xms}m\3'
backrefs: yes
# NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- name: Validate the sudoers file before saving
ansible.builtin.lineinfile:
path: /etc/sudoers
state: present
regexp: '^%ADMIN ALL='
line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
validate: /usr/sbin/visudo -cf %s
# See https://docs.python.org/3/library/re.html for further details on syntax
- name: Use backrefs with alternative group syntax to avoid conflicts with variable values
ansible.builtin.lineinfile:
path: /tmp/config
regexp: ^(host=).*
line: \g<1>{{ hostname }}
backrefs: yes
- code
Installation
- Docker
- Tomcat
- Apache
- Jenkins
- Git
- Mysql
- Other
dnf (package management)
- Installs, upgrade, removes, and lists packages and groups with the dnf package manager.
- yum module only works on Python 2. for Python 3 support dnf module.
- - name: install the latest version of Apache and MariaDB
dnf:
name:
- httpd
- mariadb-server
state: latest
- code
- code
cli_command/ansible.netcommon.cli_command
- The cli_command module, first available in Ansible 2.7, provides a platform-agnostic way of pushing text-based configurations to network devices over the network_cli connection plugin.
-
- name: run show version on remote devices
ansible.netcommon.cli_command:
command: show version
- name: run command with json formatted output
ansible.netcommon.cli_command:
command: show version | json
- name: run command expecting user confirmation
ansible.netcommon.cli_command:
command: commit replace
prompt: This commit will replace or remove the entire running configuration
answer: "yes"
- name: run command expecting user confirmation
ansible.netcommon.cli_command:
command: show interface summary
prompt: Press any key to continue
answer: y
newline: false
- name: run config mode command and handle prompt/answer
ansible.netcommon.cli_command:
command: "{{ item }}"
prompt:
- Exit with uncommitted changes
answer: y
loop:
- configure
- set system syslog file test any any
- exit
- name: multiple prompt, multiple answer (mandatory check for all prompts)
ansible.netcommon.cli_command:
command: copy sftp sftp://user@host//user/test.img
check_all: true
prompt:
- Confirm download operation
- Password
- Do you want to change that to the standby image
answer:
- y
- <password>
- y
- code
archive/community.general.archive & unarchive module
- The archive module creates a compressed archive of one or more files. By default, it assumes the compression source exists on the target.
-
- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
community.general.archive:
path: /path/to/foo
dest: /path/to/foo.tgz
- name: Compress regular file /path/to/foo into /path/to/foo.gz and remove it
community.general.archive:
path: /path/to/foo
remove: true
- name: Create a zip archive of /path/to/foo
community.general.archive:
path: /path/to/foo
format: zip
- name: Create a bz2 archive of multiple files, rooted at /path
community.general.archive:
path:
- /path/to/foo
- /path/wong/foo
dest: /path/file.tar.bz2
format: bz2
- name: Create a bz2 archive of a globbed path, while excluding specific dirnames
community.general.archive:
path:
- /path/to/foo/*
dest: /path/file.tar.bz2
exclude_path:
- /path/to/foo/bar
- /path/to/foo/baz
format: bz2
- name: Create a bz2 archive of a globbed path, while excluding a glob of dirnames
community.general.archive:
path:
- /path/to/foo/*
dest: /path/file.tar.bz2
exclude_path:
- /path/to/foo/ba*
format: bz2
- name: Use gzip to compress a single archive (i.e don't archive it first with tar)
community.general.archive:
path: /path/to/foo/single.file
dest: /path/file.gz
format: gz
- name: Create a tar.gz archive of a single file.
community.general.archive:
path: /path/to/foo/single.file
dest: /path/file.tar.gz
format: gz
force_archive: true
Other Modules
Playbook
What is playbook
- Modules can be called either with adhoc method or using file (yaml /json file), in adhoc you call module and it will be executed.
- Adhoc commands can run a single, simple task against a set of targeted hosts as a one-time command.
- Playbooks are design using YAML/json and they can work on all the hosts or group of hosts or single host.
- playbook can be write in
- single line format
- multiple line format
- dictionary format:
- $vim playbook1.yaml/yml/json (format for yaml & json are different)
-
- hosts: all (- space:space all/ip/group ) tasks: (start below h, tasks is to call module) - copy: (space -copy:module name which need to be executed) src: /etc/passwd (two spaced and define arguments) dest: /tmp/ owner: kubernetes (user kubernetes should be available) group: kubernetes (group kubernetes should be available) mode: 777 (permission to passwd file after copiying in nodes) |
- $ansible-playbook playbook1.yaml
- Playbooks are combination of plays and each play uses specific module to configure remote servers.
- Ansible is push model where task is perform from controller to nodes. Chef is pull model where task is generated from nodes.
- Ansible automate deployment application using playbook
- To write effective playbook, must know the following:
- YAML: Ain't another markup language, YAML is a data representation language, it is collection of name and value pai
- Modules
- TASK
- Ansible Environment Variables
- Inventory
- Ansible Configuration.
- Playbook structure:
- - name: Name of the playbook, you can use any name
- hosts: A set of hosts usually grouped together as a host group and defined in inventory file (/etc/ansible/hosts).
- become: To tell ansible this play has to be executed with elevated privileges
- become_user: root : the user name that we want to switch to like compare it with $sudo su
- tasks: set of tasks to be executed on the above hosts, All tasks would be defined below this, we have two modules the first module is yum and the second module is service.
- In the first task:
- - name: description of the task is performing
- yum: module is used in CentOS & Fedora. apt is used in ubuntu.
- name: httpd (in yum module httpd is use to install Apache)
- state: latest represents that the forementioned package httpd should be installed if it is not installed (or) if it is already installed it should be upgraded to the latest version available.
- other state can be used as:
- present: if httpd package is not installed whre you can define state: present
- absent: if you want to remove httpd package
- In the second task:
- - name: description of the task is performing
- service: module service is used.
- name: httpd (service name for httpd is httpd)
- state: started (we are making sure that the service named httpd is started and running using the state: started. Ansible would not restart the service if it is already started and running
- Playbook vs XML Structure
simple Playbook syntax
variables use in playbook
- some of the task in the playbook has been defined many times, it can be define as variable and call several times in the playbook for repetative task.
- define the variable (variable_name=task), call the task in the playbook defined as variable use {{ variable_name }}
- Ansible Facts and How to use them - Ansible Variable list
- For examples check the main list.
Installing Apache server.
- Installing Apache Server on CentOS using Yum Module.
- Installing Apache Server on CentOS with Playbook.
- $vi apache.yaml
- $ansible-playbook apache.yaml (this will run playbook)
- Check Apache (httpd) status:
- $systemctl status httpd in RHEL/Centos/Fedora (check in worker nodes )
- $ansible web -a 'systemctl status httpd' in RHEL/CentOS/Fedors (check from control node)
- $systemctl status apache2 in Debian/Ubuntu (check in worker nodes)
- $ansible web -a 'systemctl status apache2' (check from control node)
- $systemctl start httpd (run this on worker nodes)
- $ansible web -a 'systemctl start httpd' (run from control node)
- To check webserver: open browser and run http://IP on both worker nodes.
- Remove Apache server:in the playbook change status to absent and run the playbook.
- Installing Apache Server on Ubuntu/Debian using APT module.
- $vi apache1.yaml
- $ansible-playbook apache1.yaml
- Remove: To remove a package with Ansible apt. Use state: absent along with the package name of your choice.
- apt update cache:
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and install openssl
apt:
name: openssl
state: present
update_cache: yes
- Upgrade a Single package or Software with ansible apt: Let us suppose we want to upgrade the OpenSSL version installed in our system and this is the command we would execute on our servers.
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and upgrade openssl
apt:
name: openssl
state: latest
update_cache: yes
- Update & Upgrade All the packages installed in OneGo:
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and Upgrade all Packages
register: updatesys
apt:
name: "*"
state: latest
update_cache: yes
- name: Display the last line of the previous task to check the stats
debug:
msg: "{{updatesys.stdout_lines|last}}"
-
Installing Apache Server & Mariadb.
- Playbook using module yum for installing Apache server & Mariadb on CentOS:
- $vi apache_mariadb.yaml
- $ansible-playbook apache_mariadb.yaml (yum module has been used as python is 2.0, if python is 3.0 then use dnf module)
- $systemctl status httpd.service (you can check on worker nodes running this command or from control node run $ansible web -a 'systemctl status httpd.service'
- $systemctl start httpd (run this on worker nodes or from control node run $ansible web -a 'systemctl start httpd')
- Check Mariadb is installed: $service mariadb status from worker node or from control node run $ansible web -a 'service mariadb status'
- start Mariadb: $systemctl start mariadb from worker node or from control node run $ansible web -a 'systemctl start mariadb'
- Remove Apache & Mariadb: to uninstall change status: absent and run the yaml file.
- Playbook using module APT for installing Apache server & Mariadb on Ubuntu
- code
Installing list of packages (nginx, postgresql, postgresql-server), specific version
- Installing nginx, postgresql, postgresql-server in centos using YUM Module on CentOS.
- $vi list_of_packages.yaml
- $ansible-playbook list_of_packages.yaml
- check status of nginx: $service nginx status from worker nodes or from control node $ansible web -a 'service nginx status'
- start nginx:
- $service nginx start from worker nodes or from control node $ansible web -a 'service nginx start'
- check status of postgresql:$systemctl status postgresql from worker nodes or from control node $ansible web -a 'systemctl status postgresql'
- start postgresql:
- check status of postgresql-server:
- start postgresql-server:
- Installing nginx in Debian/Ubuntu using APT Module.
- $vi nginx.yaml
- $ansible-playbook nginx1.yaml
- But, What If I want ansible to use apt-get over apt? Well Ansible apt module supports apt-get commands as well and you could use instruct ansible apt module to use apt-get using a parameter named force_apt_get.
- ---
- name: Playbook to install NGINX
hosts: web
become: true
tasks:
- name: Ansible apt install nginx
apt:
name: nginx
state: present
force_apt_get: yes
- Installing list of packages using APT Module in Ubuntu/Debian (LAMP):
- It is not wise to create plays for each package installation.
The right approach to install multiple packages with ansible apt is to use ansible loops and iteration methods. A Simple Programming paradigm.
This is the playbook we are going to use to install / setup a LAMP (LinuxApacheMysqlPhp) stack on our Debian/Ubuntu server.
- $vi list_of_packages1.yaml
- Installing a specific Version:
- $vi tomcat1.yaml
- $ansible-playbook tomcat1.yaml
Various Playbook Examples
update cache, upgrade a single package, update & upgrade all packages,
- Update Cache:
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and install openssl
apt:
name: openssl
state: present
update_cache: yes
- Upgrade a Single package or Software with ansible apt: Let us suppose we want to upgrade the OpenSSL version installed in our system and this is the command we would execute on our servers.
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and upgrade openssl
apt:
name: openssl
state: latest
update_cache: yes
- Update & Upgrade All the packages installed in OneGo:
-
---
- name: Ansible apt module examples
hosts: web
become: true
tasks:
- name: Ansible Update Cache and Upgrade all Packages
register: updatesys
apt:
name: "*"
state: latest
update_cache: yes
- name: Display the last line of the previous task to check the stats
debug:
msg: "{{updatesys.stdout_lines|last}}"
- code
Installing tomcat with specific version
- Installing tomcat using yum module in CentOS
- Installing tomcat with specific version on Debian/Ubuntu:
- $vi tomcat1.yaml
- $ansible-playbook tomcat1.yaml
- code
Validate if a packages has been installed
- To validate if the package is installed or not without making any modifications to the system. Though it can be done with Ansible apt module and check_mode or package_facts module to validate if the package is installed or not.
- check if packages has been installed in CentOS/RHEL
- check if packages has been installed in Debian/Ubuntu.
- $vi validate_packages1.yaml
- $asible-playbook validate_packages1.yaml
- It will show packages installed, for packages not installed it will give skipping.
- code
Playbook 10
- Create user with user module in Ubuntu.
- code
Playbook 11
- Create user with user module in Ubuntu.
- code
Playbook 12
- Create user with user module in Ubuntu.
- code
Playbook 13
- Create user with user module in Ubuntu.
- code
Playbook 14
- Create user with user module in Ubuntu.
- code
Playbook 15
- Create user with user module in Ubuntu.
- code
Playbook 16
- Create user with user module in Ubuntu.
- code
Playbook 17
- Create user with user module in Ubuntu.
- code
Playbook 18
- Create user with user module in Ubuntu.
- code
Playbook 19
- Create user with user module in Ubuntu.
- code
Playbook 20
- Create user with user module in Ubuntu.
- code
Playbook 21
- Create user with user module in Ubuntu.
- code
Playbook 22
- Create user with user module in Ubuntu.
- code
Playbook 23
- Create user with user module in Ubuntu.
- code
Playbook 24
- Create user with user module in Ubuntu.
- code
Playbook 25
- Create user with user module in Ubuntu.
- code
Playbook 26
- Create user with user module in Ubuntu.
- code
Playbook 27
- Create user with user module in Ubuntu.
- code
Playbook 28
- Create user with user module in Ubuntu.
- code
Playbook 29
- Create user with user module in Ubuntu.
- code
Playbook 30
- Create user with user module in Ubuntu.
- code
Ansible Role:
What is Ansible Role:
- In the playbook you define hosts, user, variables, tasks, handlers and metadata. If number of tasks are higher and thousands of lines than it will be difficult to read the playbook.
- variables, tasks, handlers and metadata can be separated in different folders and in each folder can write a separate playbook.
- With the help of Roles you can split the playbook and put in different folder.
- Ansible Galaxy: will create the folders by using the following command.
- $ansible-galaxy --version (to check ansible galaxy is available)
- $ansible-galaxy role init testrole1 (it will create, delete, manage roles)
- $ls - ltr (folders are created: README.md, files, templates, vars, tasks, tests, meta, defaults, handlers)
- Roles can be uploaded to ansible galaxy repository. upload/download roles like github.
- code
Convert apache_install1.yaml file into roles
- Existing yaml file: it will be converted into roles.
- In the above yaml file, it deploys apache2 on web worker nodes, copy index.html file from role/ folder to /var/www/html in worker nodes.
- lets convert the yaml file into roles. Go to the folder where you have apache_install1.yaml and index files (roles) and run the following command
- $ansible-galaxy role init testrole1: the following files and folders will be created.
-
- copy complete tasks section from apache_install1.yaml and paste it in testrole1/tasks/main.yml:
- $vi apache_install1.yaml and paste it /testrole1/tasks/main.yml
- move index.html to folder: $mv index.html testrole1/files
- define role in apache_install1.yaml file
- ---
- hosts: web
become: true
roles:
- testrole1
- Run the role: $ansible-playbook apache_install.yaml
- check the index file in workernoes: /var/www/html
- Idempodent: system will not copy if it already exist. When you run playbook again it will not copy index file as it is exist. delete index.html and run plybook and it will show changed=1.
- code
code
code
code
code
code
Variable
What is Variable
- some of the task in the playbook has been defined many times, it can be define as variable and call several times in the playbook for repetative task.
- define the variable (variable_name=task), call the task in the playbook defined as variable use {{ variable_name }}
- code
- code
code
Ansible Facts and How to use them - Ansible Variable list
creating a directory, copying file,
- $vim directory.yaml
- ---
- name: Creating a directory in /tmp folder with the name star using variable mkdir (- name is use to pass the message, - name can be use to pass the message anywhere in the playbook) when you run plybook message appears.
hosts: web
vars:
mkdir: /tmp/star
tasks:
- file:
path: "{{ mkdir }}"
state: directory
- $ansible-playbook directory.yaml
- Pass the message for the task
- copy a file
- $vim directory.yaml
- ---
- name: Creating a directory in /tmp folder with the name star using variable mkdir
hosts: web
vars:
mkdir: /tmp/star
copy: /etc/passwd
tasks:
- name: Creating a Directory
file:
path: "{{ mkdir }}"
state: directory
- name: copying file
copy:
src: "{{ copy }}"
dest: "{{ mkdir }}"
owner: abdul
group: abdul
mode: 777
- $ansible-playbook directory.yaml
- define message using variable in the above
- ---
- name: Creating a directory in /tmp folder with the name star using variable mkdir
hosts: web
vars:
mkdir: /tmp/star
copy: /etc/passwd
tasks:
- name: "creating a directory in the {{ mkdir }}"
file:
path: "{{ mkdir }}"
state: directory
- name: copying file in the /tmp folder
copy:
src: "{{ copy }}"
dest: "{{ mkdir }}"
owner: abdul
group: abdul
mode: 777
- code
- code
Installing list of packages
- $vim package.yaml
- ---
- name: Installing list of packages apache, nfs-utils, tree, samba using variable
hosts: web
vars:
pkg:
- httpd
- nfs-utils
- tree
- samba
tasks:
- yum:
name: "{{ pkg }}"
state: latest
- $ansible-playbook package.yaml
- check packages are installed in worker nodes: cd /etc/www/html
- define the message using variable
- ---
- name: Installing list of packages apache, nfs-utils, tree, samba using variable
hosts: web
vars:
pkg:
- httpd
- nfs-utils
- tree
- samba
tasks:
- name: installing different packages
yum:
name: "{{ pkg }}"
state: latest
variables define in different file
- define variables in different file and call variables in palybook.
- ---
- name: Creating a directory in /tmp folder with the name star using variable mkdir
hosts: web
vars:
mkdir: /tmp/star
copy: /etc/passwd
tasks:
- name: Creating a Directory
file:
path: "{{ mkdir }}"
state: directory
- name: copying file
copy:
src: "{{ copy }}"
dest: "{{ mkdir }}"
owner: abdul
group: abdul
mode: 777
- for the above playbook define in different file and call in the playbook
- $vi directory.yaml
- ---
- name: Creating a directory in /tmp folder with the name star using variable mkdir
hosts: web
vars_files:
- ./var.yaml
tasks:
- name: Creating a Directory
file:
path: "{{ mkdir }}"
state: directory
- name: copying file
copy:
src: "{{ copy }}"
dest: "{{ mkdir }}"
owner: abdul
group: abdul
mode: 777
- $vim var.yaml
- mkdir: /tmp/star
copy: /etc/passwd
pkg:
- httpd
- nfs-utils
- tree
- samba
- code
Variable used in command while running playbook
Loop
simple Loop: copy, directory creation, variable.
- Scenario: copy /etc/passwd, /etc/group, /etc/shadow these files in /tmp folder using playbook with / without loop
- in simple loop only one loop is used
- copy without loop:
- $vi copy.yaml
- - name: copy /etc/passwd, /etc/group, /etc/shadow files into all worker nodes /tmp folder.
hosts: web
tasks:
- copy:
src: /etc/passwd
dest: /tmp
- copy:
src: /etc/group
dest: /tmp
- copy:
src: /etc/shadow
dest: /tmp
- $ansible-playbook copy.yaml
- need to use multiple times copy module, cannot define in one line like src: /etc/passwd,/etc/group,/etc/shadow
- copy with loop (simple loop):
- $vi simpleloop1.yaml
- - name: copy /etc/passwd, /etc/group, /etc/shadow files in the /tmp folder using simple loop
hosts: web
tasks:
- copy:
src: "{{ item }}"
dest: /tmp
with_items:
- /etc/passwd
- /etc/group
- /etc/shadow
- $ansible-playbook simpleloop.yaml
- By using loop we use copy module only once and used pre defined items, entered values in with_items.
- make sure variable defined is item and adding values in with_items. check alignment which is in line with copy.
- copy with loop in src and dest, create multiple folders using loop.
- $vi simpleloop2.yaml
-
- name: copy /etc/passwd, /etc/group, /etc/shadow files in /tmp folder
hosts: web
tasks:
- copy:
src: "{{ item }}"
dest: /tmp
with_items:
- /etc/passwd
- /etc/group
- /etc/shadow
- file:
path: "{{ item }}"
state: directory
with_items:
- /tmp/folder1
- /tmp/folder2
- /tmp/folder3
- copy:
src: /etc/passwd
dest: "{{ item }}"
with_items:
- /tmp/folder1
- /tmp/folder2
- /tmp/folder3
- $ansible-playbook simpleloop2.yaml
- using loop & variable: copy with loop in src and dest, create multiple folders using loop and define variable.
- Installing package using loop.
- $vi simpleloop4.yaml
-
- name: Installing ftp, httpd, vsftpd, nfs-utils package using loop.
hosts: web
tasks:
- yum:
name: "{{ item }}"
state: installed
with_items:
- ftp
- httpd
- vsftpd
- nfs-utils
$ansible-playbook simpleloop4.yaml
- loop is not required if using yum
-
- name: Installing ftp, httpd, vsftpd, nfs-utils package using loop and variable.
hosts: web
tasks:
- yum:
- ftp
- httpd
- vsftpd
- nfs-utils
state: installed
nested Loop:
- nested loop are used when multiple loops are used in playbook.
- $vi nestedloop1.yaml
-
- name: nested loop for using multiple loops
hosts: all
tasks:
- copy:
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
with_nested:
- /etc/passwd
- /tmp
- copy multiple files to a single folder with nested loop.
-
- name: nested loop for using multiple loops
hosts: all
tasks:
- copy:
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
with_nested:
- ['/etc/passwd','/etc/group','/etc/shadow']
- ['/tmp']
- copy multiple files to multiple destination
-
- name: nested loop for using multiple loops
hosts: all
tasks:
- copy:
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
with_nested:
- ['/etc/passwd','/etc/group','/etc/shadow']
- ['/tmp','/mnt','/opt']
- copying multiple files to multiple loation using variable & loop:
-
- name: nested loop for using multiple loops
hosts: all
vars:
src_file:
- /etc/passwd
- /etc/group
- /etc/shadow
dest_file:
- /tmp
- ~/test
tasks:
- copy:
src: "{{ item[0] }}"
dest: "{{ item[1] }}"
with_nested:
- "{{ src_file }}"
- "{{ dest_file }}"
-
- copying multiple files to multiple location using variable & pre-defined {{ item }} and custom loop {{ any_name }}.
Hash Loop:
- copy specific file to specific folder: suppose you have three files (a,b,c) and three folders (F1, F2, F3), copy a to F1, b to F2 and c to F3 which can not be done using simple and nested loop.
- It can be done using simple without loop but need to call copy command three times.
- simple loop:
- $vi loop1.yaml
-
- name: copy three files in three different folders
hosts: all
tasks:
- copy:
src: "{{ item }}"
dest: /tmp
with_items:
- /etc/passwd
- copy:
src: "{{ item }}"
dest: ~/test
with_items:
- /etc/group
- copy:
src: "{{ item }}"
dest: /mnt
with_items:
- etc/shadow
- $ansible-playbook loop1.yaml
- without loop:
- $vi noloop.yaml
-
- name: copy three files in three different folders
hosts: all
tasks:
- copy:
src: /etc/passwd
dest: /tmp
- copy:
src: /etc/group
dest: ~/test
- copy:
src: /etc/shadow
dest: /mnt
- $ansible-playbook noloop.yaml
- with hash loop calling copy command only once:
- $vi hashloop1.yaml
-
- name: copy three files in three different folders
hosts: all
tasks:
- copy:
src: "{{ item.a }}"
dest: "{{ item.b }}"
with_items:
- { a: '/etc/passwd', b: '/tmp' }
- { a: '/etc/group', b: '~/test'}
- { a: '/etc/shadow', b: '/mnt'}
- $ansible-playbook hashloop1.yaml
- you can use any word instead of a and b. a and b are used to define src and destination values.
- Add three users in three different groups using hash loop. (harry to dev-grp, natasha to test-grp, sarah to prod-grp)
- create three groups $groupadd dev-grp $groupadd test-grp $groupadd prod-grp
- $vi hashloop2.yaml
-
-
- name: add three users in three group, harry to dev-grp, natasha to test-grp, sarah to prod-grp, make sure groups and users are created already.
hosts: all
tasks:
- user:
name: "{{ item.user }}"
state: present
groups: "{{ item.group }}"
with_items:
- { user: 'harry', group: 'dev-grp' }
- { user: 'natasha', group: 'test-grp' }
- { user: 'sarah', group: 'prod-grp' }
- $ansible-playbook hashloop2.yaml
- check users are availale in worker nodes, go to nodes and run $grep harry /etc/passwd
- check groups are available in worker nodesas it has been added: $grep dev-grp /etc/group
code
code
code
Facts
- It is the complete information of worker nodes gathered before implementing configuration.
- information is displayed with variable and value,
- module setup is used to gather information and it is installed by default
gather information.
- $ansible all -m setup : it will display all worker nodes information.
- you can get specific information using variable
- $ansible all -m setup -a 'filter=ansible_all_ipv4_addresses' : it will display ipv4 information.
- $ansible all -m setup -a 'filter=ansible_nodename' : It will display node name.
- $ansible all -m setup -a 'filter=ansible_distribution' : it will display node o/s.
- code
Conditions
- Execute the task only when a condition is met defined in playbook.
- It is defined as when: variable_operator "value"
- operators used
- == (equal to)
- != (Not equal to)
- <
- >
- <=
- >=
- and
- or
Install apache on nodes where OS is "CentOS" using ==
- $vi condition1.yaml
-
- name: Install Apache server on nodes where operating System is CentOS only.
hosts: all
tasks:
- yum:
name: httpd
state: latest
when: ansible_distribution == "CentOS"
-
- $ansible-playbook condition1.yaml
- ansible_distribution is a variable used to define nodes OS. it can be get through setup module ($ansible all -m setup) or ($ansible all -m setup -a 'filter=ansible_distribution'
code.
code.
code.
code.
code.
code.
Notify& Handlers, Tag, Ignore, Rescue, Block, Vault, Roles Structure, Roles Galaxy
Notify & Handlers.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
AWS Deployment using Ansible
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Azure deployment using Ansible
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Code.
Ansible Projects
Create Docker container
Side Docker Container
Deploy Apache
Project
Code.
Code.
Code.
Code.
Code.
Troubeshooting
Failed to connect to the host: peremission denied
- Enable Password based authentication:
- $sudo vi /etc/ssh/sshd_config (PasswordAuthentication yes), save & exit
- $sudo service sshd restart (ubuntu)
- $sudo systemctl restart sshd.service (centos)
- Create a usere and give admin/root rights
- $adduser ansible
- $sudo visudo (add line (ansible ALL=(ALL:ALL) NOPASSWD:ALL))
- Enable Passwordless authentication to nodes
- $ssh-keygen
- $ls ~/.ssh (id_rsa & id_rsa.pub) copy public id to nodes so it can login to nodes withouts password.
- $ssh-copy-id username@IP
- $ssh ip (no username & password required)
- $cd ~/.ssh
- $ls authorized keys
code
code
code
code
code
code
Interview
Basic
- What is Ansible?
Ans: Ansible is an open-source automation tool used for configuration management, application deployment, and task automation.
- How does Ansible work?
Ans: Ansible works by connecting to nodes and pushing out small programs called "Ansible modules" to perform the required tasks.
- What are the key features of Ansible?
Ans: Simple and easy to learn, agentless architecture, idempotency, powerful automation, and extensive module support.
- What is an Ansible playbook?
Ans: A playbook is a YAML file containing a series of tasks to be executed on a set of hosts.
- What is an inventory file in Ansible?
Ans: An inventory file is a configuration file that defines the hosts and groups of hosts upon which Ansible operates.
- What are Ansible modules?
Ans: Modules are the units of work in Ansible, which can control system resources, manage packages, services, files, etc.
- What is the difference between a playbook and a play?
Ans: A playbook is a collection of plays, and a play is a set of tasks executed on a specified set of hosts.
- How do you run an Ansible playbook?
Ans: Use the command ansible-playbook <playbook-file>.yml.
- What is the Ansible Galaxy? Ans: Ansible Galaxy is a community hub for finding, sharing, and reusing Ansible content.
- What is a role in Ansible?
Ans: A role is a way to organize playbooks and other Ansible components into reusable and shareable units.
- How do you install Ansible?
Ans: Ansible can be installed using package managers like apt, yum, or using pip (Python package installer).
- What is an ad-hoc command in Ansible?
Ans: Ad-hoc commands are used to perform quick, one-time tasks without writing a playbook.
- How do you use variables in Ansible?
Ans: Variables can be defined in playbooks, inventory files, or external variable files, and are referenced using the {{ variable_name }} syntax.
- What is a task in Ansible?
Ans: A task is a single unit of work executed by Ansible, such as running a module with specific parameters.
- What is the use of the ansible.cfg file?
Ans: ansible.cfg is the configuration file for Ansible, allowing customization of settings like inventory location, SSH settings, and more.
- How do you handle errors in Ansible?
Ans: Use error handling strategies like ignore_errors, failed_when, and block/rescue to manage errors.
- What are handlers in Ansible?
Ans: Handlers are special tasks triggered by notify statements in other tasks, used to perform actions like restarting a service.
- What is idempotency in Ansible?
Ans: Idempotency ensures that applying the same configuration multiple times will not change the system state after the initial application.
- How do you create custom modules in Ansible?
Ans: Custom modules can be created using any programming language that returns JSON, typically Python, and are placed in the library directory of a role or playbook.
- What is ansible-vault?
Ans: Ansible Vault is a feature that allows you to encrypt and decrypt sensitive data in playbooks and variable files.
Advanced
- How do you use Ansible with dynamic inventories?
Ans: Use dynamic inventory scripts to pull host information from sources like cloud providers, CMDBs, etc.
- How do you optimize Ansible playbooks for performance?
Ans: Optimize by using strategies like free, linear, reducing the number of tasks, parallel execution, and proper use of handlers.
- What is delegate_to in Ansible?
Ans: delegate_to allows tasks to be executed on a different host than the one specified in the play.
- How do you manage dependencies in Ansible roles?
Ans: Use the meta/main.yml file to define role dependencies, ensuring roles are installed in the correct order.
- What is a callback plugin in Ansible?
Ans: Callback plugins enable custom behavior when Ansible events occur, such as logging, notifications, and custom output.
- How do you test Ansible playbooks?
Ans: Use tools like ansible-lint, molecule, and testinfra to test playbooks and roles for syntax errors and functionality.
- What are facts in Ansible?
Ans: Facts are system properties gathered by the setup module, which can be used within playbooks for decision making.
- How do you use loops in Ansible?
Ans: Use the loop keyword to iterate over a list of items in a task.
- What is the ansible-pull command?
Ans: ansible-pull is a command that pulls playbooks from a version control repository and executes them on the local machine.
- How do you handle secrets and sensitive data in Ansible?
Ans: Use Ansible Vault to encrypt sensitive data, and manage secrets using tools like HashiCorp Vault, AWS Secrets Manager, etc.
- code
- code
Configuration & Management
- 31. How do you configure Ansible to use SSH keys?
Ans: Specify the path to the SSH private key in the inventory file or ansible.cfg.
- 32. What is become in Ansible?
Ans: become is used to escalate privileges and run tasks as a different user, typically root.
- 33. How do you run a specific task in a playbook?
Ans: Use tags to mark tasks and run specific tasks with the --tags option.
- 34. What are conditionals in Ansible?
Ans: Conditionals allow tasks to be executed based on certain conditions, using the when keyword.
- 35. What is a lookup plugin in Ansible?
Ans: Lookup plugins allow you to retrieve data from external sources like files, databases, or APIs.
- 36. How do you manage large-scale Ansible deployments?
Ans: Use best practices like breaking down playbooks into roles, using dynamic inventories, and employing Ansible Tower/AWX for centralized management.
- 37. What is Ansible Tower?
Ans: Ansible Tower is an enterprise framework for controlling, securing, and managing Ansible automation.
- 38. How do you use Ansible Vault in playbooks?
Ans: Encrypt files using ansible-vault encrypt <file>, and reference them in playbooks with --ask-vault-pass or --vault-password-file.
- 39. What is the difference between copy and template modules?
Ans: The copy module copies a file from the control machine to the target, while the template module processes a Jinja2 template before copying.
- 40. How do you ensure idempotency in custom scripts?
Ans: Ensure custom scripts check the current state before making changes, and only perform actions when necessary.
- code
- code
Debugging & Troubleshooting
- 41. How do you debug Ansible playbooks?
Ans: Use the -vvv verbosity level for detailed logs, ansible-playbook --step to run interactively, and debug module for debugging information.
- 42. What is the assert module in Ansible?
Ans: The assert module validates conditions in a playbook, ensuring tasks only proceed if conditions are met.
- 43. How do you use the debug module?
Ans: The debug module prints statements during playbook execution, useful for troubleshooting and information display.
- 44. How do you handle playbook execution failures?
Ans: Use failed_when, ignore_errors, and rescue blocks to manage and handle failures.
- 45. What are the common causes of SSH failures in Ansible?
Ans: Incorrect SSH keys, network issues, incorrect user permissions, and misconfigured SSH settings.
- 46. How do you use register in Ansible?
Ans: register is used to capture the output of a task, which can be used later in the playbook.
- 47. What is the purpose of gather_facts in Ansible?
Ans: gather_facts collects system information, which can be used in playbooks for decision making.
- 48. How do you handle timeouts in Ansible?
Ans: Configure SSH timeouts in the ansible.cfg file or inventory file.
- 49. How do you use loops in Ansible?
Ans: Loops in Ansible can be implemented using the with_items, with_dict, loop, and other looping constructs.
- 50. What are facts in Ansible?
Ans: Facts are variables that contain information about the system, such as IP addresses, OS type, memory, etc., gathered by Ansible's setup module.
- 51. What is the purpose of the vars_files keyword in a playbook?
Ans: The vars_files keyword is used to include external YAML files containing variables in a playbook.
- 52. Explain the register keyword in Ansible.
Ans: The register keyword is used to capture the output of a task into a variable for use later in the playbook.
- 53. What is a task in Ansible?
Ans: A task in Ansible is a single unit of work, such as installing a package, running a command, or modifying a file.
- 54. How do you execute an ad-hoc command in Ansible?
Ans: Ad-hoc commands in Ansible can be executed using the ansible command followed by the host pattern and the module to be run.
- 55. What is the difference between ansible and ansible-playbook commands?
Ans: The ansible command is used for running ad-hoc tasks, while the ansible-playbook command is used to run playbooks.
- 56. What is a vault in Ansible?
Ans: Ansible Vault is a feature that allows you to encrypt and decrypt sensitive data, such as passwords and keys, within Ansible files.
- 57. How do you define dependencies between roles in Ansible?
Ans: Role dependencies can be defined in the meta/main.yml file within a role.
- 58. What is the purpose of the gather_facts directive in a playbook?
Ans: The gather_facts directive, when set to true, collects facts about the managed nodes before executing tasks.
- 59. What is a dynamic inventory in Ansible?
Ans: A dynamic inventory is generated at runtime using scripts or plugins, allowing for more flexible and dynamic inventory management.
- 60. How do you include one playbook within another in Ansible?
Ans: You can include one playbook within another using the include or import_playbook directives.
- 61. What is an Ansible callback plugin?
Ans: Callback plugins enable you to hook into different stages of the Ansible execution cycle to extend functionality, such as logging, notifications, and custom outputs.
- 62. How do you handle idempotency in Ansible?
Ans: Idempotency in Ansible is ensured by writing tasks that can be repeated multiple times without changing the outcome after the initial application.
- 63. What is the difference between include and import in Ansible?
Ans: include is processed at runtime, whereas import is processed during playbook parsing, allowing for conditional and looped imports.
- 64. How do you use the ansible-vault command to create a new encrypted file?
Ans: Use ansible-vault create <filename> to create a new file and open it in your default editor for adding encrypted content.
- 65. Explain the use of the block directive in Ansible.
Ans: The block directive groups tasks together, allowing for common error handling, conditionals, and handlers to be applied to the entire block.
- 66. How do you manage complex variable structures in Ansible?
Ans: Complex variables can be managed using dictionaries (hashes) and lists, and accessed using dot notation or bracket syntax.
- 67. What is the purpose of pre_tasks and post_tasks in a playbook?
Ans: pre_tasks are executed before the main tasks in a play, while post_tasks are executed after the main tasks.
- 68. How do you limit Ansible playbook execution to specific hosts?
Ans: Use the --limit flag with the ansible-playbook command to restrict execution to specified hosts.
- 69. What is a filter in Ansible?
Ans: Filters are used to modify or transform data within Jinja2 templates, providing a way to process variables and facts.
- 70. How do you use the delegate_to directive in Ansible?
Ans: The delegate_to directive allows you to execute a task on a different host than the one to which the play is currently assigned.
- 71. Explain the concept of roles in Ansible Galaxy.
Ans: Roles in Ansible Galaxy are shared collections of tasks, variables, files, templates, and handlers that can be reused across projects and playbooks.
- 72. What are lookup plugins in Ansible?
Ans: Lookup plugins are used to retrieve data from external sources, such as files, databases, or APIs, during playbook execution.
- 73. How do you handle different environments (dev, staging, production) in Ansible?
Ans: Use separate inventory files, variable files, and playbooks for each environment, and include environment-specific configurations.
- 74. What is the use of the set_fact module in Ansible?
Ans: The set_fact module is used to define variables dynamically during playbook execution, allowing for more flexible automation.
- 75. How do you use the ansible-config command?
Ans: The ansible-config command is used to view, validate, and dump the current Ansible configuration settings.
- 76. Explain the use of tags in Ansible playbooks.
Ans: Tags allow you to selectively run or skip specific tasks, plays, or roles within a playbook using the --tags and --skip-tags options.
- 77. What is the ansible-lint tool?
Ans: ansible-lint is a command-line tool that checks Ansible playbooks for best practices, syntax errors, and style issues.
- 78. How do you use the copy module in Ansible?
Ans: The copy module copies files from the local machine to remote hosts, supporting attributes like owner, group, mode, and backup.
- 79. What is the raw module in Ansible?
Ans: The raw module executes commands directly on remote hosts without requiring a Python interpreter, useful for bootstrapping systems.
- 80. How do you manage multiple Ansible versions on the same machine?
Ans: Use virtual environments, such as virtualenv or pyenv, to manage and switch between different Ansible versions.
- 81. What is the local_action directive in Ansible?
Ans: The local_action directive allows you to run a task on the control node instead of the remote hosts.
- 82. How do you use the debug module in Ansible?
Ans: The debug module prints variables and messages to the playbook output, useful for troubleshooting and validation.
- 83. Explain the use of with_fileglob in Ansible.
Ans: with_fileglob iterates over a list of files matching a specified pattern, useful for processing multiple files in a directory.
- 84. What is the purpose of the notify directive in Ansible?
Ans: The notify directive triggers handlers when a task changes, ensuring that dependent actions are executed only when necessary.
- 85. How do you manage Ansible configurations for different users?
Ans: Use user-specific configuration files, such as .ansible.cfg in the user's home directory, to override global settings.
- 86. What is the ansible-pull command?
Ans: The ansible-pull command is used for a pull-based configuration management approach, where nodes pull configurations from a central repository.
- 87. How do you secure sensitive information in Ansible?
Ans: Use Ansible Vault to encrypt sensitive information, and store encrypted files or variables securely within your playbooks.
- 88. What is a custom module in Ansible?
Ans: A custom module is a user-defined module written in Python or other languages to extend Ansible's functionality beyond the built-in modules.
- 89. How do you test Ansible playbooks?
Ans: Test Ansible playbooks using tools like Molecule, which provides a framework for testing roles and playbooks in isolated environments.
- 90. What is the ansible-doc command?
Ans: The ansible-doc command displays detailed documentation for Ansible modules, plugins, and other components.
- 91. How do you manage dependencies in Ansible roles?
Ans: Define dependencies in the meta/main.yml file within a role, specifying other roles that need to be run before or after the current role.
- 92. What is the ansible-inventory command?
Ans: The ansible-inventory command is used to display or dump the inventory configuration, supporting various output formats and options.
- 93. How do you use the template module in Ansible?
Ans: The template module processes Jinja2 templates and copies the rendered files to remote hosts, allowing for dynamic configuration files.
- 94. What is the purpose of the until directive in Ansible?
Ans: The until directive retries a task until a certain condition is met, supporting parameters like retries and delay.
- 95. How do you define custom facts in Ansible?
Ans: Custom facts can be defined by placing executable scripts in the /etc/ansible/facts.d directory on managed nodes.
- 96. What is the ansible-vault rekey command used for?
Ans: The ansible-vault rekey command changes the encryption password for an existing Vault file or files.
- 97. How do you handle large numbers of hosts in Ansible?
Ans: Use dynamic inventories, host groups, and parallel execution settings to manage and scale Ansible operations efficiently.
- 98. What is the ansible-config dump command used for?
Ans: The ansible-config dump command outputs the current configuration settings in a machine-readable format, useful for troubleshooting and validation.
- 99. Explain the use of the fetch module in Ansible.
Ans: The fetch module copies files from remote hosts to the control node, supporting parameters like flat, fail_on_missing, and validate_checksum.
- 100. How do you monitor and troubleshoot Ansible executions?
Ans:- Monitor and troubleshoot Ansible executions using verbose mode (-v), log files, callback plugins, and external tools like AWX or Ansible Tower.
101. What is AWX and how does it relate to Ansible?
Ans: AWX is the open-source version of Ansible Tower, a web-based interface for managing and visualizing Ansible projects, job scheduling, and role-based access control.
102. Explain the concept of idempotency in Ansible.
Ans: Idempotency means that applying the same playbook multiple times will not change the system state after the first application, ensuring predictable and repeatable results.
103. How do you integrate Ansible with CI/CD pipelines?
Ans: Integrate Ansible with CI/CD pipelines using tools like Jenkins, GitLab CI, or GitHub Actions, calling ansible-playbook commands as part of the build and deployment steps.
104. What are Ansible Collections?
Ans: Ansible Collections are a distribution format for Ansible content, including roles, modules, plugins, and playbooks, packaged together and published for easier sharing and reuse.
105. How do you handle cross-platform support in Ansible playbooks?
Ans: Handle cross-platform support by using conditionals, platform-specific tasks, and variables to accommodate differences between operating systems.
106. What is the ansible-test command used for?
Ans: The ansible-test command is used to run unit tests, integration tests, and sanity checks for Ansible content, ensuring code quality and functionality.
107. How do you manage secrets in Ansible without using Ansible Vault?
Ans: Manage secrets using external secret management tools like HashiCorp Vault, AWS Secrets Manager, or environment variables.
108. Explain the purpose of the meta module in Ansible.
Ans: The meta module is used for special tasks like managing role dependencies, stopping playbook execution, and flushing handlers.
109. How do you debug complex playbooks in Ansible?
Ans: Debug complex playbooks using the debug module, --step and --start-at-task options, and verbose mode (-vvv) to gather detailed execution information.
110. What is the ansible-doc command and how is it useful?
Ans: The ansible-doc command provides documentation for Ansible modules and plugins, helping users understand module usage and parameters.
111. How do you implement a custom dynamic inventory script in Ansible?
Ans: Implement a custom dynamic inventory script by writing a script in Python or another language that outputs JSON-formatted inventory data.
112. What is the ansible-config command used for?
Ans: The ansible-config command is used to view, validate, and dump the current Ansible configuration, useful for troubleshooting and ensuring consistency.
113. How do you use the lineinfile module in Ansible?
Ans: The lineinfile module ensures a particular line is present or absent in a file, supporting regex patterns for more complex manipulations.
114. Explain the use of the ansible-pull command.
Ans: The ansible-pull command allows nodes to pull playbooks from a remote repository and apply them, suitable for a pull-based configuration management approach.
115. How do you handle nested loops in Ansible?
Ans: Handle nested loops using the with_nested directive or nested loop constructs, iterating over multiple lists or dictionaries.
116. What is the purpose of the retry_files_enabled setting in Ansible?
Ans: The retry_files_enabled setting controls whether Ansible generates retry files for failed playbook runs, allowing users to rerun only failed tasks.
117. How do you use the wait_for module in Ansible?
Ans: The wait_for module waits for a specified condition, such as a port being open or a file being present, useful for synchronization tasks.
118. What are Ansible plugins and how are they used?
Ans: Ansible plugins extend the functionality of Ansible, including callback plugins, connection plugins, and filter plugins, and can be custom developed as needed.
119. How do you use the winrm connection plugin in Ansible?
Ans: The winrm connection plugin allows Ansible to manage Windows hosts using the Windows Remote Management (WinRM) protocol.
120. Explain the use of the ansible-galaxy command.
Ans: The ansible-galaxy command manages Ansible roles and collections, including installing, removing, and creating roles from the Ansible Galaxy repository.
121. How do you manage different versions of Ansible modules?
Ans: Manage different versions of Ansible modules by using specific version tags in playbooks, collections, and roles, ensuring compatibility and stability.
122. What is the ansible-doc command used for?
Ans: The ansible-doc command provides detailed documentation for Ansible modules and plugins, aiding in understanding module usage and parameters.
123. How do you handle large-scale deployments with Ansible?
Ans: Handle large-scale deployments using parallel execution, dynamic inventories, load balancing, and breaking tasks into smaller, manageable chunks.
124. What is the purpose of the hosts directive in an inventory file?
Ans: The hosts directive defines the target nodes or groups of nodes on which tasks will be executed, organizing the inventory structure.
125. How do you use Ansible with cloud providers like AWS, Azure, and GCP?
Ans: Use Ansible with cloud providers by leveraging their specific modules, dynamic inventory scripts, and integrations for provisioning and managing cloud resources.
126. Explain the concept of task delegation in Ansible.
Ans: Task delegation involves executing tasks on a different host than the one defined in the play, using the delegate_to directive.
127. How do you implement error handling in Ansible playbooks?
Ans: Implement error handling using the ignore_errors, failed_when, and rescue directives, providing custom error messages and recovery steps.
128. What is the ansible-vault view command used for?
Ans: The ansible-vault view command displays the contents of an encrypted Vault file without decrypting it to disk, ensuring secure access to sensitive data.
129. How do you use the file module in Ansible?
Ans: The file module manages file properties, such as permissions, ownership, and symbolic links, supporting attributes like state, owner, and group.
130. What is the purpose of the become directive in Ansible?
Ans: The become directive allows tasks to be executed with elevated privileges, such as sudo, facilitating administrative operations.
131. How do you manage dependencies between Ansible roles?
Ans: Manage dependencies between roles by specifying them in the meta/main.yml file within each role, ensuring proper execution order.
132. What is the ansible-vault encrypt_string command used for?
Ans: The ansible-vault encrypt_string command encrypts a single string and outputs it in a format that can be included directly in playbooks and variables files.
133. How do you handle configuration drift in Ansible?
Ans: Handle configuration drift by regularly running playbooks to enforce desired states, using tools like AWX/Tower for continuous monitoring and compliance.
134. What is the purpose of the command module in Ansible?
Ans: The command module runs commands on remote hosts, similar to executing them in a shell, but without using a shell interpreter.
135. Explain the use of with_items in Ansible.
Ans: with_items is used to loop over a list of items, executing the same task for each item in the list.
136. How do you use the ansible-vault decrypt command?
Ans: The ansible-vault decrypt command decrypts encrypted Vault files, allowing access to their plaintext contents.
137. What is the ansible-config view command used for?
Ans: The ansible-config view command displays the current configuration settings, useful for verifying and troubleshooting configurations.
138. How do you use the copy module to manage files in Ansible?
Ans: The copy module copies files from the control node to remote hosts, supporting attributes like src, dest, owner, and mode.
139. Explain the purpose of the local_action directive in Ansible.
Ans: The local_action directive allows tasks to be executed on the control node instead of the remote hosts, useful for control node-specific operations.
140. How do you use the lineinfile module to manage file contents?
Ans: The lineinfile module ensures specific lines are present or absent in a file, supporting regex patterns and other attributes for precise control.
141. What is the purpose of the ansible-playbook --check option?
Ans: The ansible-playbook --check option runs the playbook in a dry-run mode, simulating changes without making any actual modifications.
142. How do you manage complex variables in Ansible?
Ans: Manage complex variables using dictionaries (hashes) and lists, and access them using dot notation or bracket syntax in playbooks and templates.
143. Explain the use of roles_path in Ansible configuration.
Ans: roles_path specifies the directory paths where Ansible looks for roles, allowing for organized and reusable role management.
144. What is the ansible-pull command used for?
Ans: The ansible-pull command allows nodes to pull playbooks from a remote repository and apply them, suitable for pull-based configuration management.
145. How do you use the wait_for module to manage task dependencies?
Ans: The wait_for module waits for a specified condition, such as a port being open or a file being present, ensuring tasks are executed in the correct order.
146. What is the purpose of the notify directive in Ansible?
Ans: The notify directive triggers handlers when a task changes, ensuring dependent actions are executed only when necessary.
147. How do you manage multiple inventory sources in Ansible?
Ans: Manage multiple inventory sources using inventory plugins, dynamic inventory scripts, and combining static inventory files.
148. Explain the use of with_fileglob in Ansible.
Ans: with_fileglob iterates over a list of files matching a specified pattern, useful for processing multiple files in a directory.
149. What is the ansible-galaxy init command used for?
Ans: The ansible-galaxy init command creates a new role directory structure, providing a standardized template for developing roles.
150. How do you manage playbook execution order in Ansible?
Ans: Manage playbook execution order using dependencies, task priorities, and the serial directive to control the number of hosts processed at a time.
- 151. What is an Ansible Operator and how is it used with Kubernetes?
Ans: An Ansible Operator is a way to define Kubernetes operators using Ansible, allowing you to manage Kubernetes resources using Ansible playbooks and roles.
152. How do you use the ansible-test integration command?
Ans: The ansible-test integration command runs integration tests for Ansible content, ensuring that modules and playbooks work correctly in real-world scenarios.
153. Explain the concept of inventory plugins in Ansible.
Ans: Inventory plugins allow for dynamic and flexible inventory management by enabling Ansible to pull inventory data from external sources like cloud providers, databases, or APIs.
154. What is the ansible-config dump command used for?
Ans: The ansible-config dump command outputs the current configuration settings in a machine-readable format, useful for validation and troubleshooting.
155. How do you handle Ansible playbook versioning and updates?
Ans: Handle versioning using Git for source control, tagging releases, and maintaining clear documentation of changes. Use CI/CD pipelines for automated testing and deployment.
156. What are Ansible connection plugins and how are they used?
Ans: Connection plugins manage the connection type for Ansible to communicate with remote hosts, such as SSH, WinRM, or local connections.
157. Explain how you can optimize Ansible performance for large-scale deployments.
Ans: Optimize performance by using parallelism with forks, managing SSH connections with ControlPersist, using async tasks, and reducing unnecessary fact gathering.
158. What is the ansible-galaxy collection command used for?
Ans: The ansible-galaxy collection command manages Ansible collections, allowing you to install, build, and publish collections of Ansible content.
159. How do you handle network automation with Ansible?
Ans: Use network-specific modules and roles, leverage connection plugins like network_cli, and manage configurations and state of network devices using Ansible playbooks.
160. What are the best practices for writing maintainable Ansible playbooks?
Ans: Use roles and collections for reusability, keep playbooks and tasks modular, use clear and consistent naming conventions, document thoroughly, and implement error handling.
161. How do you use the ansible-playbook --diff option?
Ans: The ansible-playbook --diff option shows changes that would be made to managed nodes, displaying the differences between the current and desired states.
162. Explain the use of the ansible-vault rekey command.
Ans: The ansible-vault rekey command changes the encryption password for existing Vault files, ensuring that sensitive information remains secure with updated credentials.
163. What is the ansible-cmdb tool and how is it used?
Ans: ansible-cmdb generates system configuration documentation and reports from Ansible fact data, providing insights into your infrastructure's state.
164. How do you manage external dependencies in Ansible roles?
Ans: Manage external dependencies using the meta/main.yml file in roles, specifying dependencies on other roles or collections, and using ansible-galaxy for installation.
165. Explain the use of ansible-playbook --list-tasks and --list-hosts.
Ans: --list-tasks lists all tasks in a playbook without executing them, while --list-hosts lists all hosts that would be targeted by a playbook run.
166. What is the purpose of Ansible's callback plugins?
Ans: Callback plugins extend Ansible's functionality by hooking into different stages of playbook execution, enabling custom logging, notifications, and reporting.
167. How do you use Ansible with Windows hosts?
Ans: Use the winrm connection plugin, install necessary PowerShell modules, and leverage Windows-specific modules to manage Windows hosts with Ansible.
168. What is Ansible's ansible-connection module and how is it used?
Ans: Ansible's ansible-connection module defines and manages the connection settings for communicating with remote hosts, crucial for establishing and maintaining connectivity.
169. How do you handle multi-step orchestration workflows in Ansible?
Ans: Handle orchestration by chaining multiple playbooks, using include or import_playbook, and implementing task dependencies and conditions.
170. Explain the use of the ansible-playbook --syntax-check option.
Ans: The ansible-playbook --syntax-check option validates the syntax of a playbook without executing any tasks, ensuring that the playbook is error-free.
171. How do you integrate Ansible with monitoring tools?
Ans: Integrate Ansible with monitoring tools by using modules and plugins for systems like Prometheus, Nagios, or Datadog, automating the setup and configuration of monitoring.
172. What is the ansible-vault edit command used for?
Ans: The ansible-vault edit command opens an encrypted file in the default editor, allowing you to make changes to the content while keeping it encrypted.
173. How do you use Ansible to manage containerized environments?
Ans: Manage containerized environments using modules like docker, podman, or k8s to deploy, configure, and maintain containers and Kubernetes resources.
174. Explain the use of the ansible-inventory command.
Ans: The ansible-inventory command displays or dumps inventory information, supporting various output formats and dynamic inventory scripts.
175. What are some advanced techniques for debugging Ansible playbooks?
Ans: Advanced debugging techniques include using ansible-playbook -vvv for detailed output, debug module for variable inspection, and custom callback plugins for enhanced logging.
- 176. How do you ensure Ansible playbooks are idempotent?
Ans: Ensure idempotency by writing tasks that check the current state before making changes, using appropriate modules that inherently support idempotency, and testing thoroughly.
177. What is the ansible-lint tool and how is it used?
Ans: ansible-lint checks playbooks for best practices and potential errors, helping maintain clean, efficient, and consistent Ansible code.
178. How do you manage Ansible configurations for different teams or projects?
Ans: Manage configurations using separate inventory files, variable files, and playbooks for each team or project, and leveraging role-based access control (RBAC) in tools like AWX/Tower.
179. Explain the concept of asynchronous actions in Ansible.
Ans: Asynchronous actions allow tasks to run in the background and continue execution without waiting for completion, using the async and poll directives.
180. How do you handle large inventories in Ansible?
Ans: Handle large inventories using dynamic inventory scripts, host grouping, inventory directories, and optimizing inventory refresh intervals.
181. What is the ansible-vault encrypt command used for?
Ans: The ansible-vault encrypt command encrypts files to secure sensitive information, making it accessible only with the correct Vault password.
182. How do you use the ansible-playbook --start-at-task option?
Ans: The ansible-playbook --start-at-task option starts playbook execution at a specific task, useful for resuming interrupted runs or debugging specific tasks.
183. Explain the use of custom inventory scripts in Ansible.
Ans: Custom inventory scripts dynamically generate inventory data from external sources, allowing for flexible and scalable inventory management.
184. How do you use the copy module for secure file transfers in Ansible?
Ans: The copy module transfers files securely using SSH, supporting options like mode, owner, group, and backup for file attributes.
185. What are some common pitfalls to avoid when writing Ansible playbooks?
Ans: Common pitfalls include hardcoding values, ignoring idempotency, not handling errors, poor variable management, and lack of documentation and testing.
186. How do you use the ansible-vault rekey command to update encryption keys?
Ans: The ansible-vault rekey command updates the encryption key for existing Vault files, ensuring continued security with a new password.
187. Explain the use of local_action in multi-host Ansible playbooks.
Ans: local_action executes tasks on the control node within a playbook targeting multiple hosts, useful for orchestration and control node-specific operations.
188. What is the purpose of the ansible-galaxy role init command?
Ans: The ansible-galaxy role init command initializes a new role with a standard directory structure, providing a template for developing roles.
189. How do you manage Ansible playbooks in a CI/CD pipeline?
Ans: Manage playbooks in CI/CD pipelines by integrating with tools like Jenkins, GitLab CI, or GitHub Actions, automating testing, deployment, and version control.
190. What is the ansible-vault view command used for?
Ans: The ansible-vault view command displays the contents of an encrypted Vault file without decrypting it to disk, ensuring secure access to sensitive data.
191. How do you use Ansible to configure network devices?
Ans: Configure network devices using Ansible modules specific to network platforms, connection plugins like network_cli, and roles designed for network automation.
192. Explain the concept of task retries in Ansible.
Ans: Task retries involve re-executing a task until a condition is met or a maximum number of retries is reached, using the `re
triesanddelay` directives.
193. What is the ansible-vault decrypt command used for?
Ans: The ansible-vault decrypt command decrypts Vault-encrypted files, allowing access to their plaintext contents for reading or modification.
194. How do you implement cross-platform playbooks in Ansible?
Ans: Implement cross-platform playbooks using conditionals, platform-specific modules, and variables to handle differences between operating systems.
195. What are some security best practices for Ansible?
Ans: Security best practices include using Ansible Vault for sensitive data, minimizing use of become, regularly updating Ansible and dependencies, and restricting SSH access.
196. Explain the use of the ansible-playbook --diff option.
Ans: The ansible-playbook --diff option shows changes that would be made to managed nodes, displaying the differences between the current and desired states.
197. How do you manage Ansible inventory in a hybrid environment?
Ans: Manage inventory in a hybrid environment using dynamic inventory scripts, combining static and dynamic sources, and organizing hosts into logical groups.
198. What is the ansible-playbook --vault-id option used for?
Ans: The ansible-playbook --vault-id option specifies the Vault ID to use for decrypting Vault-encrypted data, supporting multiple Vault passwords.
199. How do you use the ansible-doc command to understand module usage?
Ans: The ansible-doc command provides detailed documentation for Ansible modules, including descriptions, options, and examples, helping understand module usage.
200. What is the purpose of Ansible Collections?
Ans: Ansible Collections package and distribute roles, modules, plugins, and other content, facilitating reuse, sharing, and version control across projects.
- code
Real Time Interview Questions
code
code
Videos
Sanjay
Quality Thought
Sunil
IntelliQit
code
code
code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
- code
| spring-pet-clinic | student courses | Automate deployent |
Ansible intro, |
Manual Deployment, |
Ansible Installation by sunil, installation by intelliqit, |
Automate Deployment using playbook, example1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, |
Inventory/hosts file, custom inventory file, |
Ansible Variables, Handlers, Error Handling, when statement, tags, Loops, |
Ansible Modules, Ansible command module, Playbook, YAML, |
|
playbook vs xml, |
www.middlewareinventory.com/blog/ansible-playbook-example |
Shell module example1: Installing docker on nodes.
- #ansible all -m shell -a 'curl -fsSL https://get.docker.com -o get-docker.sh'
- #ansible all -m shell -a 'sh get-docker.sh'
- #ansible all -m command -a 'docker --version' (To check docker is installed)
- #ansible all -a '
snap remove --purge docker' -b
Shell Module example2: Ansible execute command 'ls -la' and output is saved in a file (redirect output in a file)
- #ansible all -m shell -a 'ls -la > file1'
User Module Example1: Create a user in all nodes. Refer docs.ansible here
- #ansible all -m user -a 'name=aziz password=India123' (will get permission error as it is executed as ubuntu user, either run as root user or use sudo because passwd file is not having write permission for others)
- #ansible all -m user -a 'name=aziz password=India123' -b (-b=become, it is used for getting higher priviledges on the manageed nodes)
- #ansible all -m user -a 'name=Abdul password=India123 home=/home/Abdul comment="manager" uid=1234 shell=/bin/bash' -b
Group Module Example1: create a group in all nodes. Refer docs.ansible here
- #ansible all -m group -a 'name=group1 state=present' -b
APT Module Example1: install git on all nodes. refer docs.ansible here
- #ansible all -m apt -a 'update_cache=yes' -b
- #ansible all -m apt -a 'name=git state=present' -b (present = install, absent=uninstall, latest=upgradation)
- #ansible all -m command -a 'git --version'
- #ansible all -m apt -a 'name=git state=absent' -b
- #ansible all -m apt -a 'name=git state=present update_cache=yes' -b
APT Module Excample2: Install tomcat8 and update repository as well.
- #ansible all -m apt -a 'name=tomcat8 state=present update_cache=yes' -b
- To chedck tomcat8 is installed, in any browser enter publicIP:8080
File Module Example1: create, delete file / folder, refer docs.ansible here
- #ansible all -m file -a 'name=/tmp/file1 state=touch' (create empty file)
- #ansible all -m file -a 'name=/tmp/folder1 state=directory'(directory created)
- #ansible all -m file -a 'name=/tmp/file1 state=absent' (it will delete)
File Module Example2: File permission
- #ansible all -m file -a 'name=file1 state=touch'
- #ansible all -a 'ls -l'
- -rw-rw-r-- 1 ubuntu ubuntu (file permission= owner=rw- group=rw- others=r-- owner=ubuntu group=ubuntu)
- #ansible all -m file -a 'name=file5 state=touch owner=aziz1 group=group1 mode=700' -b
Copy Module Example1: It copies the file from controller to nodes.
- #ansible all -m copy -a 'src=/data1 dest=/tmp'
Copy Module Example2: copy the file but change the owner group and file permission in the destination. actual permission is -rw-r--r-- change to -rwxrwxrwx 1 aziz1 group1
- #ansible all -m copy -a 'src=/data1 dest=/ owner=aziz1 group=group1 mode=777' -b
Copy Module Example3: copy new content and overwrite into the destination file. (data1 has got some text which will be overwrite with content=welcome to star distributors).
- #ansible worker1IP -m copy -a 'content="welcome to star distributors\n" dest=/data1' -b
Fetch Module Example1: It fetch or copes from nodes to controller.
- #ansible worker1IP -m fetch -a 'src=/data1 dest=/tmp/worker1' -b (it will create a folder worker1 and inside create a folder of privateIP of worker1 in /tmp folder and data1 file copied)if you use all and same file present in all nodes then there will be folder of all nodes IP and file will be copied. #tree /tmp/worker1
- copy file beteen two nodes (worker1 and worker2), it is two step process, it fetch the file from node to controller and copy from controller to second node.
- fetch from node to controller: #
- copy controller to node: #
Synchronize Module Example1: copy files between two nodes or remote servers. It ca be done with fetch modules as well. For Synchronize module to work hassle-free,SSH Key-based authentication must be enabled between remote nodes. otherwise, the synchronize task will get stuck and so does your Ansible play. Ansible Synchronize is more like Ansible RSYNC. the typical rsync feature of Linux.
- Synchronize pull method: worker1 to worker2 (execute in worker2) pull the file from worker1.
- #
Ping Module Exampe1: Ping with nodes
- #ansible all -m ping
Git Module Example1: it is used to clone from git hub repository to all nodes.
- #ansible all -m git -a 'repo=https://github.com/aziz27uk/intelliqitdev.git dest=/tmp/mygit' -b (it will create mygit folder and clone all files)
Service Module Example1: it is used to stop start restart services on nodes.
- #ansible all -m service -a 'name=tomcat8 state=restarted' -b
- state= restarted (restarting a service)
- state= stopped (stop a running service)
- state=started (starting a stopped service)
Replace Module Example1: in tomcat server.xml file in which port defined on which tomcat runs. default 8080 port will replace to 5050 in all nodes. (cd /etc/tomcat8/server.xml check connector where port defined)
- #ansible all -m replace -a 'regexp=8080 replace=5050 path=/etc/tomcat8/server.xml' -b (regexp= regular expression the value which need to replace).
- #ansible all -m service -a 'name=tomcat8 state=restarted' -b
URI Module Example1: It is used to check the particular URL is reachable from nodes.
- #ansible all -m uri -a 'url=http://facebook.com' (Outcome will be in green colour as there is no change but only it is testing and status=200)
get_url command example1: download jenkins.war into all nodes
- #ansible ll -m get_url -a 'url=https://get.jenkins.io/war-stable/2.289.3/jenkins.war dest=/tmp'
Manual Deployment: Sprint-Pet-Clinic & Student Courses Application.
Spring-Pet-Clinic: Manual deployment of application (sprint pet clinic, java based), click for quality thought notes
Pre requisite:
- create a ubuntu instance. open ports ssh 8080
- Java 8 should be installed.
- #sudo apt-get update
- #sudo apt-cache search jdk | less
- #sudo apt-get install openjdk-8-jdk
- #java -version
- Download spring pet clinic application
- wget https://referenceappkhaja.s3-us-west-2.amazonaws.com/spring-petclinic-2.2.0.BUILD-SNAPSHOT.jar
- #java -jar spring-petclinic-2.2.0.BUILD-SNAPSHOT.jar
- Access application with public IP of instance and it runs on port 8080
- publicIP:8080
Student Courses Application : manual deployment of application is written in python. clone source code from github.
Pre-requisite:
- create a ubuntu instance. open ports ssh 8080
- Install python3, PIP-3 and git
- #sudo apt-get install python3 python3-pip git -y
- clone source code of student courses application from git hub.
- #git clone https://github.com/DevProjectsForDevOps/StudentCoursesRestAPI.git
- #cd StudentCoursesRestAPI.git #ls
- #pip3 install -r requirements
- #python3 app.py
- Access applcation with public IP and use port 8080
Automate Deployment of application through Ansible: The above two deployments has been done manually, now automate deployment of application using ansible, can be done by writing playbook.
Playbook_example1:check colours in the following example playbook and adhoc module.
--- -name: Creating users on managed nodes hosts: all become: yes tasks: -name: user creation user: name: aziz password: India123 home: /home/aziz uid: 1010 shell: /bin/bash comment: "manager user" ... |
---
-name: titile of the playbook
hosts: all become: yes tasks: -name: -<module_name>: <module_arg1>:<module_value1>
...
|
Adhoc command:
#ansible all -m user -a 'name=aziz password=India123 home=/home/aziz uid=1010 shell=/bin/bash comment="manager user"' -b
|
- #ansible-playbook playbook1.yml --syntax-check (To check playbook syntax is correct or not)
- #anisble-playbook playbook1.yml -b (execute playbook)
Playbook_example2: Create a directory and copy files.
--- - name: create a directory and copy files hosts: all become: yes tasks: - name: create a directory file: name: /tmp/folder1 state: directory - name: copy the /etc/passwd copy: src: /etc/passwd dest: /tmp/folder1 ... |
#ansible all -m file -a 'name=/tmp/folder1 state=directory
#ansible all -m copy -a 'src=/data1 dest=/tmp'
|
Playbook_example3: Install git and clone remote repository.
--- - name: Installing git and cloning remote repository hosts: all become: yes tasks: - name: installing git in all nodes apt: name: git state: present update_cache: yes - name: cloning git repository git: repo: https://github.com/aziz27uk/intelliqitdev.git dest: /home/ubuntu/playbookgit ... |
#ansible all -m apt -a 'name=git state=present' -b
#ansible all -m git -a 'repo=https://github.com/aziz27uk/intelliqitdev.git dest=/tmp/mygit' -b
|
Playbook_example4: Installing tomcat8, copy user.xml, replace 8080 port to 5050, restart comat8 service, check url working in nodes.
--- - name: Installing tomcat8, copy user.xml, replace 8080 port to 5050, restart comat8 service, check url working in nodes. hosts: all tasks: - name: installing tomcat8 apt: name: tomcat8 state: present update_cache: yes - name: copy tomcat-user.xml file copy: src: /home/ubuntu/tomcat-user.xml dest: /etc/tomcat8 - name: change port number replace: regexp: 8080 replace: 5050 path: /etc/tomcat8/server.xml - name: restart tomcat8 service: name: tomcat8 state: restarted - name: url check of worker1 uri: url: http://172.31.25.210:5050 status_code: 200 - name: url check for worker2 uri: url: http://172.31.16.152:5050 status_code: 200 - name: url check for worker3 uri: url: http://172.31.39.28:5050 status_code: 200 |
|
Playbook_Example5: Configuring Apache2, create index.html, restart apache2 and check url is reachable.
---
- name: install Apache2, create index.html, restart apache2 and check url hosts: all tasks: - name: Install apache2 apt: name: apache2 status: present - name: edit index.html file copy: content: "Welcome to star Distributors\n" dest: /var/www/html/index.html - name: restart httpd service service: name: apache2 state: restarted - name: check url is reachable in node worker1 uri: url: http://privateIP:80 state_code: 200 - name: check url is reachable in node worker2 uri: url: http://privateIP:80 state_code: 200
...
|
|
Variables: Ansible uses 3 types of variables:
- Global Scope variables: The values of varibales are entered while executing playbook file --extra-vars and they have the highest priority.
- Host Scope variables
- Play Scope variables: the values of varibales are hardcode in playbook file as default values, you ue --extra-vars to enter variables values at execution of playbook file, if any value is not entered then it will take default hardcode value. It works with only one play. Any variable declared within vars section within playbook is called as play scope variable.
Playbook_example6: Playbook for installing/uninstalling software packages using gloabal scope variable.
- define variable in the playbook and enter variable values while executing playbook file.
--- - name: Installing/Uninstalling s/w package hosts: all tasks: - name: Installing, uninstalling, update s/w packages apt: name: "{{a}}" state: "{{b}}" update_cache: "{{c}}" ... |
Global Scope Variable |
- #ansible-playbook playbook6.yml --extra-vars "a=git b=present c=yes" -b (install git with update_cache)
- #ansible-playbook playbook6.yml --extra-vars "a=git b=absent c=no" -b (uninstall git with no update_cache)
- #ansible-playbook playbook6.yml --extra-vars "a=tree b=present c=no" -b (install tree without update_cache)
Playbook_example7: creating users , assigning home directory and downloading files into users home directory using global scope variable.
--- - name: create user and downloading files into users home directory hosts: all tasks: - name: create user user: name: "{{a}}" password: "{{b}}" home: "{{c}}" - name: downloading files into users home directory get_url: url: "{{d}}" dest: "{{e}}" ... |
Global Scope Variable |
Playbook_example13: Play Scope Variable: install software using play scope varibale where variable is hardcode.
--- - name: install software using play scope variable hosts: all vars: - a: tomcat8 - b: present - c: no tasks: - name: install software apt: name: "{{a}}" state: "{{b}}" update_cache: "{{c}}" ... |
Play Scope Variable |
- #ansible-playbook playbook13.yml (it will install tomcat8 as varible is defined)
- ansible-playbook playbook13.yml --extra-vars "a=git b=present" -b (variable values entered at execution will take precedence, git will be install where variable a & b is defined whiel varible c value will be taken from playbook file.
Handlers: In ansible if any module is failed then it will not execute next module. If we want to execute a module only if someother module is executed successfully and it has made some changes(successfull and yellow coloured), handlers are executed only after all the tasks are executed. Handlers are executed in the order that they are mentioned in the handler section and not in the order they are called in task section. Even if a handler is called multiple times in the task section it will be executed only once.
Playbook_example12:installing apache2, edit index.html and restart apache2 with handler.
- In the plybook_example4 where 4 modules are ececuting, first install tomcat8, copy user.xml file, replace port and restart tomcat8, in this scenarios suppose installing, copy and replace port is done already and outcome will be success but green coloured then there is no point to execute module tomcat8 restart.
--- - name: installing apache2, edit index.html and restart apache2 with handler hosts: all tasks: - name: Installing apache2 apt: name: apache2 state: present - name: Edit index.html copy: content: "Welcome to Star Distributors\n " dest= /var/www/html/index.html notify: restart apache2 handlers: - name: restart apache2 service: name: apache2 state: restarted ...
|
Handlers: There are two tasks define in the playbook, where task one install apache2 and edit index.html, when these two tasks successful and changed in yellow coloured then it notify to handlers to restart apache2 service, if either one task is not sucessfull or not in yellow coloured (changed) then it will not nofify to handlers. |
- #ansible-playbook playbook12.yml -y
- It will install apache2, edit index.html and restart apache2 (sucessful and all yellow coloured)
- if you run the above playbook again the outcome will be install apache2 and edit index.html is successful andwill be in green coloured (not changed) and handler will not be notified and apache2 will not restart.
Playbook_example14: installing apache2, edit index.html and In handler restart apache2 and check url response in nodes.
--- - name: installing apache2, edit index.html and restart apache2 with handler and check url response hosts: all tasks: - name: Installing apache2 apt: name: apache2 state: present notify: url response on all nodes - name: Edit index.html copy: content: "Welcome to Star Distributors\n" dest: /var/www/html/index.html notify: restart apache2 handlers: - name: restart apache2 service: name: apache2 state: restarted - name: url response on all nodes uri: url: "{{item}}" status_code: 200 with_items: - http://172.31.32.32 - http://172.31.42.147 - http://172.31.31.164 - http://172.31.31.64 ... |
Handlers: installing apache2, edit index.html and restart apache2 with handler and check url response |
- #ansible-playbook playbook14.yml -b
Error Handling: Whenever a module in ansible playbook fails, the execution of playbook stops there. If we want to continue the playbook executioneven after a module fails we can use error handling, this is implemented by using three keywords of ansible: Block, Rescue, Always. If a code present block section fails control will come into the rescue section, if the block section is successful control does not come to rescue section. Always section executed everytime irrespective of block section seccess or fails.
Playbook_example15: Error Handling, installing tomcat7 if not tomcat8 and check url response in nodes.
--- - name: Error Handling, installing tomcat7 if not tomcat8 and check url response hosts: all tasks: - block: - name: installing tomcat7 apt: name: tomcat7 state: present rescue: - name: installing tomcat8 apt: name: tomcat8 state: present always: - name: check url is reachable uri: url: "{{item}}" status_code: 200 with_items: - http://172.31.32.32 - http://172.31.42.147 - http://172.31.31.164 - http://172.31.31.64 ... |
Error Handling, installing tomcat7 if not tomcat8 and check url response in always section. |
When Statement: This is similar to if conditions, execute a module only if condition is true/met.
Playbook_example16: When statement: Installing firewalld when the variable value is 10.
--- - name: Implementing when statement hosts: all vars: - a: 10 tasks: - name: installing firewalld apt: name: firewalld state: present when: a == 10 ... |
Implementing when statement
Installing firewalld when the variable value is 10.
|
Debug Module: This is used for printing some output, we can capture the output of any module using register variable and display that using debug module.
Playbook_example17: Create a user and user details are stored in a vaiable and display variable values using debug module.
--- - name: create a user and store values in a variable and display details using debug module hosts: all tasks: - name: create a user user: name: abdulaziz password: India123 home: /home/abdulaziz uid: 1234 register: userdetails - name: display output of user module debug: var: userdetails ... |
create a user and store values in a variable and display details using debug module, when you run playbook it will display details. |
- #ansible-playbook playbook17.yml -b
Tags: Tags are used for getting for more modular control on the playbook execution, using tag we can excecute only certain section of the playbook. register is a variable to store capture data.
--- - name: check directory is present, capture info and display hosts: all tasks: - name: check directory present stat: path: /home/ubuntu register: info - name: display info debug: var: info ... |
check directory is present, capture info and display.
It will check directory present , if present capture information and display when you run playbook.It will present data info in parent and child format. info variable is a parent for directory and all information is present in child format.
ex. "info" : {
"changed": false, (no change in directory), "exists": true, (directory present), "mode": 0755 (permission)
|
Playbook_example18: Execute playbook particular module using tag.
--- - name: Implementing tags, Install tree, create a user, create a file hosts: all tasks: - name: install tree apt: name: tree state: present tags: tree_installation - name: create a user user: name: yezdani password: India123 home: /home/yezdani uid: 1235 tags: user_creation - name: create a file file: name: abc1 state: touch ... |
Implementing tags, Install tree, create a user, create a file
if you run playbook then it will execute all modules, install tree, create user and create a file.
use tag to run specific module.
files will not be created as there is no tag defined. it only created if run playbook without defining tags.
|
- #ansible-playbook playbook18.yml -b (will execute all modules)
- #ansible-playbook playbook18.yml --tags=user_creation (only user creation module will be executed)
- #ansible-playbook playbook18.yml --tags=tagged (all modules where tags are defined will be executed, file tag is not defined.)
- #ansible-playbook playbook18.yml --tags=untagged( modules without tags are defined will be executed)
Condition Statement:
Playbook_example19: Check a directory is present in remote nodes. module stat is used to get information about a file or directory from remote nodes.
--- - name: check directory is present, capture info and display hosts: all tasks: - name: check directory present stat: path: /home/ubuntu register: info - name: display info debug: var: info ... |
check directory is present, capture info and display.
It will check directory present , if present capture information and display when you run playbook.It will present data info in parent and child format. info variable is a parent for directory and all information is present in child format.
ex. "info" : {
"changed": false, (no change in directory), "exists": true, (directory present), "mode": 0755 (permission)
|
- #ansible-playbook playbook19.yml -b
Playbook_example20: Check apache2 is installed by checking /var/www/html/index.html file exist. The output of any module is captured in jason format, this output can be captured in variable which belongs to register type and it can be displayed using debug module.
--- - name: check directory is present, capture info and display hosts: all tasks: - name: check file present stat: path: /var/www/html/index.html register: info - name: display info debug: var: info ... |
it will check file index.html is present or not, if present display information, where you can check exists: true. |
Playbook_example21: check the directory is present, if not present then create a directory. The output of any module is captured in jason format, this output can be captured in variable which belongs to register type and it can be displayed using debug module.
--- - name: check directory is present, capture info and display hosts: all tasks: - name: check folder present stat: path: /home/ubuntu/folder100 register: info - name: display info debug: var: info - name: create a folder folder100 file: name: /home/ubuntu/folder100 state: touch when: info.stat.exists == false ... |
it will check the directory folder100 is present and capture details and display.
we have define parent and child condition as follows:
info.stat.exists == false (info is parent, child is stat, subchild is exists, if it is false (folder100 is not present) then it will create folder.
|
Include Module: A child playbook can be called in parent playbook and execute.
Playbook_example22:
Playbook_example8: Check nodes uptime
--- - name: Check the remote host uptime hosts: all tasks: - name: Execute the Uptime command over Command module register: uptimeoutput command: "uptime"
- debug: var: uptimeoutput.stdout_lines ...
|
|
Playbook_example9:Check the node hostname, version, distribution with uname.
--- - name: Check the remote host Hostname, Version, Distribution with UNAME hosts: all tasks: - name: Execute the UNAME command register: unameout command: "uname -a"
- debug: var: unameout.stdout_lines
...
|
|
Playbook_example10: Install Apache 2 and make sure it is latest and running.
--- - name: Install apache2, make sure it is lates and running hosts: all become: yes become_user: root tasks: - name: Install apache2 latest version apt: name: apache2 state: latest - name: ensure apache is running service: name: apache2 state: started ...
|
|
Playbook_example11: Apache2 restart
--- - name: restart apache web server hosts: all become: yes become_user: root tasks: - name: restartapache service: name: apache2 state: restarted ... |
|
hosts: all
become: yes
tasks:
- name: install git
package:
name: git
state: present
-name: uninstall git
package:
name: git
state: absent
|
Install tree package in ubuntu machine using playbook automation:
manual steps:
- #sudo apt-get update
- #sudo apt-get install tree -y
The above manual execution perform in ansible automation:
- inventory file
- playbook
playbook:The above manual commands done with automation in playbook
hosts: all
become: yes
tasks:
-name: update ubuntu packages
-name: install tree
|
3. module: need module to automate, select pre-defined modules and can write custom modules (required python code).
- Search the modules in google for the above apt-get update (apt-get update in ansible)
4. based on search result from google, fill the module in playbook
hosts: all
become: yes
tasks:
-name: update ubuntu packages and install tree
apt:
name: tree
update_cache: yes
state: present
|
5. log into ansible controller.
6. inventory file
7. create yaml file
8. run yaml file