Practical Ansible Use Cases
Server Provisioning
Ansible can be used to automate the provisioning of servers, including installing the operating system, configuring network settings, and installing necessary software. Here's an example playbook that provisions a new Ubuntu 22.04 server:
- hosts: new_server
tasks:
- name: Install required packages
apt:
name:
- openssh-server
- python3
- python3-pip
state: present
- name: Configure network settings
network:
interface: eth0
dhcp: yes
- name: Create a new user
user:
name: labex
groups: sudo
password: "$6$rounds=656000$xxxxxxxxxx"
Configuration Management
Ansible can be used to manage the configuration of servers and applications, ensuring that they are in the desired state. This includes tasks such as installing and configuring software, managing system services, and applying security updates.
- hosts: webservers
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Start Apache
systemd:
name: apache2
state: started
enabled: yes
- name: Copy Apache configuration
template:
src: apache.conf.j2
dest: /etc/apache2/apache.conf
notify: Restart Apache
handlers:
- name: Restart Apache
systemd:
name: apache2
state: restarted
Application Deployment
Ansible can be used to automate the deployment of applications, including tasks such as building and packaging the application, deploying it to the target servers, and configuring any necessary dependencies.
- hosts: app_servers
tasks:
- name: Build application
docker_image:
name: myapp
build:
path: .
- name: Deploy application
docker_container:
name: myapp
image: myapp
state: started
ports:
- 80:8080
Orchestration and Workflow Automation
Ansible can be used to orchestrate complex workflows, such as provisioning infrastructure, deploying applications, and performing maintenance tasks. This can be achieved by chaining multiple playbooks together or by using Ansible's built-in workflow features, such as roles and tags.
graph TD
A[Provision Infrastructure] --> B[Deploy Application]
B --> C[Perform Maintenance]
C --> D[Decommission Infrastructure]
By leveraging Ansible's flexibility and power, you can automate a wide range of IT tasks and workflows, improving efficiency, consistency, and reliability across your infrastructure.