ansible playbook code example

Example 1: ansible playbook enable service

- name: Start service httpd, if not started
  service:
    name: httpd
    state: started

- name: Stop service httpd, if started
  service:
    name: httpd
    state: stopped

- name: Restart service httpd, in all cases
  service:
    name: httpd
    state: restarted

- name: Reload service httpd, in all cases
  service:
    name: httpd
    state: reloaded

- name: Enable service httpd, and not touch the state
  service:
    name: httpd
    enabled: yes

- name: Start service foo, based on running process /usr/bin/foo
  service:
    name: foo
    pattern: /usr/bin/foo
    state: started

- name: Restart network service for interface eth0
  service:
    name: network
    state: restarted
    args: eth0

Example 2: run ansible yaml file

ansible-playbook playbook.yml

Example 3: ansible playbook webserver

- hosts: "webserver"
  tasks:
  - name: "installing webserver"
    package:
        name: "httpd"
        state: "present"
  - name: "copying index.html"
    copy:
        src: "~/index.html"
        dest: "/var/www/html/"
  - name: "starting httpd service"
    service:
        name: "httpd"
        state: "started"

  - name: "stopping firewalld service"
    service:
        name: "firewalld"
        state: "stopped"

Example 4: ansible example playbook

---
- name: update web servers
  hosts: webservers
  remote_user: root

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf

- name: update db servers
  hosts: databases
  remote_user: root

  tasks:
  - name: ensure postgresql is at the latest version
    yum:
      name: postgresql
      state: latest
  - name: ensure that postgresql is started
    service:
      name: postgresql
      state: started

Example 5: ansible playbook omit tag

# Use the --skip-tags flag 
ansible-playbook myplaybook.yaml --skip-tags mytag

Tags:

Misc Example