Mastering Ansible: 10 Essential Playbook Examples for Automating Your IT Infrastructure
1. Ping Module
This playbook pings all servers in the all
group.
- name: Test connectivity hosts: all tasks: - name: Ping all hosts ping:
2. Install a Package
Installs the "nginx" package on all Debian-based servers.
- name: Install Nginx hosts: all become: yes tasks: - name: Install nginx apt: name: nginx state: present
3. Copy File
Copies a local file to remote hosts.
- name: Copy file to hosts hosts: all tasks: - name: Copy sample file copy: src: /localpath/sample.txt dest: /remotepath/sample.txt
4. Create a User
Creates a user on all servers.
- name: Create a user hosts: all become: yes tasks: - name: Ensure user 'johndoe' is present user: name: johndoe state: present
5. Manage Services
Starts and enables the "httpd" service on CentOS servers.
- name: Manage Httpd Service hosts: all become: yes tasks: - name: Start and enable httpd service: name: httpd state: started enabled: true
6. Execute Commands
Runs a shell command on all servers.
- name: Execute a command hosts: all tasks: - name: List contents of directory command: ls -l /some/directory
7. Gather Facts
Gathers facts about the hosts without any specific task.
- name: Gather facts hosts: all tasks: - name: Gather facts from hosts setup:
8. Conditional Tasks
Executes a task based on a condition.
- name: Conditional task hosts: all tasks: - name: Install httpd on CentOS 7 yum: name: httpd state: latest when: ansible_distribution == 'CentOS' and ansible_distribution_major_version == '7'
9. Loop Example
Installs multiple packages using a loop.
- name: Install multiple packages hosts: all become: yes tasks: - name: Install packages apt: name: "{{ item }}" state: present loop: - vim - git
10. Template Module
Deploys a configuration file from a Jinja2 template.
- name: Deploy template hosts: all tasks: - name: Deploy a template file template: src: /localpath/template.j2 dest: /remotepath/config.conf
No comments:
Post a Comment