playbooks itself consists of the following parts
(1) Tasks: tasks, that is, multiple operations are organized and run in one playbook by calling ansible templates through tasks
(2) Variables: Variables
(3) Templates: Templates
(4) Handlers: processor. When the changed status condition is met, (notify) triggers the operation to be executed
(5) Roles: roles
//Example:
vim test1.yaml --- #Yaml file starts with - -- to indicate that this is a yaml file and can be omitted - name: first play #Define the name of a play, which can be omitted gather_facts: false #Set not to collect facts information, which can speed up the execution speed and can be omitted hosts: webservers #Specify the managed host groups to perform tasks. For example, multiple host groups are separated by colons remote_user: root #Specifies the user who performs tasks on the managed host tasks: #Define the task list. Each task in the task list is executed on the host specified in hosts one by one in order - name: test connection #Custom task name ping: #Use the format of module: [options] to define a task - name: disable selinux command: '/sbin/setenforce 0' #The command module and shell module do not need to use the key=value format ignore_errors: True #If the return value of the command is not 0, an error will be reported and tasks will stop. You can use ignore_errors ignore failed tasks - name: disable firewalld service: name=firewalld state=stopped #The task is defined in the format of module: options, and the option is in the format of key=value - name: install httpd yum: name=httpd state=latest - name: install configuration file for httpd copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf #Here you need a prepared / opt/httpd.conf file notify: "restart httpd" #If the status is changed after the above operation, the handlers operation of the corresponding name will be triggered through the name specified in notify - name: start httpd service service: enabled=true name=httpd state=started handlers: #Tasks are defined in handlers. The tasks in handlers here use the service module - name: restart httpd #The names of tasks in notify and handlers must be consistent service: name=httpd state=restarted ##Ansible does not execute the corresponding handler immediately after executing a task, but executes the handler after all ordinary tasks in the current play. This has the advantage that notify can be triggered multiple times, but only execute the corresponding handler once in the end, so as to avoid multiple restarts.
//Run playbook
ansible-playbook test1.yaml
//Supplementary parameters:
-k (– ask pass): used to enter ssh password interactively
-K (- ask come pass): used to enter sudo password interactively
-u: Designated user
Ansible playbook test1.yaml -- syntax check # checks whether the syntax of yaml file is correct
Ansible playbook test1.yaml -- list task # check tasks
Ansible playbook test1.yaml -- List hosts # check valid hosts
Ansible playbook test1.yaml -- start at task ='install httpd '# specifies to run from a task
//Define and reference variables
- name: second play hosts: dbservers remote_user: root vars: #Define variables - groupname: mysql #The format is key: value - username: nginx tasks: - name: create group group: name={{groupname}} system=yes gid=306 #Use {{key}} to reference the value of the variable - name: create user user: name={{username}} uid=306 group={{groupname}} - name: copy file copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt #The facts variable information can be obtained in the setup module ansible-playbook test1.yaml -e "username=nginx" #Define variables on the command line
//Specify the remote host sudo switch user
--- - hosts: dbservers remote_user: zhangsan become: yes #The parameter after version 2.6, formerly sudo, means to switch the user's operation become_user: root #Specify sudo user as root
When executing Playbook: ansible playbook test1.yml - K < password >
//when condition judgment
In Ansible, the only general condition judgment provided is the when instruction. When the value of the when instruction is true, the task will be executed, otherwise the task will not be executed.
//when a common application scenario is to skip a host and do not execute tasks, or only qualified hosts execute tasks
vim test2.yaml --- - hosts: all remote_user: root tasks: - name: shutdown host command: /sbin/shutdown -r now when: ansible_default_ipv4.address == "192.168.73.40" #The variable name in the when directive does not need to be manually added with {} or when: inventory_hostname == "<host name>" ansible-playbook test2.yaml
//Iteration
Ansible provides many kinds of loop structures, which are generally named with_items, which is equivalent to a loop loop.
vim test3.yaml --- - name: play1 hosts: dbservers gather_facts: false tasks: - name: create directories file: path: "{{item}}" state: directory with_items: #Equivalent to loop: - /tmp/test1 - /tmp/test2 - name: add users user: name={{item.name}} state=present groups={{item.groups}} with_items: - name: test1 groups: wheel - name: test2 groups: root or with_items: - {name:'test1', groups:'wheel'} - {name:'test2', groups:'root'} ansible-playbook test3.yaml
//Templates module
Jinja is a Python based template engine. Template class is an important component of Jinja. It can be regarded as a compiled template file, which is used to generate target text and pass Python variables to the template to replace the tags in the template.
1. First prepare a template file with. j2 as suffix and set the referenced variables
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2 vim /opt/httpd.conf.j2 Listen {{http_port}} #Line 42, modified ServerName {{server_name}} #Line 95, modified DocumentRoot "{{root_dir}}" #Line 119, modify
2. Modify the host list file and use the host variable to define a variable with the same variable name but different values
vim /etc/ansible/hosts [webservers] 192.168.73.40 http_port=192.168.80.11:80 server_name=www.accp.com:80 root_dir=/etc/httpd/htdocs [dbservers] 192.168.73.50 http_port=192.168.80.12:80 server_name=www.benet.com:80 root_dir=/etc/httpd/htdocs
3. Write playbook
vim apache.yaml --- - hosts: all remote_user: root vars: - package: httpd - service: httpd tasks: - name: install httpd package yum: name={{package}} state=latest - name: install configure file template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #Use template template notify: - restart httpd - name: create root dir file: path=/etc/httpd/htdocs state=directory - name: start httpd server service: name={{service}} enabled=true state=started handlers: - name: restart httpd service: name={{service}} state=restarted ansible-playbook apache.yaml
//tags module
You can define "tags" for one or some tasks in a playbook. When executing this playbook, you can only run the specified tasks by using the -- tags option through the ansible playbook command.
playbook also provides a special tags for always. The function is that when the task of always is used, no matter which tag is executed, the tags with always defined will be executed.
vim webhosts.yaml --- - hosts: webservers remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/opt/hosts tags: - only #Customizable - name: touch file file: path=/opt/testhost state=touch tags: - always #Represents the code to always run ansible-playbook webhosts.yaml --tags="only"
vim dbhosts.yaml --- - hosts: dbservers remote_user: root tasks: - name: Copy hosts file copy: src=/etc/hosts dest=/opt/hosts tags: - only - name: touch file file: path=/opt/testhost state=touch ansible-playbook dbhosts.yaml --tags="only"
//Go to the two managed hosts to check the file creation
//Roles module
Ansible uses roles to organize playbooks hierarchically and structurally. Roles can automatically load variable files, tasks, handlers, etc. according to the hierarchical structure. In short, roles is to place variables, files, tasks, modules and processors in separate directories and easily include them. Roles are generally used in the scenario of building services based on hosts, but they can also be used in scenarios such as building daemons.
//Directory structure of roles:
cd /etc/ansible/ tree roles/ roles/ ├── web/ │ ├── files/ │ ├── templates/ │ ├── tasks/ │ ├── handlers/ │ ├── vars/ │ ├── defaults/ │ └── meta/ └── db/ ├── files/ ├── templates/ ├── tasks/ ├── handlers/ ├── vars/ ├── defaults/ └── meta/
//Explanation of the meaning of each directory in roles
●files
Used to store files called by copy module or script module.
●templates
It is used to store jinjia2 templates. The template module will automatically find jinjia2 template files in this directory.
●tasks
This directory should contain a main.yml file to define the task list of this role. This file can use include to contain other task files located in this directory.
●handlers
This directory should contain a main.yml file that defines the actions to be performed when triggering conditions in this role.
●vars
This directory should contain a main.yml file that defines the variables used by this role.
●defaults
This directory should contain a main.yml file to set default variables for the current role.
●meta
This directory should contain a main.yml file that defines the special settings of this role and its dependencies.
//To use roles in a playbook:
(1) Create a directory named roles
mkdir /etc/ansible/roles/ -p #yum will be installed by default
(2) Create global variable directory (optional)
mkdir /etc/ansible/group_vars/ -p touch /etc/ansible/group_vars/all #The file name is defined by itself. Pay attention when referencing
(3) In the roles directory, create directories for commands with the name of each role, such as httpd and mysql
mkdir /etc/ansible/roles/httpd mkdir /etc/ansible/roles/mysql
(4) Create files, handlers, tasks, templates, meta, defaults, and vars directories in the directory of each role command. Directories that are not used can be created as empty directories or not
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta}
(5) Create the main.yml file in the directories of handlers, tasks, meta, defaults and vars of each role. You must not customize the file name
touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
(6) Modify the site.yml file to call different roles for different hosts
vim /etc/ansible/site.yml --- - hosts: webservers remote_user: root roles: - httpd - hosts: dbservers remote_user: root roles: - mysql
(7) Run ansible playbook
cd /etc/ansible ansible-playbook site.yml
Example:
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml
------Write httpd module------
Write a simple tasks/main.yml
vim /etc/ansible/roles/httpd/tasks/main.yml - name: install apache yum: name={{pkg}} state=latest - name: start apache service: enabled=true name={{svc}} state=started
//Define variable: it can be defined in global variables or roles variables. Generally, it is defined in role variables
vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd
-------Write mysql module-------
vim /etc/ansible/roles/mysql/tasks/main.yml - name: install mysql yum: name={{pkg}} state=latest - name: start mysql service: enabled=true name={{svc}} state=started vim /etc/ansible/roles/mysql/vars/main.yml pkg: - mariadb - mariadb-server svc: mariadb
-------Writing php modules-----
vim /etc/ansible/roles/php/tasks/main.yml - name: install php yum: name={{pkg}} state=latest - name: start php-fpm service: enabled=true name={{svc}} state=started vim /etc/ansible/roles/php/vars/main.yml pkg: - php - php-fpm svc: php-fpm
-----Writing roles examples-----
vim /etc/ansible/site.yml --- - hosts: webservers remote_user: root roles: - httpd - mysql - php
cd /etc/ansible
ansible-playbook site.yml