Fferanet
Wiki menu

Ansible

Create an inventory file to define the hosts and groups of hosts to manage.

Configuration

Inventory File

Create an inventory file to define the hosts and groups of hosts to manage.

# filepath: /etc/ansible/hosts
[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.comini

Ansible Configuration File

Create an Ansible configuration file to set global options.

# filepath: /etc/ansible/ansible.cfg
[defaults]
inventory = /etc/ansible/hosts
remote_user = ansible
host_key_checking = Falseini

Basic Commands

Ping All Hosts

ansible all -m pingbash

Run a Command on All Hosts

ansible all -a "/bin/echo hello"bash

Run a Command on a Specific Group

ansible webservers -a "/bin/echo hello"bash

Playbooks

Basic Playbook

Create a playbook to automate tasks.

# filepath: /etc/ansible/playbooks/example.yml
- hosts: webservers
  tasks:
    - name: Ensure Apache is installed
      apt:
        name: apache2
        state: present
      become: yes

    - name: Ensure Apache is running
      service:
        name: apache2
        state: started
        enabled: yes
      become: yesyaml

Run a Playbook

ansible-playbook /etc/ansible/playbooks/example.ymlbash

Useful Modules

Package Management

- name: Install a package
  apt:
    name: package_name
    state: present
  become: yesyaml

Service Management

- name: Start a service
  service:
    name: service_name
    state: started
    enabled: yes
  become: yesyaml

File Management

- name: Create a directory
  file:
    path: /path/to/directory
    state: directory
    mode: "0755"
  become: yesyaml