Ansible

Ansible is an open-source software provisioning, configuration management, and application-deployment tool enabling infrastructure as code. Ansible is agent less (push configuration), Python based, connect via SSH to run commands, Open Source.

Ansible Examples

Ansible: Create a file with Date & Time Stamp

This Ansible playbook demonstrates how to:

  1. Retrieve the current date and time via ansible-facts
  2. Store the date and time in variables
  3. Concatenate the date & time with a string to build the filename
  4. Create the file the the timestamped filename
  5. Run a command for hosts in the inventory
  6. Retrieve attributes from the command results
  7. Write the results of the command for each host to the timestamped file

--- 
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
# Ansible Playbook 
# FileName: demo-timestamp-filename.yml 
# 
# Description: Demonstrate how to create a file 
#              with a timestamped filename
#              and write command results to the file
# 
# Revised: 2021-01-18 by Chin for ConsciousVibes.com
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 


- name: Output to Filename with Timestamp
  hosts: healthchecks
  connection: local
  gather_facts: yes
  strategy: linear
  order: inventory

  vars:
    report_filename_prefix: "HealthCheckResults-"
    report_date_time: "{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}"
    report_filename_date: "{{ report_filename_prefix }}{{ report_date_time }}.txt"
    report_path: "/reports/healthchecks/{{ report_filename_date }}"

  tasks:
    - name: Create file with timestamped filename
      delegate_to: localhost
      lineinfile:
        path: "{{ report_path }}"
        create: yes
        line: "Start: Health Check Report\n{{ report_path }}"
      run_once: true

    - name: Run nslookup command
      delegate_to: localhost
      throttle: 1
      command: nslookup {{ inventory_hostname }}
      register: nslookup_result

    - name: Append nslookup results to a file
      delegate_to: localhost
      throttle: 1
      blockinfile:
        state: present
        insertafter: EOF
        dest: "{{ report_path }}"
        marker: "- - - - - - - - - - - - - - - - - - - - -"
        block: |

          Server: {{ inventory_hostname }}
          Environment: {{ environmentz }}

                {{ nslookup_result.stdout_lines.3 }}
                {{ nslookup_result.stdout_lines.4 }}

### End of Playbook

Note: If the time changes (e.g. hour or minutes) while the playbook is still iterating through the hosts in the inventory, the variable changes, throwing a “path does not exist” error for each of the remaining hosts.

See: Ansible: How to Define Variables in Playbook Which Do Not Change per Host

Reference