Ansible YAML Playbooks Overview

Introduction

Introduction

Playbooks record and execute Ansible’s configuration, deployment, and orchestration functions. Using YAML format, files end with .yaml or .yml

Official website:

https://docs.ansible.com/ansible/latest/user_guide/playbooks.html#working-with-playbooks

YAML Language

Introduction to Play Syntax

Syntax Overview: Almost every YAML file starts with a list. Each item in the list is a key/value pair list, commonly referred to as a "hash" or "dictionary". All YAML files (regardless of whether they are associated with Ansible) can optionally start and end with --- to indicate the beginning and end of the document. All members of the list begin with lines at the same indentation level, starting with a dash and a space: "- ". Dictionaries are represented in a simple form (a space must follow the colon): key: value.
Subsequent lines generally write the file content, with strict indentation and case sensitivity. Key/value pairs can be written across multiple lines or in a single line, separated by commas. A value can be a string or a list. A play must include a name and tasks; name is a description; tasks are actions. A name can only contain one task. The file extension can be yml or yaml.

Example: cat yml_file/sshd.yml ---- name: change sshd file     # The dash in front indicates a list  hosts: 192.168.1.1         # The host to execute, can be an IP address, hostname, or inventory group name  gather_facts: false        # Do not collect facts variables  vars:                      # Set variables in key-value form, can also use vars_files to specify files    port: 9222              # Key-value pair for a single variable    users:                   # A single key corresponding to multiple values      - user01      - user02  tasks:                    # Ansible tasks    - name: add port        # Task name      lineinfile:           # Module used        path: /etc/ssh/sshd_config        insertafter: '^#Port 22'        line: 'Port {{ port }}'        backup: yes    - name: add permit user   # Second task      lineinfile:        path: /etc/ssh/sshd_config        line: 'allowusers     {{ users | join(" ") }}'   # Using join function to connect all value values        state: present       notify: rest sshd                      # Trigger defined handlers, indicating that the module is successfully executed  handlers:    - name: rest sshd      service:        name: httpd        state: restarted

Leave a Comment