bashadvanced

Ansible Playbook for Server Setup

Ansible playbook to provision a web server with Nginx, Node.js, and firewall configuration.

bash
# playbook.yml
---
- name: Setup Web Server
  hosts: webservers
  become: true
  vars:
    node_version: "20"
    app_dir: /opt/webapp

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install base packages
      apt:
        name:
          - nginx
          - ufw
          - curl
          - git
        state: present

    - name: Install Node.js
      shell: |
        curl -fsSL https://deb.nodesource.com/setup_{{ node_version }}.x | bash -
        apt-get install -y nodejs
      args:
        creates: /usr/bin/node

    - name: Create app directory
      file:
        path: "{{ app_dir }}"
        state: directory
        owner: www-data
        group: www-data

    - name: Configure UFW firewall
      ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop:
        - '22'
        - '80'
        - '443'

    - name: Enable UFW
      ufw:
        state: enabled
        default: deny

    - name: Copy Nginx config
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/sites-available/webapp
      notify: Restart Nginx

    - name: Enable site
      file:
        src: /etc/nginx/sites-available/webapp
        dest: /etc/nginx/sites-enabled/webapp
        state: link

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

# Run: ansible-playbook -i inventory.yml playbook.yml

Use Cases

  • Automated server provisioning across environments
  • Reproducible infrastructure setup
  • Configuration management for web servers

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.