30选5玩法|福彩30选5开奖结果321|
 

标签:ansible

一看必会系列:ansible 本站实验基础

 

以下为ansible实验的基础配置

           

创建免密登陆
[[email protected]_master ~]# ssh-keygen -t rsa -P ”
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory ‘/root/.ssh’.
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
3b:13:81:60:1d:34:54:32:27:b8:35:64:e3:d1:07:8e [email protected]_master
The key’s randomart image is:

 

将.pub导入到目标服务器

ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

修改 /etc/ansible/hosts

#以下[ ]中为rols调用名

[test]
192.168.142.104

 

运行 ansible-playbook

ansible-playbook /etc/ansible/roles/xx.yaml -vv

—-技巧————————————–
ansible 常用模块之command/shell/raw

是否支持管道

------中间广告---------

module    是否支持管道
command    不支持管道
shell    支持管道——–
raw    支持管道  ——–

使用方法

[[email protected] ~]# ansible localhost -m command -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible localhost -m shell -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible localhost -m raw -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

直接执行某个文件

[[email protected] ~]# ansible host32 -m command -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible host32 -m raw -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible host32 -m shell -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

 

[[email protected]_master roles]# ansible all -m shell -a ‘systemctl status iptables  |grep Active’
192.168.142.102 | SUCCESS | rc=0 >>
   Active: active (exited) since Wed 2018-02-28 11:29:23 CST; 33min ago

192.168.142.104 | SUCCESS | rc=0 >>
   Active: active (exited) since Mon 2018-02-26 17:48:34 CST; 1 day 18h ago

192.168.142.103 | SUCCESS | rc=0 >>
   Active: active (exited) since Mon 2018-02-26 17:49:06 CST; 1 day 18h ago

[[email protected]_master roles]#

ansible-doc -l  列出所有支持的模块
            -s  列出模块支持的动作
            -h
            -v 或-vvv 显示详细信息

一看必会系列:ansible 自动部署mysql多实例

 

 

目录

/etc/ansible/roles/m_mysql/
?#25193;ぉ?files
│   ?#25193;ぉ?m_mysql3355_adduser.sh
│   ?#25193;ぉ?m_mysql3355_setup.sh
│   ?#25193;ぉ?m_mysql3356_adduser.sh
│   ?#25193;ぉ?m_mysql3356_setup.sh
│   ?#25193;ぉ?mysql-5.5.34.tar.gz
│   └── mysql-5.6.34.tar.gz
└── tasks
    ?#25193;ぉ?main.yaml

 

—–testmysql.yaml

– name: test
  hosts: test
  remote_user: root
  roles:
    – m_mysql

 

——m_mysql\tasks\main.yaml

– name: cp tar5.5
  copy: src=mysql-5.5.34.tar.gz dest=/tmp
– name: cp tar5.6
  copy: src=mysql-5.6.34.tar.gz dest=/tmp
– name: cp 3355
  copy: src=m_mysql3355_setup.sh dest=/tmp mode=700
– name: cp 3355 add usre
  copy: src=m_mysql3355_adduser.sh dest=/tmp mode=700
– name: cp 3356
  copy: src=m_mysql3356_setup.sh dest=/tmp mode=700
– name: cp 3356 add user
  copy: src=m_mysql3356_adduser.sh dest=/tmp mode=700
#开始二进制安装
– name: exec m_mysql3355_setup.sh
  shell: /tmp/m_mysql3355_setup.sh
– name: exec m_mysql3356_setup.sh
  shell: /tmp/m_mysql3356_setup.sh
#开始启动授权
– name: start m_mysql3355
  shell: cd /usr/mysqlsoft_3355 && ./bin/mysqld_safe –user=mysql &
– name: start m_mysql3356
  shell: cd /usr/mysqlsoft_3356 && ./bin/mysqld_safe –user=mysql &
– name: sleep 2
  shell: sleep 2
– name: exec m_mysql3355_adduser.sh
  shell: /tmp/m_mysql3355_adduser.sh
– name: exec m_mysql3356_adduser.sh
  shell: /tmp/m_mysql3356_adduser.sh
– name: delete sh
  shell: rm -rf /tmp/*.sh

 

各脚本内容

———\m_mysql\files\m_mysql3355_setup.sh

 

#!/bin/bash
yum -y install gcc gcc-c++ make cmake automake autoconf libxml2 libxml2-devel zlib zlib-devel ncurses ncurses-devel
yum -y install libaio libaio-devel

groupadd mysql
useradd mysql -g mysql

rm -rf /usr/mysqlsoft_3355/*
rm -rf /usr/mysqldata/3355/*
mkdir /usr/mysqlsoft_3355
mkdir -p /usr/mysqldata/3355
mkdir -p /usr/mysqlsoft_3355/etc
touch /usr/mysqldata/3355/install3355.log
chown -R mysql:mysql  /usr/mysqlsoft_3355
chown -R mysql:mysql  /usr/mysqldata/3355

cd /usr/mysqlsoft_3355
cp /tmp/mysql-5.5.34.tar.gz .
tar -zxf mysql-5.5.34.tar.gz
cd mysql-5.5.34

cmake \
-DCMAKE_INSTALL_PREFIX=/usr/mysqlsoft_3355 \
-DMYSQL_DATADIR=/usr/mysqldata/3355 \
-DSYSCONFDIR=/usr/mysqlsoft_3355/etc \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
-DWITH_READLINE=1 \
-DMYSQL_UNIX_ADDR=/tmp/mysql3355.sock \
-DMYSQL_TCP_PORT=3355 \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8mb4 \
-DDEFAULT_COLLATION=utf8mb4_general_ci

make && make install >> /usr/mysqldata/3355/install3355.log

rm -rf /etc/my.cnf
rm -rf /usr/mysqlsoft_3355/etc/my.cnf

cp /usr/mysqlsoft_3355/support-files/my-large.cnf /usr/mysqlsoft_3355/etc/my.cnf

cd /usr/mysqlsoft_3355
/usr/mysqlsoft_3355/scripts/mysql_install_db –user=mysql –datadir=/usr/mysqldata/3355/
#/usr/mysqlsoft_3355/bin/mysqladmin -umysql -pmysql -S /tmp/mysql3355.sock shutdown

 

———\m_mysql\files\

#!/bin/bash
/usr/mysqlsoft_3355/bin/mysql -u root  -S /tmp/mysql3355.sock << EOF
use mysql;
grant shutdown on *.* to [email protected]’localhost’ identified by ‘mysql’;
flush privileges;
EOF

image

一看必会系列:ansible初始化 centos 7

一看必会系列:ansible初始化 centos 7

—————–hosts

[initialize-group]
192.168.142.104

目录规化

?#25193;ぉ?initialize
│   ?#25193;ぉ?files
│   │   ?#25193;ぉ?Centos-7.repo
│   │   └── epel.repo
│   └── tasks
│       └── main.yaml
?#25193;ぉ?initialize.yaml
?#25193;ぉ?zabbix-agent
│   ?#25193;ぉ?handlers
│   │   └── main.yaml
│   └── tasks
│       └── main.yaml
└── zabbix-agent.yaml

———-initialize.yaml

– name: centos7 initialize.
  hosts: initialize-group
  remote_user: root
  roles:
  – initialize
  – zabbix-agent

———initialize/tasks/main.yaml
[[email protected]_master roles]# vim initialize/tasks/main.yaml

– name: copy alirepo
  copy: src=Centos-7.repo dest=/etc/yum.repos.d/Centos-7.repo
– name: copy epel
  copy: src=epel.repo dest=/etc/yum.repos.d/epel.repo
#- name: 重构源
#  yum: name=makecache
– name: 安装vim,nettools
#多项同步安装
  yum: name={{ item }} state=installed
  with_items:
     – vim
     – net-tools
– name: 安装ntp
  yum: name=chrony state=installed
– name: 开机启动ntp服务
  service: name=chronyd enabled=yes
– name: 修改时区
  shell: timedatectl set-timezone Asia/Shanghai
– name: 修改ntp配置
  shell: sed -i ‘s/server 0.centos.pool.ntp.org iburst/server 172.30.100.139 iburst/g’ /etc/chrony.conf
– name: 重启ntp服务
  service: name=chronyd state=restarted
– name: 查看同步是否正确
  shell: ‘chronyc sources -v >> /tmp/ntp.log’

———–zabbix-agent/tasks/main.yaml
[[email protected]_master roles]# vim zabbix-agent/tasks/main.yaml

#前提是开启了iptables /firewalld才使用
#- name: add iptables
#  shell: iptables -I  INPUT 1 -p tcp –dport 10050 -j ACCEPT
#- name: save iptables
#  shell: service iptables save
#前提是开启了iptables /firewalld才使用
– name: rpm i
  yum: name=http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
– name: yum zabbix-agent
  #yum: name=zabbix-agent state=latest enable=yes
  yum: name=zabbix-agent state=latest
– name: enable service
  shell: systemctl enable zabbix-agent
– name: change server ip
  shell: sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
– name: change server active ip
  shell: sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
– name: change server hostname
  shell: sed -i ‘s/Hostname=Zabbix server/Hostname={{hostname}}/g’ /etc/zabbix/zabbix_agentd.conf
  notify :
      – restart zabbix-agent

——以下是思路—————
#替换成国内源
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum clean all
yum makecache
yum install epel-release

 

——————-备用

服务器配置chrony  ntp
  yum install -y chrony  安装
  systemctl enable chronyd  开机启动
  systemctl restart chronyd  启动服务
  timedatectl
  chronyc sources

  开放端口看
  [[email protected] ~]# netstat -ntlpu |grep chrony
udp        0      0 127.0.0.1:323           0.0.0.0:*                           31875/chronyd      
udp        0      0 0.0.0.0:123             0.0.0.0:*                           31875/chronyd      
udp6       0      0 ::1:323                 :::*                                31875/chronyd      
[[email protected] ~]#

 
客户端配置chrony
vim /etc/chrony.conf
service 172.30.100.139 iburst
保存重启服务
查看同步命令

systemctl restart chronyd
chronyc sources -v
date
timedatectl -h
timedatectl set-timezone Asia/Shanghai
date  确认无误
———————————–
[[email protected] ~]# date
Tue Dec 26 02:59:21 EST 2017
[[email protected] ~]# !time
-bash: !time: event not found
[[email protected] ~]# timedatectl
      Local time: Tue 2017-12-26 02:59:42 EST
  Universal time: Tue 2017-12-26 07:59:42 UTC
        RTC time: Tue 2017-12-26 07:59:42
       Time zone: America/New_York (EST, -0500)
     NTP enabled: yes
NTP synchronized: yes
RTC in local TZ: no
      DST active: no
Last DST change: DST ended at
                  Sun 2017-11-05 01:59:59 EDT
                  Sun 2017-11-05 01:00:00 EST
Next DST change: DST begins (the clock jumps one hour forward) at
                  Sun 2018-03-11 01:59:59 EST
                  Sun 2018-03-11 03:00:00 EDT
—————————————-
[[email protected] ~]# timedatectl
      Local time: Tue 2017-12-26 16:00:47 CST
  Universal time: Tue 2017-12-26 08:00:47 UTC
        RTC time: Tue 2017-12-26 08:00:47
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: yes
NTP synchronized: yes
RTC in local TZ: no
      DST active: n/a

6.8
[[email protected] ~]# ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*172.30.100.139  85.199.214.100   2 u   24   64    1    2.261    1.572   0.806
7.0
[[email protected] conf.d]# chronyc sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample
===============================================================================
^* 172.30.100.139                2   6   377    42   -203us[+1131us] +/-  145ms
[[email protected] conf.d]#

测试
[[email protected] ~]# date -s 2000-01-01  修改时间
Sat Jan  1 00:00:00 CST 2000
[[email protected] ~]# date
Sat Jan  1 00:00:02 CST 2000
[[email protected] ~]# service ntpd restart 重启服务
Shutting down ntpd:                                        [FAILED]
Starting ntpd: 
[[email protected] ~]# date
Fri Apr 28 15:50:59 CST 2017
[[email protected] ~]# ntpq -p  查看状态
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
*172.30.100.139  61.216.153.104   4 u    9   64    1    2.673    0.396   0.376
[[email protected] ~]# 

一看必会系列:ansible 部署lamp

 

————目录规划
[[email protected]_master roles]# tree
.
?#25193;ぉ?apache
│   ?#25193;ぉ?tasks
│   │   └── main.yaml
│   └── templates
│       └── index.php

?#25193;ぉ?lamp.yaml
?#25193;ぉ?mysql
│   └── tasks
│       ?#25193;ぉ?main.yaml
│       └── main.yaml~

————mysql/main.yaml

[[email protected]_master roles]# cat mysql/tasks/main.yaml
– name: install MySQL-python
  yum: name=MySQL-python state=installed
– name: install mariadb-server
  yum: name={{ item }} state=installed
  with_items:
        – mariadb-server
  notify:
        – restart mysql
– name: Start mariadb
  service: name=mariadb state=restarted enabled=yes
#增加用户方式1 
– name: user
  mysql_user: name=xx password=12345 priv=*.*:ALL state=present  
– name: Create db
  mysql_db:
    login_host: "127.0.0.1"
    login_user: "root"
    login_password: ""
    login_port: "3306"
    name: "cisco_db"
    encoding: "utf8"
    state: "present"
#增加用户方式2
– name: create a user
  mysql_user:
      login_host: "127.0.0.1"
      login_user: "root"
      login_password: ""
      login_port: "3306"
      name: "cisco"
      password: "1234"
      host: "192.168.142.%"
      priv: "*.*:all"
      state: "present"
#collation,config_file,connect_timeout,encoding,login_host,login_password,login_port,login_unix_socket,login_user,name,quick,single_transaction,ssl_ca,ssl_cert,ssl_key,state,target

———-apache/main.yaml
[[email protected]_master roles]# cat apache/tasks/main.yaml
– name: remove old version php
  yum: name=php* state=absent
– name: remove old version mysql
  yum: name=MySQL-server-5.6.35-1.el7.x86_64 state=absent
– name: install apache and php
  yum: name={{ item }} state=present
  with_items:
        – httpd
        – php
        – php-mysql
– name: copy index.php.j2
  template: src=index.php dest=/var/www/html/index.php
– name: http service state
  service: name=httpd state=restarted
– name: http service enable
  shell: systemctl enable httpd
[[email protected]_master roles]#

———lamp.yaml
[[email protected]_master roles]# cat lamp.yaml
– name: hosts
  hosts: all
  remote_user: root
– name: install omysql
  hosts: mysql
  roles:
    – mysql
– name: install apache and php
  hosts: apache
  roles:
    – apache

———-验证–
[[email protected]_master roles]# ansible apache -m shell -a "curl localhost/index.php |grep ansible"
[WARNING]: Consider using get_url or uri module rather than running curl

192.168.142.103 | SUCCESS | rc=0 >>
<tr><td class="e">System </td><td class="v">Linux ansible_03 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 22 16:42:41 UTC 2016 x86_64 </td></tr>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 47382    0 47382    0     0  3157k      0 –:–:– –:–:– –:–:– 3305k

192.168.142.102 | SUCCESS | rc=0 >>
<tr><td class="e">System </td><td class="v">Linux ansible_02 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 22 16:42:41 UTC 2016 x86_64 </td></tr>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 47382    0 47382    0     0  3667k      0 –:–:– –:–:– –:–:– 3855k

[[email protected]_master roles]#

 

———执行结果—
ansible-playbook lamp.yaml

PLAY [hosts] ********************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************
ok: [192.168.142.104]
ok: [192.168.142.102]
ok: [192.168.142.103]

PLAY [install omysql] ***********************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************
ok: [192.168.142.104]

TASK [mysql : install MySQL-python] *********************************************************************************************
ok: [192.168.142.104]

TASK [mysql : install mariadb-server] *******************************************************************************************
ok: [192.168.142.104] => (item=[u’mariadb-server’])

TASK [mysql : Start mariadb] ****************************************************************************************************
changed: [192.168.142.104]

TASK [mysql : user] *************************************************************************************************************
ok: [192.168.142.104]

TASK [mysql : Create db] ********************************************************************************************************
ok: [192.168.142.104]

TASK [mysql : create a user] ****************************************************************************************************
ok: [192.168.142.104]

PLAY [install apache and php] ***************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************
ok: [192.168.142.102]
ok: [192.168.142.103]

TASK [apache : remove old version php] ******************************************************************************************
changed: [192.168.142.103]
changed: [192.168.142.102]

TASK [apache : remove old version mysql] ****************************************************************************************
ok: [192.168.142.103]
ok: [192.168.142.102]

TASK [apache : install apache and php] ******************************************************************************************
changed: [192.168.142.103] => (item=[u’httpd’, u’php’, u’php-mysql’])
changed: [192.168.142.102] => (item=[u’httpd’, u’php’, u’php-mysql’])

TASK [apache : copy index.php.j2] ***********************************************************************************************
changed: [192.168.142.103]
changed: [192.168.142.102]

TASK [apache : http service state] **********************************************************************************************
changed: [192.168.142.103]
changed: [192.168.142.102]

TASK [apache : http service enable] *********************************************************************************************
changed: [192.168.142.103]
changed: [192.168.142.102]

PLAY RECAP **********************************************************************************************************************
192.168.142.102            : ok=8    changed=5    unreachable=0    failed=0  
192.168.142.103            : ok=8    changed=5    unreachable=0    failed=0  
192.168.142.104            : ok=8    changed=1    unreachable=0    failed=0 

———-之前安装mysql报错

TASK [mysql : user] ***************************************************************************************************************
task path: /etc/ansible/roles/mysql/tasks/main.yaml:11
fatal: [192.168.142.104]: FAILED! => {"changed": false, "msg": "The MySQL-python module is required."}
    to retry, use: –limit @/etc/ansible/roles/lamp.retry

解决方法:mysqlserver 需要安装MySQL-python

ansible mysql_db模块 说明

No Comments Linux

https://www.kancloud.cn/hiyang/ansiblebook/306176

mysql_db模块用于建立、删除、导入和导出数据库

建立数据库

state="present"

---
- name: mysql
  hosts: s.hi.com
  tasks:
  - name: create a database
    mysql_db:
      login_host: "127.0.0.1"
      login_user: "root"
      login_password: "[email protected]"
      login_port: "3306"
      name: "mezz"
      encoding: "utf8"
      state: "present"
删除数据库

state="absent"

---
- name: mysql
  hosts: s.hi.com
  tasks:
  - name: delete a database
    mysql_db:
      login_host: "127.0.0.1"
      login_user: "root"
      login_password: "[email protected]"
      login_port: "3306"
      name: "mezz"
      state: "absent"
导出数据库

state="dump"

---
- name: mysql
  hosts: s.hi.com
  tasks:
  - name: dump a database
    mysql_db:
      login_host: "127.0.0.1"
      login_user: "root"
      login_password: "[email protected]"
      login_port: "3306"
      name: "mezz"
      target: "/tmp/mezz.gz"
      state: "dump"
导入数据库

state="import"

---
- name: mysql
  hosts: s.hi.com
  tasks:
  - name: import a database
    mysql_db:
      login_host: "127.0.0.1"
      login_user: "root"
      login_password: "[email protected]"
      login_port: "3306"
      name: "mezz"
      target: "/tmp/mezz.gz"
      state: "import"

Ansible:命令说解

No Comments Linux
[[email protected] ~]# ansible
Usage: ansible <host-pattern> [options]

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS    模块的?#38382;?如果执行默认COMMAND的模块,即是命令?#38382;?如:“date”,"pwd"等等
                        module arguments    模块?#38382;?  -k, --ask-pass        ask for SSH password  登录密码,提示输入SSH密码而不是假设基于密钥的验证
  --ask-su-pass         ask for su password    su切换密码
  -K, --ask-sudo-pass   ask for sudo password  提示密码使用sudo,sudo表示提权操作
  --ask-vault-pass      ask for vault password
  -B SECONDS, --background=SECONDS     后台运行超时时间
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don't make any changes; instead, try to predict some    只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化
                        of the changes that may occur
  -c CONNECTION, --connection=CONNECTION   连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动。
                        connection type to use (default=smart)
  -f FORKS, --forks=FORKS   并行任务数。NUM被指定为一个整数,默认是5
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit   打开帮助文档API
  -i INVENTORY, --inventory-file=INVENTORY    指定库存主机文件的路径,默认为/etc/ansible/hosts
                        specify inventory host file
                        (default=/etc/ansible/hosts)
  -l SUBSET, --limit=SUBSET    进一步限制所选主机/组模式  --limit=192.168.91.135 只对这个ip执行
                        further limit selected hosts to an additional pattern
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  -m MODULE_NAME, --module-name=MODULE_NAME   执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m?#38382;?                        module name to execute (default=command)
  -M MODULE_PATH, --module-path=MODULE_PATH    要执行的模块的路径,默认为/usr/share/ansible/
                        specify path(s) to module library
                        (default=/usr/share/ansible/)
  -o, --one-line        condense output      压缩输出,摘要输出.尝试一切都在一行上输出。
  -P POLL_INTERVAL, --poll=POLL_INTERVAL    调查背景工作每隔数秒。需要- b
                        set the poll interval if using -B (default=15)
  --private-key=PRIVATE_KEY_FILE    私钥路径,使用这个文件来验证连接
                        use this file to authenticate the connection
  -S, --su              run operations with su    用 su 命令
  -R SU_USER, --su-user=SU_USER      指定SU的用户,默认是root用户
                        run operations with su as this user (default=root)
  -s, --sudo            run operations with sudo (nopasswd)    
  -U SUDO_USER, --sudo-user=SUDO_USER    sudo到哪个用户,默认为 root  
                        desired sudo user (default=root)
  -T TIMEOUT, --timeout=TIMEOUT    指定SSH默认超时时间,  默认是10S
                        override the SSH timeout in seconds (default=10)
  -t TREE, --tree=TREE  log output to this directory     将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上。
  -u REMOTE_USER, --user=REMOTE_USER    远程用户, 默认是root用户
                        connect as this user (default=root)
  --vault-password-file=VAULT_PASSWORD_FILE  
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable    详细信息
                        connection debugging)
  --version             show program's version number and exit   输出ansible的版本
 
 特殊说明:    
1. ansible是指令核心部分,其主要用于执行ad-hoc(点对点)命令,即单条命令。默认后面需要跟主机和选项部分,默认不指定模块时,使用的是command模块。      
2. 默认使用的模块是可以在ansible.cfg 中进行修改的。 /etc/ansible/ansible.cfg  \
举例:    [[email protected] ~]# ansible 192.168.91.137 -a 'pwd'192.168.91.137 | success | rc=0 >>/root
 
[[email protected] ~]# ansible-doc  -h
Usage: ansible-doc [options] [module...]

Show Ansible module documentation     显示Ansible模块文档

Options:
  --version             show program's version number and exit    显示ansible-doc的版本号
  -h, --help            show this help message and exit  显示命令?#38382;鼳PI文档
  -M MODULE_PATH, --module-path=MODULE_PATH   查询模块,--module-path=MODULE_PATH  指定模块的路径
                        Ansible modules/ directory
  -l, --list            List available modules   显示已存在的所有模块列表
  -s, --snippet         Show playbook snippet for specified module(s)   显示playbook制定模块的用法
  -v                    Show version number and exit   显示ansible-doc的版本号
 
举例:      $     ansible-doc -l      $     ansible-doc -s command 3.ansible-galaxy   ?#38382;?#35814;解:
 
 
[[email protected] ~]# ansible-galaxy -h
Usage: ansible-galaxy [init|info|install|list|remove] [--help] [options] ...

Options:
  -h, --help  show this help message and exit

See 'ansible-galaxy <command> --help' for more information on a specific command.

  特殊说明:    ansible-galaxy 指令用于方便的从https://galaxy.ansible.com/ 站点下载第三方扩展模块,我们可以形象的理解其类似于centos下的yum、python下的pip或easy_install  举例:    [[email protected] ~]# ansible-galaxy install aeriscloud.docker – downloading role ‘docker’, owned by aeriscloud – extracting aeriscloud.docker to /etc/ansible/roles/aeriscloud.docker – aeriscloud.docker was installed successfully 4.ansible-playbook  ?#38382;?#35814;解:

[[email protected] ~]# ansible-playbook -h
Usage: ansible-playbook playbook.yml

Options:
  -k, --ask-pass        ask for SSH password
  --ask-su-pass         ask for su password
  -K, --ask-sudo-pass   ask for sudo password
  --ask-vault-pass      ask for vault password
  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur
  -c CONNECTION, --connection=CONNECTION
                        connection type to use (default=smart)
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON
  --force-handlers      run handlers even if a task fails
  -f FORKS, --forks=FORKS
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory-file=INVENTORY
                        specify inventory host file
                        (default=/etc/ansible/hosts)
  -l SUBSET, --limit=SUBSET
                        further limit selected hosts to an additional pattern
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  --list-tasks          list all tasks that would be executed
  -M MODULE_PATH, --module-path=MODULE_PATH
                        specify path(s) to module library
                        (default=/usr/share/ansible/)
  --private-key=PRIVATE_KEY_FILE
                        use this file to authenticate the connection
  --skip-tags=SKIP_TAGS
                        only run plays and tasks whose tags do not match these
                        values
  --start-at-task=START_AT
                        start the playbook at the task matching this name
  --step                one-step-at-a-time: confirm each task before running
  -S, --su              run operations with su
  -R SU_USER, --su-user=SU_USER
                        run operations with su as this user (default=root)
  -s, --sudo            run operations with sudo (nopasswd)
  -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root)
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  -t TAGS, --tags=TAGS  only run plays and tasks tagged with these values
  -T TIMEOUT, --timeout=TIMEOUT
                        override the SSH timeout in seconds (default=10)
  -u REMOTE_USER, --user=REMOTE_USER
                        connect as this user (default=root)
  --vault-password-file=VAULT_PASSWORD_FILE
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

5.ansible-pull  ?#38382;?#35814;解:

[[email protected] ~]# ansible-pull -h
Usage: ansible-pull [options] [playbook.yml]

Options:
  -K, --ask-sudo-pass   ask for sudo password    
  -C CHECKOUT, --checkout=CHECKOUT
                        branch/tag/commit to checkout.  Defaults to behavior
                        of repository module.
  -d DEST, --directory=DEST    
                        directory to checkout repository to
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON
  -f, --force           run the playbook even if the repository could not be
                        updated
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory-file=INVENTORY    指定库存主机文件的路径,默认为/etc/ansible/hosts
                        location of the inventory host file
  -m MODULE_NAME, --module-name=MODULE_NAME   从仓库检查的模块名,默认是git
                        Module name used to check out repository.  Default is
                        git.
  -o, --only-if-changed   
                        only run the playbook if the repository has been
                        updated
  --purge               purge checkout after playbook run   
  -s SLEEP, --sleep=SLEEP
                        sleep for random interval (between 0 and n number of
                        seconds) before starting. this is a useful way to
                        disperse git requests
  -U URL, --url=URL     URL of the playbook repository
  --vault-password-file=VAULT_PASSWORD_FILE
                        vault password file
  -v, --verbose         Pass -vvvv to ansible-playbook

6.ansible-vault  ?#38382;?#35814;解:

[[email protected] ~]# ansible-vault 
Usage: ansible-vault [create|decrypt|edit|encrypt|rekey] [--help] [options] file_name

Options:
  -h, --help  show this help message and exit

See 'ansible-vault <command> --help' for more information on a specific command.

  特殊说明:官方博客。 7.参考资料  ansible中文权威?#25913;希?strong> http://www.ansible.com.cn/  ansible小结(二):ansible结构:  http://ju.outofmemory.cn/entry/143179

ansible roles说明

No Comments Linux

一、roles简介

一个项?#30475;?#24320;始到结束,不是简单几十个playbook就可以完事了,当文件数很多,有上百个的话,仅通过简单的includes不停的引用,那最终的结果错综复杂。这个时候ansible roles就可以很好的发挥它的作用了。

roles,?#32622;?#24847;思是?#24039;?#30340;含义,可以理解为有相互关联功能的集合。我?#21069;?#23433;装ntp、mem、nginx、db等等的功能?#24039;?#25918;在一个大仓库里,然后用到哪个,从那里面去拿,拿一个,拿两个都可以。

roles:是个目录,?#24039;?#38598;合

里面放的有:

    mysql/
    httpd/
    nginx/
    memcached/
每个?#24039;?#26159;一个目录

每个?#24039;?#30340;格式,一特定的层级目录结构进行组织,如下:

mysql/
    files/
    templates/
    tasks/
    handlers/
    vars/
    meta/
用到哪个目录,给出哪个目录

二、在playbook中调用?#24039;?#30340;方式

- hosts: webservers
  remote_user: root
  roles:
  - mysql
  - memcached
  - nginx

三、以mysql/为例,?#30452;?#20171;绍各个目录的意思

(1)files/:存放copy或script模块等调用的文件

(2)templates/:templates查找所需要模块文件的目录;

(3)tasks/:(必须要有)至少应该包含一个名为main.yml的文件,其他的文件需要在此文件中通过include进行包含;

(4)handlers/:至少应该包含一个名为main.yml的文件,其他的文件需要在此文件中通过include进行包含;

(5)vars/:定义的是变量,至少应该包含一个名为main.yml的文件,其他的文件需要在此文件中通过include进行包含;

(6)meta/:定义?#35828;?#21069;?#24039;?#30340;特殊设定及其他依赖关系,至少应该包含一个名为main.yml的文件,其他的文件需要在此文件中通过include进行包含;

(7)default/:为当前?#24039;?#35774;定默认变量时使用目录中的main.yml文件

一看必会系列:ansible 批量部署脚本 zabbix-agent

——–hosts配置———-
[[email protected]_master roles]# vim ../hosts

[zabbix-agent]
192.168.142.102 hostname=ansible_02  #给后面?#38382;?#36827;行调用
192.168.142.103 hostname=ansible_03
192.168.142.104 hostname=ansible_04

 

?#25193;ぉ?zabbix-agent
│   ?#25193;ぉ?handlers
│   │   └── main.yaml
│   └── tasks
│       └── main.yaml
└── zabbix-agent.yaml   #这个是引用文件,放置在roles目录,运行这个文件即可.

————思路——————

rpm -i http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
yum install zabbix-agent

vim /etc/zabbix/zabbix_agentd.conf
Server=127.0.0.1        改成Server=172.16.9.54
ServerActive=127.0.0.1  改成ServerActive=172.16.9.54
Hostname=Zabbix server  改成Hostname={hostname}   此处进行调用

——zabbix-agent.yaml  配置———
vim zabbix-agent.yaml

– hosts: zabbix-agent
  remote_user: root
  roles:
  – zabbix-agent

 

——-tasks配置脚本———-
vim zabbix-agent/tasks/main.yaml

– name: add iptables
  shell: iptables -I  INPUT 1 -p tcp –dport 10050 -j ACCEPT
– name: save iptables
  shell: service iptables save
– name: rpm i
#  shell: rpm -i http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
  yum: name=http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
– name: yum zabbix-agent
  #yum: name=zabbix-agent state=latest enable=yes
  yum: name=zabbix-agent state=latest
– name: enable service
  shell: systemctl enable zabbix-agent  #或使用 service: name=zabbix-agent enable=true
#  shell: yum install -y zabbix-agent
– name: change server ip
  shell: sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
– name: change server active ip
  shell: sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
– name: change server hostname
  shell: sed -i ‘s/Hostname=Zabbix server/Hostname={{hostname}}/g’ /etc/zabbix/zabbix_agentd.conf
  notify :
      – restart zabbix-agent

 

————-handlers脚本—————-

[[email protected]_master roles]# vim zabbix-agent/handlers/main.yaml

– name: restart zabbix-agent
  shell: systemctl restart zabbix-agent

——–正确的执行结果
[[email protected]_master roles]# ansible-playbook zabbix-agent.yaml -v
Using /etc/ansible/ansible.cfg as config file

PLAY [zabbix-agent] ******************************************************************************************

TASK [Gathering Facts] ***************************************************************************************
ok: [192.168.142.102]
ok: [192.168.142.104]
ok: [192.168.142.103]

TASK [zabbix-agent : add iptables] ***************************************************************************
changed: [192.168.142.102] => {"changed": true, "cmd": "iptables -I INPUT 1 -p tcp –dport 10050 -j ACCEPT", "delta": "0:00:00.007840", "end": "2018-02-28 17:16:59.680023", "rc": 0, "start": "2018-02-28 17:16:59.672183", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.104] => {"changed": true, "cmd": "iptables -I INPUT 1 -p tcp –dport 10050 -j ACCEPT", "delta": "0:00:00.008892", "end": "2018-02-28 17:16:59.700064", "rc": 0, "start": "2018-02-28 17:16:59.691172", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.103] => {"changed": true, "cmd": "iptables -I INPUT 1 -p tcp –dport 10050 -j ACCEPT", "delta": "0:00:00.007997", "end": "2018-02-28 17:16:59.698600", "rc": 0, "start": "2018-02-28 17:16:59.690603", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

TASK [zabbix-agent : save iptables] **************************************************************************
[WARNING]: Consider using service module rather than running service

changed: [192.168.142.103] => {"changed": true, "cmd": "service iptables save", "delta": "0:00:00.044004", "end": "2018-02-28 17:17:00.191499", "rc": 0, "start": "2018-02-28 17:17:00.147495", "stderr": "", "stderr_lines": [], "stdout": "iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]", "stdout_lines": ["iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]"]}
changed: [192.168.142.104] => {"changed": true, "cmd": "service iptables save", "delta": "0:00:00.043925", "end": "2018-02-28 17:17:00.225319", "rc": 0, "start": "2018-02-28 17:17:00.181394", "stderr": "", "stderr_lines": [], "stdout": "iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]", "stdout_lines": ["iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]"]}
changed: [192.168.142.102] => {"changed": true, "cmd": "service iptables save", "delta": "0:00:00.044992", "end": "2018-02-28 17:17:00.210450", "rc": 0, "start": "2018-02-28 17:17:00.165458", "stderr": "", "stderr_lines": [], "stdout": "iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]", "stdout_lines": ["iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]"]}

TASK [zabbix-agent : rpm i] **********************************************************************************
ok: [192.168.142.102] => {"changed": false, "msg": "", "rc": 0, "results": ["zabbix-release-3.2-1.el7.noarch providing /tmp/zabbix-release-3.2-1.el7.noarchgXuUSR.rpm is already installed"]}
ok: [192.168.142.103] => {"changed": false, "msg": "", "rc": 0, "results": ["zabbix-release-3.2-1.el7.noarch providing /tmp/zabbix-release-3.2-1.el7.noarch7GfY90.rpm is already installed"]}
ok: [192.168.142.104] => {"changed": false, "msg": "", "rc": 0, "results": ["zabbix-release-3.2-1.el7.noarch providing /tmp/zabbix-release-3.2-1.el7.noarchQBZp3k.rpm is already installed"]}

TASK [zabbix-agent : yum zabbix-agent] ***********************************************************************
changed: [192.168.142.102] => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n–> Running transaction check\n—> Package zabbix-agent.x86_64 0:3.2.11-1.el7 will be installed\n–> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package              Arch           Version               Repository      Size\n================================================================================\nInstalling:\n zabbix-agent         x86_64         3.2.11-1.el7          zabbix         348 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 348 k\nInstalled size: 1.3 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n  Verifying  : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n\nInstalled:\n  zabbix-agent.x86_64 0:3.2.11-1.el7                                            \n\nComplete!\n"]}
changed: [192.168.142.104] => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n–> Running transaction check\n—> Package zabbix-agent.x86_64 0:3.2.11-1.el7 will be installed\n–> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package              Arch           Version               Repository      Size\n================================================================================\nInstalling:\n zabbix-agent         x86_64         3.2.11-1.el7          zabbix         348 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 348 k\nInstalled size: 1.3 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n  Verifying  : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n\nInstalled:\n  zabbix-agent.x86_64 0:3.2.11-1.el7                                            \n\nComplete!\n"]}
changed: [192.168.142.103] => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n–> Running transaction check\n—> Package zabbix-agent.x86_64 0:3.2.11-1.el7 will be installed\n–> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package              Arch           Version               Repository      Size\n================================================================================\nInstalling:\n zabbix-agent         x86_64         3.2.11-1.el7          zabbix         348 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 348 k\nInstalled size: 1.3 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n  Verifying  : zabbix-agent-3.2.11-1.el7.x86_64                             1/1 \n\nInstalled:\n  zabbix-agent.x86_64 0:3.2.11-1.el7                                            \n\nComplete!\n"]}

TASK [zabbix-agent : change server ip] ***********************************************************************
[WARNING]: Consider using template or lineinfile module rather than running sed

changed: [192.168.142.102] => {"changed": true, "cmd": "sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.005006", "end": "2018-02-28 17:17:29.458373", "rc": 0, "start": "2018-02-28 17:17:29.453367", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.103] => {"changed": true, "cmd": "sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.006981", "end": "2018-02-28 17:17:29.516835", "rc": 0, "start": "2018-02-28 17:17:29.509854", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.104] => {"changed": true, "cmd": "sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.006474", "end": "2018-02-28 17:17:29.523453", "rc": 0, "start": "2018-02-28 17:17:29.516979", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

TASK [zabbix-agent : change server active ip] ****************************************************************
changed: [192.168.142.102] => {"changed": true, "cmd": "sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.007382", "end": "2018-02-28 17:17:29.960755", "rc": 0, "start": "2018-02-28 17:17:29.953373", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.103] => {"changed": true, "cmd": "sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.004726", "end": "2018-02-28 17:17:29.978994", "rc": 0, "start": "2018-02-28 17:17:29.974268", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.104] => {"changed": true, "cmd": "sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.006680", "end": "2018-02-28 17:17:30.006341", "rc": 0, "start": "2018-02-28 17:17:29.999661", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

TASK [zabbix-agent : change server hostname] *****************************************************************
changed: [192.168.142.102] => {"changed": true, "cmd": "sed -i ‘s/Hostname=Zabbix server/Hostname=ansible_02/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.005474", "end": "2018-02-28 17:17:30.583521", "rc": 0, "start": "2018-02-28 17:17:30.578047", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.104] => {"changed": true, "cmd": "sed -i ‘s/Hostname=Zabbix server/Hostname=ansible_04/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.004395", "end": "2018-02-28 17:17:30.619405", "rc": 0, "start": "2018-02-28 17:17:30.615010", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.103] => {"changed": true, "cmd": "sed -i ‘s/Hostname=Zabbix server/Hostname=ansible_03/g’ /etc/zabbix/zabbix_agentd.conf", "delta": "0:00:00.007179", "end": "2018-02-28 17:17:30.629389", "rc": 0, "start": "2018-02-28 17:17:30.622210", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

RUNNING HANDLER [zabbix-agent : restart zabbix-agent] ********************************************************
changed: [192.168.142.102] => {"changed": true, "cmd": "systemctl restart zabbix-agent", "delta": "0:00:00.066759", "end": "2018-02-28 17:17:31.157972", "rc": 0, "start": "2018-02-28 17:17:31.091213", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.104] => {"changed": true, "cmd": "systemctl restart zabbix-agent", "delta": "0:00:00.094599", "end": "2018-02-28 17:17:31.203785", "rc": 0, "start": "2018-02-28 17:17:31.109186", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
changed: [192.168.142.103] => {"changed": true, "cmd": "systemctl restart zabbix-agent", "delta": "0:00:00.069611", "end": "2018-02-28 17:17:31.203667", "rc": 0, "start": "2018-02-28 17:17:31.134056", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

PLAY RECAP ***************************************************************************************************
192.168.142.102            : ok=9    changed=7    unreachable=0    failed=0  
192.168.142.103            : ok=9    changed=7    unreachable=0    failed=0  
192.168.142.104            : ok=9    changed=7    unreachable=0    failed=0  

[[email protected]_master roles]#

———验证———————————–
ansible zabbix-agent  -m shell -a ‘cat /etc/zabbix/zabbix_agentd.conf |grep -v ^#|grep -v ^$’ -v
Using /etc/ansible/ansible.cfg as config file
192.168.142.104 | SUCCESS | rc=0 >>
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=127.0.0.1   ——–未成功
ServerActive=172.16.9.54
Hostname=ansible_04
Include=/etc/zabbix/zabbix_agentd.d/*.conf

192.168.142.103 | SUCCESS | rc=0 >>
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=127.0.0.1
ServerActive=172.16.9.54
Hostname=ansible_03
Include=/etc/zabbix/zabbix_agentd.d/*.conf

192.168.142.102 | SUCCESS | rc=0 >>
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=127.0.0.1
ServerActive=172.16.9.54
Hostname=ansible_02
Include=/etc/zabbix/zabbix_agentd.d/*.conf

————-以下是测试过程———————-

原始脚本如下 tasks/main.yaml  报错不能用
– name: add iptables
  #shell: iptables -I  INPUT 1 -p tcp –dport 10050 -j ACCEPT
– name: save iptables
  #shell: service iptables save
– name: rpm i
  raw: rpm -i http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
– name: yum zabbix-agent
  yum: name=zabbix-agent state=latest enable=yes
– name: change server ip
  shell: sed S/Server=127.0.0.1/Server=172.16.9.54/g && sed S/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g
  notify :
      – restart zabbix-agent

报这个错
不支持yum模块,实际查看是有的
      TASK [insetall zabbix-agent] *********************************************************************************
fatal: [192.168.142.102]: FAILED! => {"changed": false, "msg": "Unsupported parameters for (yum) module: enable Supported parameters include: allow_downgrade,conf_file,disable_gpg_check,disablerepo,enablerepo,exclude,install_repoquery,installroot,list,name,security,skip_broken,state,update_cache,validate_certs"}
fatal: [192.168.142.103]: FAILED! => {"changed": false, "msg": "Unsupported parameters for (yum) module: enable Supported parameters include: allow_downgrade,conf_file,disable_gpg_check,disablerepo,enablerepo,exclude,install_repoquery,installroot,list,name,security,skip_broken,state,update_cache,validate_certs"}
fatal: [192.168.142.104]: FAILED! => {"changed": false, "msg": "Unsupported parameters for (yum) module: enable Supported parameters include: allow_downgrade,conf_file,disable_gpg_check,disablerepo,enablerepo,exclude,install_repoquery,installroot,list,name,security,skip_broken,state,update_cache,validate_certs"}
    to retry, use: –limit @/etc/ansible/yamllist/zabbix-agent-all.retry

将脚本修改成
– hosts: zabbix-agent
  remote_user: root
  tasks:
    – name: insetall zabbix-agent
      shell: yum install -y zabbix-agent     —–换成这个OK
      #yum: name=zabbix-agent state=latest enable=yes

   
    [[email protected]_master roles]# ansible-playbook ../yamllist/zabbix-agent-all.yaml

PLAY [zabbix-agent] ******************************************************************************************

TASK [Gathering Facts] ***************************************************************************************
ok: [192.168.142.104]
ok: [192.168.142.102]
ok: [192.168.142.103]

TASK [insetall zabbix-agent] *********************************************************************************
[WARNING]: Consider using yum module rather than running yum

changed: [192.168.142.102]
changed: [192.168.142.103]
changed: [192.168.142.104]

PLAY RECAP ***************************************************************************************************
192.168.142.102            : ok=2    changed=1    unreachable=0    failed=0  
192.168.142.103            : ok=2    changed=1    unreachable=0    failed=0  
192.168.142.104            : ok=2    changed=1    unreachable=0    failed=0  

sed替换有问题换成这个解决
vim zabbix-agent/tasks/main.yaml
– name: change server ip
  shell: sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
  shell: sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
  shell: sed -i ‘s/Hostname=Zabbix server/Hostname={{hostname}}/g’ /etc/zabbix/zabbix_agentd.conf

TASK [zabbix-agent : change server ip] ***********************************************************************
[WARNING]: Consider using template or lineinfile module rather than running sed

changed: [192.168.142.102]
changed: [192.168.142.103]
changed: [192.168.142.104]
 
多行shell 并列测试
– name: change server ip
  shell: sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
  shell: sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /etc/zabbix/zabbix_agentd.conf
  shell: sed -i ‘s/Hostname=Zabbix server/Hostname={{hostname}}/g’ /etc/zabbix/zabbix_agentd.conf

—测试结果—————— 
      一个name只支持一个shell
[[email protected]_master roles]# ansible-playbook ../yamllist/changeip.yaml –syntax-check
[WARNING]: While constructing a mapping from /etc/ansible/yamllist/changeip.yaml, line 4, column 7, found a
duplicate dict key (shell). Using last defined value only.

修改后配置

– hosts: 192.168.142.102
  remote_user: root
  tasks:
  #测试显示 sed 可以采用 sed && sed 的方式联写,不能使用多个shell 并排
    – name: change server ip
      shell: sed -i ‘s/Server=127.0.0.1/Server=172.16.9.54/g’ /tmp/2
    – name: change servce active ip
      shell: sed -i ‘s/ServerActive=127.0.0.1/ServerActive=172.16.9.54/g’ /tmp/2
    – name: change hostname
      shell: sed -i ‘s/Hostname=Zabbix server/Hostname={{hostanme}}/g’ /tmp/2

————–以上是测试过程—————————–

ansible yum模块介绍

No Comments Linux

– name: rpm i
#  shell: rpm -i http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
  yum: name=http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
– name: yum zabbix-agent
  #yum: name=zabbix-agent state=latest enable=yes
  yum: name=zabbix-agent state=latest

 

– name: 安装最新版本的apache
  yum: name=httpd state=latest

– name: 移除apache
  yum: name=httpd state=absent

– name: 安装一个特殊版本的apache
  yum: name=httpd-2.2.29-1.4.amzn1 state=present

– name: 升级所有的软件包
  yum: name=* state=latest

– name: 从一个远程yum仓库安装nginx
  yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

– name: 从本地仓库安装nginx
  yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

– name: 安装整个Development tools相关的软件包
  yum: name="@Development tools" state=present

ansible 小技巧

No Comments Linux

ansible 常用模块之command/shell/raw

是否支持管道

module    是否支持管道
command    不支持管道
shell    支持管道——–
raw    支持管道  ——–

使用方法

[[email protected] ~]# ansible localhost -m command -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible localhost -m shell -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible localhost -m raw -a "echo hello"
localhost | SUCCESS | rc=0 >>
hello jeff

直接执行某个文件

[[email protected] ~]# ansible host32 -m command -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible host32 -m raw -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

[[email protected] ~]# ansible host32 -m shell -a "/tmp/ttt.sh"
host32 | SUCCESS | rc=0 >>
hello jeff

 

[[email protected]_master roles]# ansible all -m shell -a ‘systemctl status iptables  |grep Active’
192.168.142.102 | SUCCESS | rc=0 >>
   Active: active (exited) since Wed 2018-02-28 11:29:23 CST; 33min ago

192.168.142.104 | SUCCESS | rc=0 >>
   Active: active (exited) since Mon 2018-02-26 17:48:34 CST; 1 day 18h ago

192.168.142.103 | SUCCESS | rc=0 >>
   Active: active (exited) since Mon 2018-02-26 17:49:06 CST; 1 day 18h ago

[[email protected]_master roles]#

ansible-doc -l  列出所有支持的模块
            -s  列出模块支持的动作
            -h
            -v 或-vvv 显示详细信息

30选5玩法