Easy script -- playbook script

1: playbooks overview

1.1 what is playbooks

Playbooks are Ansible's configuration, deployment and orchestration languages. They can be described as a scheme that requires a remote host to execute commands, or a set of commands run by a group of IT programs

At the basic level, playbooks can be used to manage configuration files for deployment to remote hosts. At a higher level, playbooks can successively perform online operations, including rolling updates, on servers in a multi-layer architecture, and delegate operations to other hosts, including interaction with monitoring servers and load balancing servers

The format of playbooks is YAM and the syntax is minimized to avoid playbooks becoming a programming language or script, but it is not a configuration model or process model

playbook consists of one or more 'plays'. Its content is a list with' plays' as the element

In play, a group of machines are mapped to defined roles. In ansible, the content of play is called tasks, that is, tasks. In basic level applications, a task is a call to ansible modules, which has been learned in the previous chapters

'plays' is like a musical note, and playbook is like a musical score composed of' plays'. Through playbook, you can arrange steps for multi machine deployment, such as running certain steps on all machines in the webservers group, then running some steps in the database server group, and finally returning to the webservers group, and then running some steps, and so on

"Games" is a sports analogy. You can tell your system to do different things through multiple games, not only to define a specific state or model. You can run different games at different times


1.2 composition of playbooks

playbooks itself consists of the following parts

  1. Tasks: tasks, that is, organizing multiple operations to run in a playbook by calling an ansible template through task
  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


1.3 playbooks script example

1.3.1 modify the / etc/ansible/hosts host list first

[root@host103 ~]# vim /etc/ansible/hosts
...
#Add the host ip or host name (host name mapping) to the web servers group
[webservers]
192.168.23.105
....

1.3.2 write a script to install and start the httpd service

#The script name should end with. yml or. yaml
[root@host103 opt]# vim daemon1.yaml
---                          #Yaml file starts with three short horizontal bars --- to indicate that it is a yaml file. It can be omitted
- name: first palybook       # Defines the name of a play. It can be omitted
  gather_facts: false        #Set not to collect facts information. This can speed up execution. The default is true. It can be omitted
  hosts: webservers          #Specify the managed hosts to perform tasks. Multiple host groups are separated by colon:.
  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 defined by hosts
    - name: test connection  #Custom task name. It can be omitted. However, it is not recommended to omit it for troubleshooting
      ping:                  #Use the format of module: [options] to define tasks. The ping module is used here

    - name: disable selinux
      command: '/sbin/setenforce 0'    #command and shell modules do not need to use the mode of key=value. Quotation marks can be omitted
      #Ignore failed tasks. If the return value of the command is not 0, an error will be reported and playbooks will exit. Therefore, use this option to ignore failed tasks
      ignore_errors: true   

    - name: disable firewalld
      #Use the format of module: option s to define tasks. Options use the format of key=value
      service: name=firewalld state=stopped enabled=no

    - name: install apache
      yum: name=httpd state=latest

    - name: start apache service
      service: name=httpd state=started enabled=yes

    - name: modify httpd configuration file
      #The / opt/httpd.conf file needs to be prepared in advance
      copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf
      #Set the trigger. If the above operation is in the change state, the handlers operation of the corresponding name will be triggered through the name specified in notify
      notify: "restart httpd"

  #Tasks are defined in handlers
  handlers:
   #Set the task name. It should be the same as the task name specified in notify
    - name: restart httpd
      #Set the action to be executed. Here, the service module is used to restart httpd
      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.


1.3.3 prepare / opt/httpd.conf file

root@host103 opt]# vim httpd.conf
#Configure the listening port and domain name (normally use port 80)
42// Listen 8080
95// ServerName www.mynet.com:8080


1.4 execute the ploybooks script

Format:

Ansible playbook script name


Supplementary parameters:

-K (- ask pass): used to enter ssh password interactively

-K (- ask come pass): used to enter sudo password interactively
-u: Designated user

#The management host executes the playbooks script
[root@host103 opt]# ansible-playbook demo1.yaml

#Access test
[root@host105 ~]# firefox http://192.168.23.105:8080



1.5 check the yaml file and specify the task to start running

1.5.1 yaml file syntax check

#Check that the syntax of the yaml file is correct
[root@host103 opt]# ansible-playbook demo1.yaml --syntax-check

#Check task
[root@host103 opt]# ansible-playbook demo1.yaml --list-task

#Check valid hosts
[root@host103 opt]# ansible-playbook demo1.yaml --list-hosts


1.5.2 specify a task to run from

#Turn on the firewalld service of the 192.168.23.105 host
[root@host105 ~]# systemctl  start firewalld
[root@host105 ~]# systemctl  is-active firewalld
active
#192.168.23.105 stop httpd service and remove httpd
[root@host105 ~]# systemctl  stop httpd
[root@host105 ~]# yum -y remove httpd


#Check out the tasks first
[root@host103 opt]# ansible-playbook demo1.yaml --list-task
playbook: demo1.yaml

  play #1 (webservers): first palybook	TAGS: []
    tasks:
      test connection	TAGS: []
      disable selinux	TAGS: []
      disable firewalld	TAGS: []
      install apache	TAGS: []
      start apache service	TAGS: []
      modify httpd configuration file	TAGS: []

#Specify the task of installing Apache
[root@host103 opt]# ansible-playbook demo1.yaml  --start-at-task='install apache'


#At this point, the 192.168.23.105 host reinstalls httpd and starts the service
[root@host105 ~]# rpm -q httpd
httpd-2.4.6-67.el7.centos.x86_64
[root@host105 ~]# systemctl is-active  httpd
active

#Since the disale firewalld task precedes the install apache task, it is not executed
[root@host105 ~]# systemctl is-active  firewalld
active


2: Defining and referencing variables

2.1 defining variables

2.1.1 legal variable name

Before using a variable, it's best to know what the legal variable name is = =. Variable names can be letters, numbers and underscores. Variables should always start with letters==

"foo_port" is a legal variable name, and so is "foo5"

"Foo port", "foo port", "foo.port" and "12" are not legal variable names


2.1.2 format of variables defined in Playbook

vars can be used to define variables. Multiple variables should form a list. The format of variables is key: value

as

- hosts: dbservers
  vars:
    - groupname: mysql  #Define the variable groupname with the value of mysql
    - username: nginx   #Define the variable username with the value of nginx


2.2 using variables

Ansible allows you to use the Jinja2 template system to reference variables in the playbook. With Jinja, you can do many complex operations,

2.2.1 substitution of variables

#In a simple template, you can operate as follows, which is also the most basic form of variable replacement
My amp goes to {{ max_amp_value }}

#Replace in playbook:
template: src=foo.cfg.j2 dest={{ remote_install_path }}/foo.cfg

#In the above example, we use variables to determine where the file is placed 
#In the template, you will automatically get access to all variables within the host scope


2.3 yaml trap

Ansible uses "{{var}}" to reference variables. If a value starts with "{", YAML will consider it a dictionary, so we must reference it, such as foo: "{variable}}"

#Wrong example
- hosts: app_servers
  vars:
      app_path: {{ base_path }}/22
      
#Correct example
- hosts: app_servers
  vars:
       app_path: "{{ base_path }}/22"


2.4 information obtained using Facts

There are other places where you can get variables that are found automatically, not set by the user

Facts obtains the corresponding information by accessing the remote system. An example is the IP address or operating system of the remote host. Use the following command to view which information is available:

ansible hostname -m setup

[root@host103 opt]# ansible webservers -m setup
[root@host103 opt]# ansible webservers -m setup -a 'filter=*ipv4'


2.5 defining variables on the command line

On the command line, you can use - e to specify variables. But it will overwrite the variables in playbooks

[root@host103 opt]#ansible-playbook demo1 -e "username=nginx"


2.6 variables provided by ansible

Ansible will automatically provide you with some variables, even if you have not defined them. The important variables are = = 'hostvariables' and' Group '_ Names', and 'groups'. = = because these variable names are reserved, users should not overwrite them.' environmen t 'is also reserved

2.6.1 hostvars variable

hostvars allows you to access the variables of other hosts, including the facts obtained from which hosts. If you haven't accessed that host in the current playbook or any play of a group of playbooks, you can obtain the variables, but you can't see the facts value. If the database server wants to use a 'fact' value of another node, Or an inventory variable assigned to the node. It can be easily implemented in a template or even on the command line:

{{ hostvars['test.example.com']['ansible_distribution'] }}

2.6.2 groups variable

group_names is a list (array) of all groups where the current host is located. Therefore, Jinja2 syntax can be used to make changes in the template according to the group relationship (or role) of the host:

{% if 'webserver' in group_names %}
   # some part of a configuration file that only applies to webservers
{% endif %}

2.6.3 groups variable

Groups is a list of all groups (hosts) in the inventory. It can be used to enumerate all hosts in the group. For example:

{% for host in groups['app_servers'] %}
   # something that applies to all app servers.
{% endfor %}

A frequently used paradigm is to find all IP addresses in the group:

{% for host in groups['app_servers'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}


2.7 separation of variable files

It's a good idea to put the playbook under source control. When you may want to make the playbook source code public, you also want to keep some important variables private. Sometimes you also want to put some information in different files away from the main playbook file

You can use external variable files to implement:

---
- hosts: all
  remote_user: root
  vars:
    favcolor: blue
  vars_files:
    - /vars/external_vars.yml

  tasks:

  - name: this is just a placeholder
    command: /bin/echo foo

This ensures that you can isolate the risk of sensitive data when sharing playbook source code

The content of each variable file is a simple YAML file, as shown below:

---
# in the above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic


2.8 priority of variables

* extra vars (Use in the command line -e)Highest priority
* Then in inventory Connection variables defined in(such as ansible_ssh_user)
* Then there are most other variables(Command line conversion,play Variables in,included Variable of,role Variables in)
* Then in inventory Other variables defined
* Then it was discovered by the system facts
* And then "role Default variable", This is the default value,It's easy to lose priority


2.9 example of using playbook variable

[root@host103 opt]# vim demo2.yaml 
- name: second playbook
  #Start facts. The default value is true (or yes). If you want to close it, use false or no
  gather_facts: yes
  hosts: webservers
  remote_user: root
  #Define variables. groupname variable, the value is test; Username variable with the value zhangsan
  vars:
    - groupname: test
    - username: zhangsan
  tasks:
    - name: create group
      #Reference variable groupname
      group: name={{groupname}} system=yes gid=1024

    - name: create user for group
      #Reference variables username and groupname
      user: name={{username}} system=yes uid=9527 group={{groupname}}

    - name: test copy file
     #Reference variables from facts. However, facts must be on
     #ansible_defaule_ipv4 is one of the key s.
      copy: content="{{ansible_default_ipv4}}" dest=/opt/test.txt


#Execute script
[root@host103 opt]# ansible-playbook demo2.yaml


#Use the ansible setup module on 192.168.23.103 and filter the key value pair information
[root@host103 opt]# ansible webservers -m setup -a 'filter=ansible_default_ipv4'

#On the 192.168.23.105 host, check whether the zhangsan user is generated and whether the group is test
[root@host105 opt]# id zhangsan
#View / opt/test.txt
[root@host105 opt]# cat /opt/test.txt


3. Specify the sudo switching user of the remote host

---
- 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

If you need to specify the password when using sudo, you can add the option -- ask sudo pass (- K) when running the ansible playbook command. If the playbook is suspected to be suspended when using sudo, it may be stuck at sudo prompt. At this time, you can execute Control-C to kill the stuck task and run it again

When using sudo_ When user switches to a non root user, the parameters of the module will be temporarily written to a random temporary file in the / tmp directory. When the command is executed, the temporary file will be deleted immediately. This happens when ordinary users switch, such as switching from 'bob' to 'timmy', and switching to the root account, it will not happen, such as switching from 'bob' to 'root', If you don't want these data to be read (not writable) in a short time, please avoid in sudo_ Pass the unencrypted password in user. In other cases, the '/ tmp' directory is not used, which will not happen. Ansible also consciously does not record the password parameters in the log


4: 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

4.1 skip the host or let the qualified host perform the task

vim demo3.yaml
---
- hosts: all
  remote_user: root
  tasks:
   - name: reboot
     command: /usr/sbin/shutdown -r now
     #The variable name in the when directive does not need to be manually added with {}
     #The effect of this task is: when the host bit is 192.168.23.105, execute the / usr/sbin/shutdown -r now command to restart the host
     when: ansible_default_ipv4.address == "192.168.23.105"      
or 
     when: inventory_hostname == "<host name>"
	
	
ansible-playbook demo3.yaml


4.2 iteration

Ansible provides many kinds of loop structures, which are generally named with_items, which is equivalent to a loop loop.

[root@host103 opt]# vim demo4.yaml
---
- name: play4
  hosts: webservers
  gather_facts: false
  tasks:
    - name: create directories
      #Create a directory. Use with for directory name_ Loop in items
      file:
      #Since the value is {....}}, double quotation marks should be added to prevent it from being considered a dictionary
        path: "{{item}}"
        state: directory
      #with_ The items loop is equivalent to the loop loop  
      with_items:
        - /opt/zhangsan
        - /opt/lisi
    - name: add users
     #Use the loop to create users and add additional groups.
      user:
       #Both of the following methods can call with_ Values in iptems
        name: "{{item.name}}"
        groups: "{{item['test_groups']}}"
      
      with_items:
        #Both of the following methods are OK
        - name: test01
          test_groups: aaa
        - {name: test02, test_groups: bbb}                                         

#Running scripts on the hypervisor
[root@host103 opt]# ansible-playbook demo4.yaml 

#View the execution results on the managed host
[root@host105 opt]# ls 
lisi  zhangsan
[root@host105 opt]# id test01
uid=9528(test01) gid=9528(test01) group=9528(test01),2222(aaa)
[root@host105 opt]# id test02
uid=9529(test02) gid=9529(test02) group=9529(test02),3333(bbb


Five 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.

5.1 preparation of formwork

Prepare a template file with a. j2 suffix and set the referenced variables

[root@host103 opt]# cp httpd.conf httpd.conf.j2
[root@host103 opt]# vim httpd.conf.j2 
 #42 / / set the listening port as a variable. Reference variable http_ Value of port
 42// Listen {{http_port}}
 #95 / / set the domain name as the reference variable server_ Value of name
 95 ServerName {{server_name}}
 #119 / / set the website root directory to reference root_ Value of dir
 119// DocumentRoot "{{root_dir}}"
 #131 / / configure directory access permissions
 131// <Directory "{{root_dir}}">


5.2 modify the host list file

Modify the host list file and use the host variable to define a variable with the same variable name but different values

[root@host103 opt]# vim /etc/ansible/hosts

#Use host variables to define variables individually
[webservers]
192.168.23.105 http_port=192.168.23.105:80 server_name=www.mynet.com:80 root_dir=/opt/mynet

[dbservers]
192.168.23.106 http_port=192.168.23.106:8080 server_name=www.zhi.com:8080 root_dir=/opt/zhi


5.3 writing playbook

---
- name: for diff apache
  hosts: webservers dbservers
  remote_user: root
  vars:
    - Package: httpd
    - Service: httpd
    - mynet: /opt/mynet
    - zhi: /opt/zhi
  tasks:
    - name: install httpd
      yum: name={{Package}} state=latest

    - name: install configure file
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
      notify:
        - restart httpd

    - name: create root dir for mynet
      file: path={{mynet}} state=directory
      when: ansible_default_ipv4.address == "192.168.23.105"

    - name: for mynet index.html
      copy: content='this is mynet.com' dest={{mynet}}/index.html
      when: ansible_default_ipv4.address == "192.168.23.105"

    - name: create root dir for zhi
      file: path={{zhi}} state=directory
      when: ansible_default_ipv4.address == "192.168.23.106"

    - name: for zhi index.html
      copy: content='this is zhi.com' dest={{zhi}}/index.html
      when: ansible_default_ipv4.address == "192.168.23.106"

    - name: start httpd
      service: name={{Service}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{Service}} state=restarted
  
  
  
  [root@host103 opt]# ansible-playbook demo5.yaml

#Access test
[root@host103 opt]# curl http://192.168.23.105:80
this is mynet.com 

[root@host103 opt]# curl http://192.168.23.106:8080
this is zhi.com


6: tags module

You can define "tags" for one or some tasks in a playbook. When executing this playbook, you can run only 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 always is used as the task of tasks, no matter which task is executed, the tasks with always defined will be executed.

6.1 specify tags to execute

[root@host104 opt]# vim webhosts.yaml
---
- name: for test tags
  hosts: webservers
  remote_user: root
  tasks:
    - name: copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      #Using tags to set labels
      tags:
        - only
    - name: touch file
      file: path=/opt/testhost state=touch
 
#Use -- tags to specify the tag. 
[root@host104 opt]# ansible-playbook webhosts.yaml --tags="only"

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ciP4sjyg-1635247577641)(image-20211025111004200.png)]

#View on managed host
[root@host105 opt]# ls
hosts  


6.2 using the always tag

playbook also provides a special tags for always. The function is that when always is used as the task of tasks, no matter which task is executed, the tasks with always defined will be executed.

#First delete the replicated file hosts on the managed host
[root@host105 opt]# rm -rf hosts

[root@host104 opt]# vim webhosts.yaml
---
- name: for test tags
  hosts: webservers
  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
      #Add tags tagalways
      tags:
        - always
        
 #It is still executed with the specified label       
[root@host104 opt]# ansible-playbook webhosts.yaml --tags="only"


[root@host105 opt]# ls
hosts  testhost


7: role 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.

7.1 directory structure of roles

[root@host104 ansible]# cd /etc/ansible/
[root@host104 ansible]# tree roles/
#The first level directory created under roles is the role directory.
#The role directory needs to contain files, templates, tasks, handlers, vars, defaults and meta directories
roles/
├── web/
│   ├── files/
│   ├── templates/
│   ├── tasks/
│   ├── handlers/
│   ├── vars/
│   ├── defaults/
│   └── meta/
└── db/
    ├── files/
    ├── templates/
    ├── tasks/
    ├── handlers/
    ├── vars/
    ├── defaults/
    └── meta/


7.2 interpretation of roles directory

  • 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.


7.3 steps of using roles in a playbook

1 create a directory named roles

#The default installed using yum is
mkdir -p /etc/ansible/rules

2 create global variable directory (optional)

mkdir -p /etc/ansible/group_vars/ 
touch /etc/ansible/group_vars/all     #The file name is defined by itself. Pay attention when referencing

3 create directories named after each role in the roles directory, such as http 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 handlers, tasks, meta, defaults and vars directories 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


7.4 examples

1 create corresponding directories and files

[root@host104 ansible]# mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p[root@host104 ansible]# mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p[root@host104 ansible]# mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p


[root@host104 ansible]# touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
[root@host104 ansible]# touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
[root@host104 ansible]# touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml


[root@host104 ansible]# tree
.
├── ansible.cfg
├── hosts
└── roles
    ├── httpd
    │   ├── defaults
    │   │   └── main.yml
    │   ├── files
    │   ├── handlers
    │   │   └── main.yml
    │   ├── meta
    │   │   └── main.yml
    │   ├── tasks
    │   │   └── main.yml
    │   ├── templates
    │   └── vars
    │       └── main.yml
    ├── mysql
    │   ├── defaults
    │   │   └── main.yml
    │   ├── files
    │   ├── handlers
    │   │   └── main.yml
    │   ├── meta
    │   │   └── main.yml
    │   ├── tasks
    │   │   └── main.yml
    │   ├── templates
    │   └── vars
    │       └── main.yml
    └── php
        ├── defaults
        │   └── main.yml
        ├── files
        ├── handlers
        │   └── main.yml
        ├── meta
        │   └── main.yml
        ├── tasks
        │   └── main.yml
        ├── templates
        └── vars
            └── main.yml

25 directories, 17 files


2 write httpd module

#Write a simple tasks/main.yml
[root@host104 ansible]# vim /etc/ansible/roles/httpd/tasks/main.yml
- name: install apache
  yum: name={{pkg}} state=latest

- name: start apache
  service: name={{svc}} state=started enabled=yes

#Define variable: it can be defined in global variables or roles variables. Generally, it is defined in role variables
[root@host104 ansible]# vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd



3. Write mysql module

[root@host104 ansible]# vim /etc/ansible/roles/mysql/tasks/main.yml 
- name: install mysql
  yum: name={{pkg}} state=latest

- name: start mysql
  service: name={{svc}} state=started enabled=yes
  #Online sources are required. Therefore, the yum source for the backup is enabled
- name: remove yumrepo
  shell: move /etc/yum.repos.d/bak/* /etc/yum.repos.d/
  ignore_errors: yes
  
[root@host104 ansible]# vim /etc/ansible/roles/mysql/vars/main.yml
pkg:
  - mariadb
  - mariadb-server
svc: mariadb


4 write php module

[root@host104 ansible]# 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
  
  
  
 [root@host104 ansible]# vim /etc/ansible/roles/php/vars/main.yml
pkg:
  - php
  - php-fpm
svc: php-fpm




5 write roles example

[root@host104 ansible]# vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
   - httpd
   - mysql
   - php


[root@host104 ansible]# cd /etc/ansible
[root@host104 ansible]# ansible-playbook site.yml


#It can be viewed on the management host
[root@host105 yum.repos.d]# systemctl  is-active httpd
active
[root@host105 yum.repos.d]# systemctl  is-active mariadb
active
[root@host105 yum.repos.d]# systemctl  is-active php-fpm
active

/etc/yum.repos.d/
ignore_errors: yes

[root@host104 ansible]# vim /etc/ansible/roles/mysql/vars/main.yml
pkg:

  • mariadb
  • mariadb-server
    svc: mariadb
</font>

<br>

### 4 write php module

<font size=2>

```yaml
[root@host104 ansible]# 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
  
  
  
 [root@host104 ansible]# vim /etc/ansible/roles/php/vars/main.yml
pkg:
  - php
  - php-fpm
svc: php-fpm




5 write roles example

[root@host104 ansible]# vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
   - httpd
   - mysql
   - php


[root@host104 ansible]# cd /etc/ansible
[root@host104 ansible]# ansible-playbook site.yml

[external chain picture transferring... (img-3MT0HIXL-1635247577644)]


#It can be viewed on the management host
[root@host105 yum.repos.d]# systemctl  is-active httpd
active
[root@host105 yum.repos.d]# systemctl  is-active mariadb
active
[root@host105 yum.repos.d]# systemctl  is-active php-fpm
active

[external chain picture transferring... (IMG jncfscdy-1635247577645)]

Tags: Operation & Maintenance ansible server

Posted on Tue, 26 Oct 2021 06:45:29 -0400 by ozone