[RHCE] 07 – Create Ansible plays and playbooks

    07_01 Commonly Used Ansible Modules Guide

    Package Management

    # filepath: package_examples.yml
    ---
    - name: Package Management Examples
      hosts: all
      become: true
      tasks:
        - name: Install packages (DNF)
          dnf:
            name: 
              - httpd
              - php
            state: present
            
        - name: Remove package (YUM)
          yum:
            name: telnet
            state: absent
            
        - name: Install from RPM
          dnf:
            name: https://example.com/package.rpm
            state: present
    

    File Operations

    # filepath: file_examples.yml
    ---
    - name: File Management Examples
      hosts: all
      tasks:
        - name: Create directory
          file:
            path: /opt/app
            state: directory
            mode: '0755'
            
        - name: Copy file
          copy:
            src: files/config.conf
            dest: /etc/app/config.conf
            owner: root
            group: root
            mode: '0644'
            
        - name: Create from template
          template:
            src: templates/app.conf.j2
            dest: /etc/app/app.conf
            
        - name: Create symlink
          file:
            src: /opt/app
            dest: /var/www/app
            state: link
    

    Service Management

    # filepath: service_examples.yml
    ---
    - name: Service Management Examples
      hosts: all
      become: true
      tasks:
        - name: Start service
          service:
            name: httpd
            state: started
            enabled: yes
            
        - name: Restart service
          systemd:
            name: mariadb
            state: restarted
            daemon_reload: yes
    

    User Management

    # filepath: user_examples.yml
    ---
    - name: User Management Examples
      hosts: all
      become: true
      tasks:
        - name: Create user
          user:
            name: webadmin
            shell: /bin/bash
            groups: wheel
            append: yes
            
        - name: Create group
          group:
            name: developers
            state: present
    

    System Tasks

    # filepath: system_examples.yml
    ---
    - name: System Management Examples
      hosts: all
      become: true
      tasks:
        - name: Set timezone
          timezone:
            name: America/New_York
            
        - name: Configure firewall
          firewalld:
            service: http
            permanent: yes
            state: enabled
            
        - name: Gather facts
          setup:
            gather_subset:
              - hardware
              - network
    

    Remember to check module documentation for complete parameter lists and examples.


    07_02 Using Variables with Command Results

    Basic Command Registration

    # filepath: command_register.yml
    ---
    - name: Command Output Examples
      hosts: all
      tasks:
        - name: Get disk usage
          command: df -h
          register: disk_info
        
        - name: Show disk info
          debug:
            var: disk_info.stdout_lines
    

    Conditional Execution

    # filepath: conditional_commands.yml
    ---
    - name: Service Check Example
      hosts: webservers
      tasks:
        - name: Check service status
          command: systemctl status httpd
          register: service_status
          ignore_errors: yes
        
        - name: Start service if not running
          service:
            name: httpd
            state: started
          when: service_status.rc != 0
    

    Error Handling

    # filepath: error_handling.yml
    ---
    - name: Error Handling Example
      hosts: all
      tasks:
        - name: Check file content
          command: cat /etc/myapp.conf
          register: file_content
          ignore_errors: yes
          
        - name: Create default config
          copy:
            src: files/default.conf
            dest: /etc/myapp.conf
          when: file_content.rc != 0
    

    Working with Results

    # filepath: process_results.yml
    ---
    - name: Process Command Results
      hosts: all
      tasks:
        - name: Get process list
          shell: ps aux | grep httpd | wc -l
          register: process_count
          
        - name: Alert if too many processes
          debug:
            msg: "Warning: High process count - {{ process_count.stdout }}"
          when: process_count.stdout|int > 10
    

    Complete Production Example

    # filepath: system_check.yml
    ---
    - name: System Health Check
      hosts: production
      tasks:
        - name: Check disk space
          shell: df -h | awk '{ print $5 }' | grep -v Use
          register: disk_usage
          
        - name: Check memory
          shell: free -m | awk 'NR==2{printf "%s\n", $3/$2*100}'
          register: memory_usage
          
        - name: Check load average
          shell: uptime | awk -F'load average:' '{ print $2 }' | awk -F, '{ print $1 }'
          register: load_average
          
        - name: Generate alert
          debug:
            msg: |
              System Alert:
              Disk Usage: {{ disk_usage.stdout_lines }}
              Memory Usage: {{ memory_usage.stdout }}%
              Load Average: {{ load_average.stdout }}
          when: >
            disk_usage.stdout_lines|select('match', '^9[0-9]%')|list|length > 0 or
            memory_usage.stdout|float > 90 or
            load_average.stdout|float > 5

    07_03 Using Conditionals in Ansible Plays

    Basic Conditionals

    # filepath: basic_conditions.yml
    ---
    - name: Basic Conditional Examples
      hosts: all
      tasks:
        - name: Install Apache on RHEL
          dnf:
            name: httpd
            state: present
          when: ansible_distribution == "RedHat"
    
        - name: Install Apache on Ubuntu
          apt:
            name: apache2
            state: present
          when: ansible_distribution == "Ubuntu"
    

    Multiple Conditions

    # filepath: multiple_conditions.yml
    ---
    - name: Multiple Conditions Example
      hosts: webservers
      tasks:
        - name: Configure High Memory Server
          template:
            src: high_mem.conf.j2
            dest: /etc/httpd/conf.d/custom.conf
          when:
            - ansible_memtotal_mb > 4096
            - ansible_distribution == "RedHat"
            - ansible_distribution_major_version == "8"
    

    Complex Logic Example

    # filepath: complex_logic.yml
    ---
    - name: Complex Logic Example
      hosts: all
      tasks:
        - name: Complex deployment logic
          debug:
            msg: "Deploying to production server"
          when: >
            (ansible_hostname.startswith('prod') and
             ansible_memtotal_mb >= 8192) or
            (ansible_hostname.startswith('stage') and
             ansible_memtotal_mb >= 4096)
    

    Working Production Example

    # filepath: production_deploy.yml
    ---
    - name: Production Deployment
      hosts: webservers
      vars:
        min_memory_mb: 4096
        required_mounts: ["/var", "/opt", "/tmp"]
        
      tasks:
        - name: Check system requirements
          assert:
            that:
              - ansible_memtotal_mb >= min_memory_mb
              - ansible_mounts | map(attribute='mount') | intersect(required_mounts) | length == required_mounts | length
            msg: "System does not meet minimum requirements"
    
        - name: Deploy application
          include_tasks: deploy.yml
          when: 
            - ansible_distribution in ["RedHat", "CentOS"]
            - ansible_distribution_major_version == "8"
            - ansible_selinux.status == "enabled"

    07_04 Ansible Error Handling Guide

    Basic Error Handling

    # filepath: /examples/basic_error.yml
    ---
    - name: Basic Error Handling
      hosts: webservers
      tasks:
        - name: Check service status
          command: systemctl status httpd
          register: service_status
          ignore_errors: yes
    
        - name: Show status
          debug:
            var: service_status.stdout_lines
          when: service_status is success
    

    Block Error Handling

    # filepath: /examples/block_error.yml
    ---
    - name: Block Error Handling
      hosts: webservers
      tasks:
        - name: Handle deployment errors
          block:
            - name: Deploy application
              git:
                repo: https://github.com/app/repo.git
                dest: /var/www/html
                
            - name: Configure application
              template:
                src: app.conf.j2
                dest: /etc/app/config.conf
                
          rescue:
            - name: Restore backup
              copy:
                src: /backup/app.conf
                dest: /etc/app/config.conf
                
          always:
            - name: Restart service
              service:
                name: httpd
                state: restarted
    

    Custom Error Conditions

    # filepath: /examples/custom_error.yml
    ---
    - name: Custom Error Conditions
      hosts: all
      tasks:
        - name: Check disk space
          shell: df -h / | awk 'NR==2 {print $5}' | sed 's/%//'
          register: disk_space
          failed_when: disk_space.stdout|int >= 90
    

    Production Error Handling

    # filepath: /examples/production_error.yml
    ---
    - name: Production Deployment
      hosts: production
      any_errors_fatal: true
      max_fail_percentage: 20
      
      pre_tasks:
        - name: Verify requirements
          block:
            - name: Check disk space
              shell: df -h / | awk 'NR==2 {print $5}' | sed 's/%//'
              register: disk_space
              failed_when: disk_space.stdout|int >= 85
              
            - name: Check memory
              shell: free | awk '/Mem:/ {print $4/$2 * 100.0}'
              register: memory
              failed_when: memory.stdout|float <= 20.0
              
          rescue:
            - name: Log failure
              local_action: 
                module: shell
                cmd: echo "Pre-check failed on {{ inventory_hostname }}" >> /var/log/deploy.log
              
            - name: Skip host
              meta: clear_host_errors

    07_05 System State Configuration Playbooks

    Base System Configuration

    # filepath: /playbooks/base_config.yml
    ---
    - name: Configure Base System State
      hosts: all
      become: true
      
      vars:
        timezone: America/New_York
        ntp_servers:
          - 0.pool.ntp.org
          - 1.pool.ntp.org
        sysctl_settings:
          net.ipv4.ip_forward: 1
          vm.swappiness: 10
        
      tasks:
        - name: Set timezone
          timezone:
            name: "{{ timezone }}"
        
        - name: Configure chronyd
          template:
            src: chrony.conf.j2
            dest: /etc/chrony.conf
          notify: restart chronyd
        
        - name: Set kernel parameters
          sysctl:
            name: "{{ item.key }}"
            value: "{{ item.value }}"
            state: present
            sysfs: yes
          loop: "{{ sysctl_settings | dict2items }}"
    

    Security Configuration

    # filepath: /playbooks/security_config.yml
    ---
    - name: Configure System Security
      hosts: all
      become: true
    
      tasks:
        - name: Set password policy
          lineinfile:
            path: /etc/security/pwquality.conf
            regexp: "^{{ item.key }}="
            line: "{{ item.key }}={{ item.value }}"
          loop:
            - { key: 'minlen', value: '12' }
            - { key: 'minclass', value: '4' }
            - { key: 'dcredit', value: '-1' }
            - { key: 'ucredit', value: '-1' }
        
        - name: Configure SSH
          template:
            src: sshd_config.j2
            dest: /etc/ssh/sshd_config
            validate: '/usr/sbin/sshd -t -f %s'
          notify: restart sshd
    

    State Verification

    # filepath: /playbooks/verify_state.yml
    ---
    - name: Verify System State
      hosts: all
      become: true
    
      tasks:
        - name: Check services
          service_facts:
        
        - name: Verify required services
          assert:
            that:
              - ansible_facts.services['httpd.service'].state == 'running'
              - ansible_facts.services['firewalld.service'].state == 'running'
            msg: "Required services not running"
        
        - name: Verify file permissions
          stat:
            path: "{{ item }}"
          register: file_stats
          loop:
            - /etc/passwd
            - /etc/shadow
            - /etc/ssh/sshd_config
        
        - name: Assert correct permissions
          assert:
            that:
              - file_stats.stat.mode == '0644'
            msg: "Incorrect file permissions"
          when: file_stats.stat.path == '/etc/passwd'


    Discover more from Altgr Blog

    Subscribe to get the latest posts sent to your email.

    Leave a Reply

    Your email address will not be published. Required fields are marked *