当前位置:网站首页>Ansible playbook and variable (II)
Ansible playbook and variable (II)
2022-06-12 21:51:00 【Stay up late and soak wolfberry】
List of articles
1. PlayBook First time to know
PlayBook namely ” Script ”
play: It defines the role of the host .( Leading role or supporting role , Which star are you looking for )
task: What is defined is the specific tasks to be performed .( The lines and actions of the characters )
playbook: By one or more play( role ) form , One play( role ) It can contain more than one task( Lines , action , What do big shots do in each episode ).
It is simply understood as : Using different modules to do one thing
stay Ansible in ” Script file ” In order to yml Final document .
stay SaltStack in ” Script file ” In order to sls Final document .
But grammar , All of them are yaml grammar

1.PlayBook Functional ratio ad-hoc More complete , It's right ad-hoc An arrangement of .
2.PlayBook Can well control the sequence of execution , And dependency .
3.PlayBook Grammar is more intuitive .
4.playbook It can be used for a long time ,ad-hoc Can't last .
YUML grammar :
grammar describe
Indent YAML Use a fixed indentation style to represent hierarchy , Each indentation consists of two spaces , Out of commission TAB
The colon Except those ending with a colon , All other colons must be followed by spaces
Dash line Represents a list item , Use a short bar with a space , Multiple items use the same indentation level as the same list
yum:
name: vsftpd
state: present
yum:
name:
- httpd
- nginx
- php-fpm
state: present
Check grammar :
ansible-playbook --syntax-check p1
Perform drill :
ansible-playbook -C p1.yml
Real execution :
ansible-playbook p1.yml
Sometimes the simulation will fail , But when it comes to real implementation, it is successful
2. PlayBook Deploy httpd practice
(1)host detailed list :
[[email protected] ~]# vim /etc/ansible/hosts
[web_group]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8
(2) The script is as follows :
- hosts: web_group
# install httpd
tasks:
- name: Install httpd Server
yum:
name: httpd
state: present
# Configure the website
- name: Config Httpd Server
copy:
content: oldboy_web_page
dest: /var/www/html/index.html
# start-up httpd
- name: Start Httpd Server
systemd:
name: httpd
state: started
enabled: yes
# Start the firewall
- name: Start Firewalld Server
systemd:
name: firewalld
state: started
enabled: yes
# Turn on the firewall 80 port
- name: Config Firewalld Server
firewalld:
service: http
immediate: yes
permanent: yes
state: enabled
3. PlayBook actual combat
Practice one :
detailed list hosts as follows :
[server]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8
[client]
backup ansible_ssh_host=10.0.0.41
The specific script is :
- hosts: all
tasks:
- name: Install rsync
yum:
name: rsync
state: present
- hosts: server
tasks:
- name: create group www
group:
name: www
gid: 666
- name: create user www
user:
name: www
uid: 666
group: www
create_home: false
shell: /sbin/nologin
- name: Create Directory
file:
path: /backup
owner: www
group: www
recurse: yes
- name: configure rsync
copy:
src: ./rsyncd.conf
dest: /etc/
- name: configure passwd
copy:
src: rsync.passwd
dest: /etc/
mode: 0600
- name: start rsyncd
systemd:
name: rsyncd
state: restarted
enabled: yes
- hosts: client
tasks:
- name: passwd file
copy:
content: '123456'
dest: /etc/rsync.pass
mode: 0600
notes : The password file required by the client and the configuration file and password file required by the server , Ahead of time /root/project1 Get ready
Actual combat II :
The required hosts The list is as follows :
[server]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8
[client]
backup ansible_ssh_host=10.0.0.41
The specific script is as follows :
- hosts: all
tasks:
- name: Install Nfs
yum:
name: nfs-utils
state: present
- name: Create group
group:
name: www
gid: 666
- name: Create user
user:
name: www
uid: 666
group: www
create_home: false
shell: /sbin/nologin
- hosts: server
tasks:
- name: Configure nfs
copy:
src: ./exports.j2
dest: /etc/exports
- name: Create Directory
file:
path: /data
state: directory
owner: www
group: www
recurse: yes
- name: Restart Nfs
systemd:
name: nfs
state: started
enabled: yes
- hosts: web01
tasks:
- name: web01 mount server
mount:
src: 172.16.1.31:/data
path: /mnt
fstype: nfs
opts: defaults
state: mounted
- hosts: web02
tasks:
- name: web01 mount server
mount:
src: 172.16.1.31:/data
path: /mnt
fstype: nfs
opts: defaults
state: mounted
Check grammar :
[[email protected] projects]# ansible-playbook --syntax-check nfs.yml -i hosts
perform :
[[email protected] projects]# ansible-playbook nfs.yml -i hosts
Be careful : The required configuration files are prepared by yourself
Actual combat three :
Actual combat needs :
Use playbook To achieve a set of LAMP framework .
Deployment requirements :
1. Use yum install httpd、php、php-mysql、php-pdo、mariadb
2. start-up httpd、mariadb service
3. download wordpress Code
4. Deploy to httpd Site directory
(1) detailed list hosts as follows
[web]
web01 ansible_ssh_host=10.0.0.7
web02 ansible_ssh_host=10.0.0.8
(2) The specific script is as follows
- hosts: web
vars:
packages:
- httpd
- mariadb-server
- php
- php-mysql
- php-pdo
tasks:
- name: Install httpd mariadb php Server
yum:
name: "{
{ packages }}"
state: present
- name: start httpd server
systemd:
name: httpd
state: started
enabled: yes
- name: start mariadb Server
systemd:
name: mariadb
state: started
enabled: yes
- name: Unarchive wordpress Package
unarchive:
src: wordpress-5.0.3-zh_CN.tar.gz
dest: /var/www/html
copy: yes
(3) Execute the script and test
Check grammar :
[[email protected] projects]# ansible-playbook --syntax-check wp.yml -i hosts
perform :
[[email protected] projects]# ansible-playbook wp.yml -i hosts
Open browser access :
http://10.0.0.7/wordpress/wp-admin/setup-config.php
http://10.0.0.8/wordpress/wp-admin/setup-config.php
Written by Argo : The database is ready to use
[[email protected] lamp]# cat lamp.yml
- hosts: web01
tasks:
- name: Install LAMP
yum:
name: "{
{ servers }}"
vars:
servers:
- httpd
- mariadb-server
- php
- php-mysql
- php-pdo
- MySQL-python
- name: Configure Html wordpress
copy:
src: wordpress-5.0.3.tar.gz
dest: /var/www/html/
- name: unarchive wordpress
unarchive:
src: /var/www/html/wordpress-5.0.3.tar.gz
dest: /var/www/html/
copy: no
- name: Change Mode Wordpress
file:
path: /var/www/html/wordpress
owner: apache
group: apache
recurse: yes
- name: Start HTTPD Server
systemd:
name: httpd
state: started
enabled: yes
- name: Start Mariadb Server
systemd:
name: mariadb
state: started
enabled: yes
- name: Removes all anonymous user accounts
mysql_user:
name: ''
host_all: yes
state: absent
- name: Create database user
mysql_user:
name: lzy
password: lzy123.com
priv: '*.*:ALL'
state: present
host: localhost
- name: Create Database wordpress
mysql_db:
login_user: lzy
login_password: lzy123.com
login_host: localhost
login_port: 3306
name: wordpress
state: present
4. Ansible Variable Overview
Variables provide a convenient way to manage Ansible playbook Dynamic values in each project of , such as nginx-1.6.3 The version of this package , It may be used again and again in other places , So if this value is set as a variable , And then in other playbook Call in , It will be much more convenient .
5. Ansible Variable definitions
(1)playbook Variables can be defined in many ways , The easiest way is to playbook Of Start by vars Define
# Method 1 :
# Install two packages using variable mode
[[email protected] project1]# cat p2.yml
- hosts: webservers
vars:
- web_package: httpd
- ftp_package: vsftpd
tasks:
- name: Installed Packages
yum:
name:
- "{
{ web_package }}"
- "{
{ ftp_package }}"
state: present
# Method 2 :
- hosts: web_group
vars:
packages:
- httpd
- mariadb-server
- php
- php-mysql
- php-pdo
tasks:
- name: Install httpd mariadb php Server
yum:
name: "{
{ packages }}"
(2) It can also be in playbook Use in vars_files Specify file as variable file , The advantage is the other playbook You can also call
[[email protected] project1]# cat vars.yml
web_package: httpd
ftp_package: vsftpd
[[email protected] project1]# cat p2.yml
- hosts: webservers
vars_files: ./vars.yml
tasks:
- name: Installed Packages
yum:
name:
- "{
{ web_package }}"
- "{
{ ftp_package }}"
state: present

(3) stay inventory Define variables in , Host variables take precedence over host group variables ( Not recommended , It is easy to make the environment very messy )
[[email protected] project1]# vim /etc/ansible/hosts
[webservers]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8
[webservers:vars]
filename=group_vars
[[email protected] project1]# cat p3.yml
- hosts: webservers
tasks:
- name: Create File
file: path=/tmp/{
{ filename }} state=touch
(4) A better way is to ansible Create two additional variable directories in the project directory of , Namely host_vars and group_vars ( Bear in mind , Directory names must be consistent , Can't make any changes )
Host group definition variables
group_vars It must be stored and inventory The group names defined in the manifest file are consistent , as follows
[[email protected] project1]# cat /etc/ansible/hosts
[webservers]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8
[[email protected] project1]# cat group_vars/webservers
web_package: httpd
ftp_package: vsftpd
Be careful : The system provides special groups ,all, That is to say group_vars Create one in the directory all file , The defined variables are valid for all hosts
Host definition variables
[[email protected] project1]# cat host_vars/web01
web_package: zlib-static
ftp_package: zmap
[[email protected] project1]# cat group_vars/webservers
web_package: httpd
ftp_package: vsftpd
[[email protected] project1]# cat p4.yml
- hosts: webservers
#- hosts: otherservers
tasks:
- name: Installed Packages
yum:
name:
- "{
{ web_package }}"
- "{
{ ftp_package }}"
state: present
The priority of the host is greater than that of the Group
(5) Override variables from the command line ,inventory The variables of will be playbook Overwrite... In file , Variables in both ways will be called
The command line directly specifies the variables to be overwritten . Use –extra-vars or -e Set variable .
[[email protected] project1]# ansible-playbook p4.yml -e "web_package=zarafa-devel" -e "ftp_package=zarafa-utils"
(6) Variable priority test
Command line variables --->play Medium vars_files--->play Medium vars Variable -->host_vars Variables defined in --->group_vars/ Group --->group_vars/all
[[email protected] project1]# cat p5.yml
- hosts: webservers
# vars:
# filename: play_vars
# vars_files:
# - ./vars.yml
tasks:
- name: Create
shell: mkdir -pv /tmp/{
{ filename }}
register: mk_test
- name: debug
debug: msg={
{ mk_test }}
6. Ansible Variable registration
When absible After the module is running , In fact, they will return some result result , It's like executing a script , We sometimes need scripts to give us some return Return value , We just found out , Whether the previous step can be executed successfully , however … By default ,ansible Of result It doesn't show , therefore , We can put these return values ’ Storage ’ Into variables , So we can go through ’ call ’ The corresponding variable name , To get these result, This will return the value of the module , Methods written to variables are called variable registration
- hosts: webservers
tasks:
- name: Get Network Port Status
shell: "ls -l /"
register: list_dir
- name: OutPut Network Port Status
debug:
msg: "{
{ list_dir.stdout_lines }}"
To call the contents of this :stdout_lines
"stdout_lines": [
" Total usage 24",
"lrwxrwxrwx. 1 root root 7 3 month 9 2019 bin -> usr/bin",
"dr-xr-xr-x. 5 root root 4096 3 month 9 2019 boot",
"drwxr-xr-x. 20 root root 3260 9 month 10 09:47 dev",
]
(1) Variables also support hierarchical definitions , Use ".“ There may be problems , It is recommended to use ”[]" Instead of .
[[email protected] project1]# cat vars1.yml
rainbow:
web:
web_package: httpd
db_package: mariadb
code:
web:
filename: code_web_filename
[[email protected] project1]# cat p8.yml
- hosts: webservers
vars_files: ./vars1.yml
tasks:
- name: Install Package
yum: name= "{
{ rainbow['web']['web_package'] }}"
- name: create filename
file:
path: /tmp/{
{ code.web.filename }}
state: touch
7. Ansible facts cache
Ansible facts Is passed on the managed machine Ansible Automatically collect discovered variables
facts(setup modular ) Contains information about each specific host . such as : The host name of the controlled end 、IP Address 、 System version 、CPU Number 、 Memory status 、 Disk status and so on .
facts Use scenarios :
1. adopt facts Cache check CPU, To generate the corresponding nginx The configuration file
2. adopt facts Cache check host name , Generate different zabbix The configuration file
3. adopt facts The cache retrieves the memory size of the physical machine to generate invalid mysql The configuration file
# edit
[[email protected] ~]# vim facts.yml
- hosts: web_group
tasks:
- name: Get Host Info
debug:
msg: >
Hostname "{
{ ansible_fqdn }}" and IP "{
{ ansible_default_ipv4.address }}"
# perform
[[email protected] ~]# ansible-playbook facts.yml
[[email protected] ~]# ansible-playbook facts.yml
ok: [web01] => {
"msg": "Hostname \"web01\" and IP \"10.0.0.7\"\n"
}
ok: [web02] => {
"msg": "Hostname \"web02\" and IP \"10.0.0.8\"\n"
}
close facts(setup modular )
[[email protected] ~]# vim facts.yml
- hosts: web_group
gather_facts: no # Turn off information collection
tasks:
facts Generate zabbix The configuration file
- hosts: web_group
vars:
- zabbix_server: 172.16.1.71
tasks:
- name: copy zabbix agent conf
template:
src: ./zabbix_agentd.conf
dest: /tmp/zabbix_agentd.conf
facts Generate mysqld The configuration file
- hosts: db_group
tasks:
- name: Install mysql server
yum:
name: mariadb-server
state: present
- name: copy mysql conf
template:
src: ./my.cnf
dest: /etc/my.cnf
[[email protected] ~]# vim /etc/my.cnf
[mysqld]
basedir=/usr
datadir=/var/lib/mysql/
socket=/var/lib/mysql/mysql.sock
log_error=/var/log/mariadb/mariadb.log
innodb_buffer_pool_size={
{ ansible_memtotal_mb * 0.8 }}
playbook To install a memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="{
{ ansible_memtotal_mb //2 }}" # //2 So divide by no decimal point
OPTIONS=""
[[email protected] project1]# cat p11.yml
- hosts: webservers
tasks:
- name: Installed Memcached
yum: name=memcached state=present
- name: Configure Memcached
template: src=./memcached.j2 dest=/etc/sysconfig/memcached
- name: Start Memcached
service: name=memcached state=started enabled=yes
8. Self summary
frequently-used facts Variable :
ansible_all_ipv4_addresses: Show only ipv4 Information about .
ansible_devices: Display only disk device information .
ansible_distribution: It shows what the system is , example :centos,suse etc. .
ansible_distribution_major_version: The display is the main version of the system .
ansible_distribution_version: Show only system version .
ansible_machine: Display system type , example :32 position , still 64 position .
ansible_eth0: Show only eth0 Information about .
ansible_hostname: Display only the host name .
ansible_kernel: Show only kernel version .
ansible_lvm: Show lvm Related information .
ansible_memtotal_mb: Display the total memory of the system .
ansible_memfree_mb: Display available system memory .
ansible_memory_mb: Display the memory in detail .
ansible_swaptotal_mb: Show the total swap Memory .
ansible_swapfree_mb: Show swap Memory available memory .
ansible_mounts: Display the system disk mount .
ansible_processor: Show cpu Number ( Show each one specifically cpu Model ).
ansible_processor_vcpus: Show cpu Number ( Only the total number is shown ).












边栏推荐
- Permission to query execution plan in Oracle Database
- NPOI 创建Word
- June training (day 11) - matrix
- Role of volatile keyword
- 阅读笔记 Deep Hough Voting for 3D Object Detection in Point Clouds
- Cloning PDB with ADG standby
- How do complex systems detect anomalies? North Carolina UNCC and others' latest overview of graph based deep learning anomaly detection methods in complex distributed systems describes the latest prog
- SQL tuning guide notes 16:managing historical optimizer statistics
- @loadbalance annotation of resttemplate
- talent showing itself! Oceanbase was selected into the 2021 "sci tech innovation China" open source innovation list
猜你喜欢

Shell script Basics

NiO User Guide

SQL调优指南笔记13:Gathering Optimizer Statistics

PCB package download website recommendation and detailed usage

Graphics2d class basic use

Ansible playbook和Ansible Roles(三)

SQL调优指南笔记10:Optimizer Statistics Concepts

Graphics2D类基本使用

SQL tuning guide notes 8:optimizer access paths

ICML2022 | GALAXY:极化图主动学习
随机推荐
ZGC concurrent identity and multi view address mapping in concurrent transition phase
Turing prize winner: what should I pay attention to if I want to succeed in my academic career?
Is it safe to open an account in tonghuashun? How to open an account
SQL调优指南笔记10:Optimizer Statistics Concepts
Ansible playbook and ansible roles (III)
Xingda easy control modbustcp to profibusdp
同花顺能开户吗,在APP上可以直接开通券商安全吗 ,证券开户怎么开户流程
Yyds dry goods inventory solution sword finger offer: the first non repeated character in the character stream
MySQL introduction and installation (I)
Ansible summary (VI)
Ansible playbook和变量(二)
[QNX hypervisor 2.2 user manual] 4.3 obtain the host component
About the solution to "the application cannot start normally 0xc00000022" after qt5.15.2 is installed and qtcreator is started
What is your understanding of thread priority?
MySQL介绍和安装(一)
SQL调优指南笔记9:Joins
SQL调优指南笔记16:Managing Historical Optimizer Statistics
Icml2022 | galaxy: active learning of polarization map
关于 安装Qt5.15.2启动QtCreator后“应用程序无法正常启动0xc0000022” 的解决方法
Oracle livelabs experiment: introduction to Oracle Spatial