MindMap Gallery ansible mind map
Ansible tutorial, Ansible is a new automated operation and maintenance tool. It is developed based on Python. It integrates the advantages of many operation and maintenance tools (puppet, cfengine, chef, func, fabric) and realizes batch system configuration, batch program deployment, and batch running commands. and other functions.
Edited at 2024-03-04 22:22:28This is a mind map about bacteria, and its main contents include: overview, morphology, types, structure, reproduction, distribution, application, and expansion. The summary is comprehensive and meticulous, suitable as review materials.
This is a mind map about plant asexual reproduction, and its main contents include: concept, spore reproduction, vegetative reproduction, tissue culture, and buds. The summary is comprehensive and meticulous, suitable as review materials.
This is a mind map about the reproductive development of animals, and its main contents include: insects, frogs, birds, sexual reproduction, and asexual reproduction. The summary is comprehensive and meticulous, suitable as review materials.
This is a mind map about bacteria, and its main contents include: overview, morphology, types, structure, reproduction, distribution, application, and expansion. The summary is comprehensive and meticulous, suitable as review materials.
This is a mind map about plant asexual reproduction, and its main contents include: concept, spore reproduction, vegetative reproduction, tissue culture, and buds. The summary is comprehensive and meticulous, suitable as review materials.
This is a mind map about the reproductive development of animals, and its main contents include: insects, frogs, birds, sexual reproduction, and asexual reproduction. The summary is comprehensive and meticulous, suitable as review materials.
Ansible
1 Concept/terminology
Overview
Ansible is a new automated operation and maintenance tool. It is developed based on Python and integrates the advantages of many operation and maintenance tools (puppet, cfengine, chef, func, fabric) to realize functions such as batch system configuration, batch program deployment, and batch running of commands.
Features
Deployment is simple, you only need to deploy the Ansible environment on the main control side, and the controlled side does not need to do any operations.
By default, the SSH protocol is used to manage the device.
Master-slave centralized management
Simple configuration, powerful functions and strong scalability
Supports API and custom modules and can be easily expanded through Python
Customize powerful configuration and status management through Playbooks
It has good support for cloud computing platforms and big data.
document
Official documentation: https://docs.ansible.com/ansible/latest/
subtopic
GitHub address: https://github.com/ansible/ansible
2. Ansible architecture
Architecture diagram
composition
Core: ansible
Core Modules: These are the modules that come with ansible
Extension modules (Custom Modules): If the core module is not enough to complete a certain function, you can add extension modules
Plugins: Complete the supplement of module functions
Playbooks: ansible's task configuration file, which defines multiple tasks in the playbook and is automatically executed by ansible
Connection Plugins: Ansible connects to each host based on connection plug-ins. Although ansible uses ssh to connect to each host, it also supports other connection methods, so a connection plug-in is required.
Host Inventory: Defines the hosts managed by ansible
3. How Ansible works
Working principle diagram
The management end supports three methods of connecting to the managed end: local, ssh, and zeromq. The default connection is based on ssh. This part corresponds to the connection module in the architecture diagram above;
The Host Inventory can be classified by application type, etc. The management node implements corresponding operations through various modules. The batch execution of a single module and a single command can be called ad-hoc;
The management node can use playbooks to implement a collection of multiple tasks to implement a type of functions, such as the installation and deployment of web services, batch backup of database servers, etc. We can simply understand playbooks as configuration files that the system operates by combining multiple ad-hoc operations.
9. Ad-Hoc (point-to-point mode)
Official documentation: https://docs.ansible.com/ansible/latest/command_guide/intro_adhoc.html
1 Introduction
The ad-hoc command is a command that can be entered quickly and does not need to be saved. It is generally used during testing and debugging. In short, ad-hoc is a "temporary command".
2) Commonly used modules
1. command module (default module)
The default module is not as powerful as the shell. Basically, the shell module can support the functions of the command module.
【1】Help
ansible-doc command # It is recommended to use the following ansible-doc command -s
【2】Parameter explanation
free_form
Required parameter, specify the command that needs to be executed remotely. It should be noted that the free_form parameter is not the same as other parameters (if you want to use a parameter, you need to assign a value to this parameter, that is, name=value mode). For example, when we want to execute the ls command on the remote host, we do not need to write "free_form=ls". This is wrong because there is no parameter named free_form. When we want to execute the ls command on the remote host, When executing the ls command in , just write ls directly. Because the function of the command module is to execute commands, any command that can be executed on the remote host can be called free_form.
chdir
The function of this parameter is to specify a directory. Before executing the corresponding command, it will first enter the directory specified by the chdir parameter.
creates
When you see creates, you may understand this parameter literally, but using this parameter will not help us create files. Its function is to not execute the corresponding command when the specified file exists. For example, if /testdir/test If the file exists, the command we specified will not be executed.
removes
It is exactly the opposite of the creates parameter. Its function is that when the specified file does not exist, the corresponding command will not be executed. For example, if the /testdir/tests file does not exist, the command we specified will not be executed. This parameter will not Help us delete files.
【3】Example demonstration
# The above command means executing the ls command on the web host. Because the root user is used, by default, the result of ls is the file list in the root user's home directory on the web host. ansible web -m command -a "ls" # The chdir parameter means that before executing the command, the specified directory will be entered first, so the above command means to check the file list in the /testdir directory on the web host, and the returned display shows that there are 2 files. ansible web -m command -a "chdir=/testdir ls" # The following command indicates that the /testdir/testfile1 file exists in the remote host, and the corresponding command will not be executed. /testdir/testfile3 does not exist before executing the "echo test" command. ansible web -m command -a "creates=/testdir/testfile1 echo test" # The following command indicates that the /testdir/testfile3 file does not exist on the remote host, and the corresponding command will not be executed. /testdir/testfile1 Execute the "echo test" command only. ansible web -m command -a "removes=/testdir/testfile1 echo test"
2. shell module
shell module [execute shell/python and other scripts on the remote host].
【1】View help
ansible-doc shell -s
【2】Example demonstration
# -o: Display in one line # Install httpd ansible web -m shell -a 'yum -y install httpd' -o # Check the time ansible web -m shell -a 'uptime' -o
3. script module
script module [execute shell/python and other scripts on the remote host on the remote host].
【1】View help
ansible-doc script -s
【2】Parameter explanation
free_form
A required parameter that specifies the script that needs to be executed. The script is located locally on the ansible management host. There is no specific parameter named free_form. For detailed explanation, please refer to the command module.
chdir
The function of this parameter is to specify a directory in the remote host. Before executing the corresponding script, it will first enter the directory specified by the chdir parameter.
creates
Use this parameter to specify a file in the remote host. When the specified file exists, the corresponding script will not be executed. Please refer to the explanation in the command module.
removes
Use this parameter to specify a file in the remote host. When the specified file does not exist, the corresponding script will not be executed. Please refer to the explanation in the command module.
【3】Example demonstration
# The following command indicates that the /testdir/testscript.sh script in the ansible host will be executed in the web host. Before executing this script, it will first enter the /opt directory in the web host. ansible web -m script -a "chdir=/opt /testdir/testscript.sh" # The following command indicates that the /testdir/testfile1 file in the web host already exists, and the /testdir/testscript.sh script in the ansible host will not be executed in the web host. ansible web -m script -a "creates=/testdir/testfile1 /testdir/testscript.sh" # The following command indicates that the /testdir/testfile1 file in the web host exists, and the /testdir/testscript.sh script in the ansible host will be executed in the web host. ansible ansible-demo3 -m script -a "removes=/testdir/testfile1 /testdir/testscript.sh"
4. raw module
raw module [similar to command module, supports pipeline transfer].
【1】View help
ansible-doc raw -s
【2】Example demonstration
ansible web -m raw -a "ifconfig eth0 |sed -n 2p |awk '{print \$2}' |awk -F: '{print \$2}'"
5. copy module
The copy module copies files from the master to the slave.
【1】View help
ansible-doc copy -s
【2】Example demonstration
# -a,--args: followed by parameters ansible web -m copy -a 'src=/etc/ansible/hosts dest=/tmp/hosts owner=root group=bin mode=777' # backup=yes/no: Whether to back up the file if it exists and the file content is different. The default is not to back up. ansible web -m copy -a 'src=/etc/ansible/hosts dest=/tmp/hosts owner=root group=bin mode=777 backup=yes'
6. fetch module
The copy module copies files from the controlled terminal to the master terminal, which is exactly the opposite of copy.
【1】View help
ansible-doc fetch -s
【2】Example demonstration
# Similar to the parameters supported by copy, src: the directory of the remote host, dest: the directory of the main control end. In fact, the actual storage directory is: /tmp/192.168.182.129/tmp/up.sh, which will be stored in groups according to each host. # This `must' be a file, not a directory: only supports single file acquisition ansible 192.168.182.129 -m fetch -a "src=/etc/fstab dest=/testdir/ansible/"
7. unarchive module (unpack module)
The unarchive module is the unpacking module.
【1】View help
ansible-doc unarchive -s
【2】Parameter explanation
copy
The default is yes. When copy=yes, the copied file is copied from the ansible host to the remote host. If set to copy=no, the src source file will be searched for on the remote host.
src
The source path can be the path on the ansible host or the path on the remote host. If it is the path on the remote host, you need to set copy=no.
dest
The destination path on the remote host.
mode
Set the decompressed file permissions.
【3】Example demonstration
ansible 192.168.182.129 -m unarchive -a 'src=/testdir/ansible/data.tar.gz dest=/tmp/tmp/'
8. Archive module (packaging module)
The unarchive module is a packaged module.
【1】View help
ansible-doc archive -s
【2】Example demonstration
9. user module
【1】View help
ansible-doc user -s
【2】Example demonstration
#Create user (present: default, can be omitted) ansible web -m user -a 'name=test state=present' # Delete user (absent) ansible web -m user -a 'name=test state=absent' # change Password # Step 1. Generate encrypted password echo '777777'|openssl passwd -1 -stdin # Step 2. Modify secret ansible web -m user -a 'name=test password="$1$Jo5FD9Jr$2QB.BuybbtR35ga4O5o8N."' #Modify shell ansible web -m user -a 'name=test shell=/sbin/noglogin append=yes'
10. group module
【1】View help
ansible-doc group -s
【2】Example demonstration
# Create ansible 192.168.182.129 -m group -a 'name=testgroup system=yes' # delete ansible 192.168.182.129 -m group -a 'name=testgroup state=absent'
11. yum module
【1】View help
ansible-doc yum -s
【2】Example demonstration
#Upgrade all packages ansible web -m yum -a 'name="*" state=latest' # Install apache ansible web -m yum -a 'name="httpd" state=latest'
12. service module
【1】View help
ansible-doc service -s
【2】Example demonstration
ansible web -m service -a 'name=httpd state=started' ansible web -m service -a 'name=httpd state=started enabled=yes' ansible web -m service -a 'name=httpd state=stopped' ansible web -m service -a 'name=httpd state=restarted' ansible web -m service -a 'name=httpd state=started enabled=no'
13. file module
【1】View help
ansible-doc file -s
【2】Example demonstration
# Create a file ansible web -m file -a 'path=/tmp/88.txt mode=777 state=touch' # Create a directory ansible web -m file -a 'path=/tmp/99 mode=777 state=directory' # delete ansible web -m file -a 'path=/tmp/99 state=absent'
14. setup module
【1】View help
ansible-doc setup -s
【2】Example demonstration
ansible web -m setup ansible web -m setup -a 'filter=ansible_all_ipv4_addresses'
15. cron module
【1】View help
ansible-doc cron -s
【2】Example demonstration
#Create a scheduled task ansible 192.168.182.129 -m cron -a 'minute=* weekday=1,3,5,6,7 job="/usr/bin/wall FBI warning" name=warningcron' # Close scheduled tasks ansible 192.168.182.129 -m cron -a 'disabled=true job="/usr/bin/wall FBI warning" name=warningcron' # Delete scheduled tasks ansible 192.168.182.129 -m cron -a ' job="/usr/bin/wall FBI warning" name=warningcron state=absent'
16. hostname module
【1】View help
ansible-doc hostname -s
【2】Example demonstration
ansible 192.168.182.129 -m hostname -a 'name=192.168.182.129'
Eight Host Inventory (host list)
Host inventory configuration (default configuration file: /etc/ansible/hosts)
1) Add managed nodes
192.168.182.110
Example:
# -m: Specify module # -a: Specify parameters ansible 192.168.182.110 -m ping ansible 192.168.182.110 -m shell -a "df -h"
sample graph
2) Configure host group
#Define webservers group [webservers] 192.168.182.110 192.168.182.112
Example:
# -m: Specify module # -a: Specify parameters ansible webservers -m ping ansible webservers -m shell -a "df -h"
picture
3) Configure the connection username and password
[webservers] 192.168.182.130 ansible_ssh_user=root ansible_ssh_pass=123456
Common configuration parameters
Example:
ansible 192.168.182.130 -m ping
picture
4) Subgroup
[web] 192.168.182.130 192.168.182.110 [mysql] 192.168.182.111 # Subgroup [nfs:children] web mysql # Define variables uniformly for groups [nfs:vars] ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22
Example:
ansible nfs -m ping # -o: Display in one line ansible nfs -m ping -o
picture
5) Custom host list file
cat>hostlist<<EOF [web] 192.168.182.130 192.168.182.110 [mysql] 192.168.182.111 # Subgroup [nfs:children] web mysql # Define variables uniformly for groups [nfs:vars] ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22 EOF
Example:
# -i: Specify host list file ansible -i hostlist nfs -m ping
picture
Seven Ansible ways to connect to the controlled terminal
1) ssh key
# Generate secret key ssh-keygen # Copy the secret key to the managed server ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22 root@192.168.182.130
2) Account password
1. Command line configuration
# -k: interactive ansible -uroot -k 192.168.182.130 -m ping
2. Configure in the configuration file
#Default host configuration file: /etc/ansible/hosts 192.168.182.130 ansible_ssh_user=root ansible_ssh_pass=123456 [web] 192.168.182.130 ansible_ssh_user=root ansible_ssh_pass=123456
Commonly used configuration parameters
Six main components
1) ansible command execution source
USER, ordinary user, that is, system administrator
USER -> ansile playbook -> ansible
CMDB, (Configuration Management Database) API call
PUBLIC/PRVATE CLOUD API calls
2) ansible management method
Ad-Hoc, the ansible command, is mainly used in temporary command usage scenarios
Ansible-playbook is mainly used in long-term planning and large-scale project scenarios, which require prerequisite planning. ansible-playbook (script) execution process: Write the already arranged task set into ansible-playbook Split the task set into one-by-one ansible commands through the ansible-playbook command, and execute them one by one according to predetermined rules.
3) ansible main operation objects
HOSTS: host
NETWORKING: Network equipment
Precautions:
The host that executes ansible is generally called the main control terminal, central control, master or bastion host.
The python version of the main control terminal needs to be 2.6 or above
If the python version of the controlled terminal is less than 2.4, you need to install python-simplejson.
If SELinux is enabled on the controlled terminal, libselinux-python needs to be installed.
Windows cannot be used as the host computer
Five Seven Commandments
Overview
After installing ansible, we found that ansible provides us with a total of seven instructions: ansible, ansible-doc, ansible-galaxy, ansible-lint, ansible-playbook, ansible-pull, and ansible-vault. Here we only look at the usage part, and the detailed part can be obtained through the "command -h" method.
1) ansible
ansible is the core part of the command, which is mainly used to execute ad-hoc commands, that is, a single command. By default, the host and options parts need to be followed. When the module is not specified by default, the command module is used. However, the module used by default can be modified in /etc/ansible/ansible.cfg #module_name = command.
ansible 192.168.182.130 -a 'date'
2) ansible-doc
This command is used to view module information. Commonly used parameters include -l and -s.
#List all installed modules ansible-doc -l ansible-doc -l #View the usage of a specific module, here is an example of viewing the command module ansible-doc -s command
3) ansible-playbook
The ansible-playbook command is the most commonly used command. It reads the playbook file and then performs corresponding actions. This will be discussed later.
4) ansible-galaxy
The ansible-galaxy command is used to conveniently download third-party extension modules from the https://galaxy.ansible.com/ site. We can visually understand that it is similar to yum under centos, pip or easy_install under python.
ansible-galaxy install aeriscloud.docker
5) ansible-lint
ansible-lint is a tool for checking the syntax of playbooks. Usage is as follows:
ansible-lint playbook.yml
6) ansible-pull
The use of this instruction requires another mode of Ansible, the pull mode, which is exactly the opposite of the push mode we usually use. It is suitable for the following scenarios: you have a huge number of machines to configure, even if you use a very high number of threads, the It takes a lot of time; you have to run Anisble on a machine that doesn't have a network connection, such as installing it after booting.
7) ansible-vault
ansible-vault is mainly used when the configuration file contains sensitive information and you don’t want it to be seen. Vault can help you encrypt/decrypt the configuration file, which is an advanced usage.
Mainly when it comes to configuring passwords or other variables in playbooks, you can use this command to encrypt. In this way, what we see through cat will be a password string file. When editing, you need to enter a preset password to open it.
When executing this kind of playbook file, you need to add the --ask-vault-pass parameter, and you also need to enter a password before it can be executed normally.
4. Installation and basic configuration
Install
yum install epel-release
yum -y install ansible
ansible --version
Execution diagram
Configuration
1) Turn on logging
Configuration file: /etc/ansible/ansible.cfg
# Remove the leading '#' sign #log_path = /var/log/ansible.log ==> log_path = /var/log/ansible.log
2) Remove the first connection ssh ask confirmation
# The first type (recommended) vi /etc/ansible/ansible.cfg # Actually just remove the # # host_key_checking = False ==> host_key_checking = False # The second type vi /etc/ssh/ssh_config StrictHostKeyChecking ask ==> StrictHostKeyChecking no
Execution diagram
playbook
I. Overview
Compared with ad-hoc, playbook is a completely different way of using ansible, similar to saltstack's state file. Ad-hoc cannot be used permanently, playbook can be used permanently.
A playbook is a list consisting of one or more plays. The main function of a play is to dress the hosts that have been previously grouped into a group into roles that have been defined through tasks in ansible.
Fundamentally speaking, the so-called task is nothing more than a module that calls ansible. Organizing multiple plays into a playbook allows them to be combined to complete a certain task according to a pre-arranged mechanism.
Reference documentation: https://ansible-tran.readthedocs.io/en/latest/docs/playbooks.html
Basic introduction to Ansible and environment deployment
picture
2. Core elements
Hosts
List of remote hosts executed
Tasks
task set
Varniables
Built-in variables or custom variables are called in the playbook
Templates
Template, that is, a file using template syntax, such as a configuration file, etc.
Handlers
Used in combination with notity, operations triggered by specific conditions will be executed only when the conditions are met, otherwise they will not be executed.
Tags
Tags specify a certain task to be executed and are used to select and run part of the code in the playbook.
3. Grammar
playbook syntax (yaml)
The playbook uses the yaml syntax format, and the suffix can be yaml or yml.
YAML ( /ˈjæməl/ ) references a variety of other languages, including: XML, C, Python, Perl, and the email format RFC2822, which was first published by Clark Evans in May 2001, and by Ingy döt Net and Oren Ben -Kiki is also the co-designer of this language.
YAML format is a JSON-like file format. YAML is used for file configuration writing, and JSON is mostly used for development and design.
1) Introduction to YAML
1. YAML format is as follows
The first line of the file should start with "---" (three hyphens), indicating the beginning of the YAML file.
In the same line, what follows # indicates a comment, similar to shell, python and ruby.
List elements in YAML begin with "-" and are followed by a space. What follows is the element content.
Elements in the same list should maintain the same indentation, otherwise it will be treated as an error.
Objects such as hosts, variables, roles, and tasks in play are represented by key values separated by ":", and a space must be added after the ":".
2. Explanation of playbooks yaml configuration file
Hosts: target host to run the specified task remote_user: The user who performs tasks on the remote host; sudo_user: tasks: task list The specific format of tasks: tasks: - name: TASK_NAME module: arguments notify: HANDLER_NAME handlers: - name: HANDLER_NAME module: arguments ##Module, module parameters: The format is as follows: (1) action: module arguments (2) module: arguments Note: Add the command directly after the shell and command modules, instead of the parameter list of key=value class. handlers: tasks, triggered under specific conditions; triggered when receiving notifications from other tasks;
3. Example
--- - hosts: web remote_user: root tasks: - name: install nginx ##To install the module, you need to add the source of nginx to the controlled host yum: name=nginx state=present - name: copy nginx.conf ##Copy the nginx configuration file. You need to edit nginx.conf in the /tmp directory of the local machine. copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf backup=yes notify: reload #When nginx.conf changes, notify the corresponding handlers tags: reloadnginx #tag - name: start nginx service #Service startup module service: name=nginx state=started tags: startnginx #tag handlers: - name: reload service: name=nginx state=restarted
2) variables variables
variablesThere are four ways to define variables. as follows:
1. facts: can be called directly
There is a setup module in ansible. This module is implemented through the facts component. It is mainly system information of the node itself, bios information, network, hard disk and other information. The variables here can also directly call the facts of the facts component. We can use the setup module to obtain them, and then put them directly into our script to call them.
ansible web -m setup
picture
Several commonly used parameters
ansible_all_ipv4_addresses # All addresses of ipv4 ansible_all_ipv6_addresses # All addresses of ipv6 ansible_date_time # Get the control node time ansible_default_ipv4 #Default ipv4 address ansible_distribution # system ansible_distribution_major_version # Major version of the system ansible_distribution_version # System version number ansible_domain #The domain where the system is located ansible_env #System environment variables ansible_hostname #The host name of the system ansible_fqdn #Full name of the system ansible_machine #System architecture ansible_memory_mb #System memory information ansible_os_family # System family ansible_pkg_mgr # System package management tool ansible_processor_cores #The number of cores of the system’s CPU (each) ansible_processor_count #The number of system CPUs ansible_processor_vcpus #The total number of system CPUs = the number of CPUs * the number of CPU cores ansible_python # python on the system
search
ansible web -m setup -a 'filter=*processor*'
picture
2. User-defined variables
There are two ways to customize variables
1. Pass in through the command line
-e VARS, --extra-vars VARS in the ansible-playbook command line, so that custom variables can be passed in directly
Use playbook to define variables. Examples are as follows:
--- - hosts: web remote_user: root tasks: - name: install {{ rpmname }} yum: name={{ rpmname }} state=present - name: copy {{ rpmname }}.conf copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes notify: reload tags: reload{{ rpmname }} - name: start {{ rpmname }} service service: name={{ rpmname }} state=started tags: start{{ rpmname }} handlers: - name: reload service: name={{ rpmname }} state=restarted
use:
ansible-playbook nginx.yml -e rpmname=keepalived ansible-playbook nginx.yml --extra-vars rpmname=keepalived
2. Define variables in the playbook
##Define variables in the playbook as follows: vars: - var1: value1 - var2: value2
use:
--- - hosts: web remote_user: root vars: - rpmname: keepalived tasks: - name: install {{ rpmname }} yum: name={{ rpmname }} state=present - name: copy {{ rpmname }}.conf copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes notify: reload tags: reload{{ rpmname }} - name: start {{ rpmname }} service service: name={{ rpmname }} state=started tags: start{{ rpmname }} handlers: - name: reload service: name={{ rpmname }} state=restarted
3. Pass variables through roles
4. Host Inventory
This can be defined in the host manifest as follows:
#Pass different variables to different hosts IP/HOSTNAME varaiable=value var2=value2 #Pass the same variables to hosts in the group [groupname:vars] variable=value
3) Process control
1. Conditional judgment expressed by when
- hosts: web remote_user: root# stands for execution as root user. The default is root and can be omitted. tasks: - name: createfile copy: content="test3" dest=/opt/p1.yml when: a=='3' - name: createfile copy: content="test4" dest=/opt/p1.yml when: a=='4'
If a"3", write "test3" into /opt/p1.yml of the managed machine under the web group. If a is "4", write "test4" into /opt/p1.yml of the managed machine under the web group.
implement
# Grammar check ansible-playbook --syntax-check p1.yml #implement ansible-playbook -e 'a="3"' p1.yml
2. Label (only execute one task in the configuration file)
- hosts: web tasks: - name: installnginx yum: name=nginx - name: copyfile copy: src=/etc/nginx/nginx.conf dest=/etc/nginx/nginx.conf tags: copyfile - name: start service: name=nginx static=restarted
implement
# Grammar check ansible-playbook --syntax-check p2.yml #implement ansible-playbook -t copyfile p2.yml
3. Loop with_items
Create three users
- hosts: web tasks: - name: createruser user: name={{ item }} with_items: -shy1 -shy2 -shy3 - name: creategroup group: name={{ item }} with_items: - group1 - group2 - group3
implement
#Grammar check ansible-playbook --syntax-check p3.yml #implement ansible-playbook p3.yml
4. Loop nesting (dictionary)
The group belonging to user shy1 is group1, the group belonging to user shy2 is group2, and the group belonging to user shy3 is group3.
- hosts: web tasks: - name: creategroup group: name={{item}} with_items: - group3 - group4 - group5 - name: createuser user: name={{item.user}} group={{item.group}} with_items: - {'user': shy3,'group': group3} - {'user': shy4,'group': group4} - {'user': shy5,'group': group5}
implement
#Grammar check ansible-playbook --syntax-check p4.yml #implement ansible-playbook p4.yml
4) templates
definition
A template is a text file with nested scripts (written using a template programming language)
Jinja2 is a template language for python, based on Django's template language.
This template supports:
String: use single or double quotes; Number: integer, floating point number; List: [item1, item2, ...] Tuple: (item1, item2, ...) Dictionary: {key1:value1, key2:value2, ...} Boolean type: true/false Arithmetic operations: , -, *, /, //, %, ** Comparison operation: ==, !=, >, >=, <, <= logic operation: and, or, not
Usually templates are used by referencing variables.
Example
1. Define the template
user nginx; #Set the system user for nginx service worker_processes {{ ansible_processor_vcpus }}; #Number of worker processes error_log /var/log/nginx/error.log warn; #nginx error log pid /var/run/nginx.pid; #pid when nginx starts events { worker_connections 1024; #Maximum number of connections allowed per process } http { #http request configuration, one http can contain multiple servers #Define Content-Type include /etc/nginx/mime.types; default_type application/octet-stream; #Log format Here main corresponds to main in access_log #$remote_addr: client address #$remote_user: The user name used by the http client to request nginx authentication. The authentication module is not enabled by default and will not be recorded. #$timelocal: nginx time #$request: request method routing http protocol version #status: http response status code #body_bytes_sent: size of response body #$http_referer: referer header information parameter, indicating the upper-level page #$http_user_agent: user-agent header information parameters, client information #$http_x_forwarded_for:x-forwarded-for header information parameters log_format main '$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #Access log, the following main means using the main format in log_format to record to access.log access_log /var/log/nginx/access.log main; One of the major advantages of #nginx is high-efficiency file transfer sendfile on; #tcp_nopush on; #Timeout time between client and server, in seconds keepalive_timeout 65; #gzip on; server { #http service, one server can configure multiple locations listen {{ nginxport }}; #Service listening port server_name localhost; #Host name, domain name #charset koi8-r; #access_log /var/log/nginx/host.access.log main; location/{ root /usr/share/nginx/html; #Page storage directory index index.html index.htm; #Default page } #error_page 404 /404.html; # Redirect the 500 502 503 504 error page to /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { #Match the page path specified by error_page root /usr/share/nginx/html; #Directory where the page is stored } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #roothtml; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; #include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } include /etc/nginx/conf.d/*.conf; }
2. Define yaml arrangement
--- - hosts: web remote_user: root vars: - rpmname: nginx - nginxport: 8088 tasks: - name: install {{ rpmname }} yum: name={{ rpmname }} state=present - name: copy {{ rpmname }}.conf copy: src=/tmp/{{ rpmname }}.conf dest=/etc/{{ rpmname }}/{{ rpmname }}.conf backup=yes notify: reload tags: reload{{ rpmname }} - name: start {{ rpmname }} service service: name={{ rpmname }} state=started tags: start{{ rpmname }} handlers: - name: reload service: name={{ rpmname }} state=restarted
use
##Use the reloadnginx tag to reload the script ansible-playbook nginx.yml -t reloadnginx
The difference between copy and template
The copy module does not replace parameters, and the template module replaces parameters.
The parameters of template are almost identical to those of copy
5) handlers (trigger events)
notify: trigger handlers: triggered actions
Usage scenario: When modifying the configuration file
[Example] Handlers will not be executed under normal circumstances.
- hosts: web tasks: - name: installredis yum: name=redis - name: copyfile template: src=redis.conf dest=/etc/redis.conf tags: copyfile notify: restart - name: start service: name=redis state=started handlers: - name: restart service: name=redis
implement
ansible-playbook -t copyfile p6.yml
6)roles
1. Introduction and advantages of roles
Generally, roles are written in /etc/ansible/roles, or they can be written in any other location (if written in other locations, you must manually create a roles folder yourself)
One disadvantage of all the above methods is that it is impossible to deploy different services such as web, database, keepalived, etc. at the same time, or to combine different applications with different servers, you need to write multiple yaml files, which makes it difficult to achieve flexible calls.
Roles are used to organize playbooks hierarchically and structurally. Roles can automatically load variable files, tasks, handlers, etc. based on hierarchical results.
To use roles, you only need to use the include directive in the playbook.
To put it simply, roles are a way of placing variables (vars), files (files), tasks (tasks), modules (modules) and handlers (handlers) in separate directories, and can easily include them. mechanism.
Roles are generally used in scenarios where services are built based on hosts, but they can also be used in scenarios such as building daemons.
2. Directory structure
Create a directory
mkdir -pv ./{nginx,mysql,httpd}/{files,templates,vars,tasks,handlers,meta,default}
picture
roles/
mysql/: yml file of mysql service
httpd/: yml file of apached service
nginx/: yml file of nginx service
files/: stores files or scripts called by modules such as copy or script;
tasks/: There should be at least one file named main.yml in this directory, which is used to define each task; other files need to be included and called by main.yml;
handlers/: There should be at least one file named main.yml in this directory, which is used to define each handler; other files need to be included and called by main.yml;
vars/: This directory should have at least one file named main, yml, which is used to define each variable; other files need to be included and called by main.yml;
templates/: stores template files called by the templates module;
meta/: There should be at least one file named main.yml in this directory, which defines the special settings and dependencies of the current role. Other files need to be included and called by main.yml;
default/: This directory should have at least one file named main.yml, which is used to set default variables;
3. Practical operations
【1】Create directory
mkdir -pv ./{nginx,mysql,httpd}/{files,templates,vars,tasks,handlers,meta,default}
【2】Define configuration file
First download the nginx rpm deployment package
# Download address: http://nginx.org/packages/centos/7/x86_64/RPMS/ wget http://nginx.org/packages/centos/7/x86_64/RPMS/nginx-1.18.0-1.el7.ngx.x86_64.rpm -O nginx/files/nginx-1.18.0-1.el7. ngx.x86_64.rpm
nginx/tasks/main.yml
- name: cp copy: src=nginx-1.18.0-1.el7.ngx.x86_64.rpm dest=/tmp/nginx-1.18.0-1.el7.ngx.x86_64.rpm - name: install yum: name=/tmp/nginx-1.18.0-1.el7.ngx.x86_64.rpm state=latest - name: conf template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf tags: nginxconf notify: new conf to reload - name: start service service: name=nginx state=started enabled=true
nginx/templates/nginx.conf.j2
user nginx; #Set the system user for nginx service worker_processes {{ ansible_processor_vcpus }}; #Number of worker processes error_log /var/log/nginx/error.log warn; #nginx error log pid /var/run/nginx.pid; #pid when nginx starts events { worker_connections 1024; #Maximum number of connections allowed per process } http { #http request configuration, one http can contain multiple servers #Define Content-Type include /etc/nginx/mime.types; default_type application/octet-stream; #Log format Here main corresponds to main in access_log #$remote_addr: client address #$remote_user: The user name used by the http client to request nginx authentication. The authentication module is not enabled by default and will not be recorded. #$timelocal: nginx time #$request: request method routing http protocol version #status: http response status code #body_bytes_sent: size of response body #$http_referer: referer header information parameter, indicating the upper-level page #$http_user_agent: user-agent header information parameters, client information #$http_x_forwarded_for:x-forwarded-for header information parameters log_format main '$http_user_agent' '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #Access log, the following main means using the main format in log_format to record to access.log access_log /var/log/nginx/access.log main; One of the major advantages of #nginx is high-efficiency file transfer sendfile on; #tcp_nopush on; #Timeout time between client and server, in seconds keepalive_timeout 65; #gzip on; server { #http service, one server can configure multiple locations listen {{ nginxport }}; #Service listening port server_name localhost; #Host name, domain name #charset koi8-r; #access_log /var/log/nginx/host.access.log main; location/{ root /usr/share/nginx/html; #Page storage directory index index.html index.htm; #Default page } #error_page 404 /404.html; # Redirect the 500 502 503 504 error page to /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { #Match the page path specified by error_page root /usr/share/nginx/html; #Directory where the page is stored } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #roothtml; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; #include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } include /etc/nginx/conf.d/*.conf; }
nginx/vars/main.yml
nginxport: 9999
nginx/handlers/main.yml
- name: new conf to reload service: name=nginx state=restarted
Define script file (roles.yml)
- hosts: web remote_user: root roles: - nginx
The final directory structure is as follows:
picture
implement
ansible-playbook roles.yml
Execution diagram