ansible

来源:互联网 发布:卫生网络答题 编辑:程序博客网 时间:2024/04/30 15:16

ansible
简介
ansible是一款远程的配置管理系统
常见与ansible相同的管理系统
fabric
puppet (ruby)
saltstack (python)
chef
cfengine
func
对管理的主机进行,应用部署,应用发布,备份配置
ansible的操作是幂等的
发布应基于灰度实现,每次下线一台主机,更新应用
或蓝绿实现,每次更新一批.
保证每台服务器的业务不存在问题.
无需其他工具,即通过ssh进行连接
被管理的主机,通过特定的程序进行操作,并且该程序可以获取管理员权限.
通过ssh 连接,
以普通用户登录,普通用户具有合适的sudo 权限
某一操作出现问题,进行快速失败,并再次执行.
使用模块进行实现,内部采用多级架构
核心模块
core Modules 实现大部分基础功能
自定义模块
custom Modules 实现扩展功能
模块通过连接插件,进行管理
connection Plugins
被管理的主机通过主机清单定义
拥有 通知插件,实现发送邮件,记录日志.
play books 定义 动作
使用YAML语言
ansible 拥有两种实现方式
通过命令行实现
通过 play books 实现
安装
yum 安装
yum -y install epel-release
yum clean all
yum info ansible
yum install ansible
插件
PyYAML-3.10-11.el7.x86_64.rpm
解析YAML格式的程序包
libyaml-0.1.4-11.el7_0.x86_64.rpm
libtomcrypt-1.17-26.el7.x86_64.rpm
python-backports-1.0-8.el7.x86_64.rpm
python-cffi-1.6.0-5.el7.x86_64.rpm
python-backports-ssl_match_hostname-3.4.0.2-4.el7.noarch.rpm
libtommath-0.42.0-6.el7.x86_64.rpm
python-enum34-1.0.4-1.el7.noarch.rpm
python-ipaddress-1.0.16-2.el7.noarch.rpm
python-httplib2-0.9.1-3.el7.noarch.rpm
ansible-2.3.1.0-3.el7.noarch.rpm
python-idna-2.0-1.el7.noarch.rpm
python-markupsafe-0.11-10.el7.x86_64.rpm
python-paramiko-2.1.1-2.el7.noarch.rpm
ssh远程连接模块
python-ply-3.4-10.el7.noarch.rpm
python-pycparser-2.14-1.el7.noarch.rpm
python-setuptools-0.9.8-4.el7.noarch.rpm
python-jinja2-2.7.2-2.el7.noarch.rpm
模板插件
python2-pyasn1-0.1.9-7.el7.noarch.rpm
python2-crypto-2.6.1-15.el7.x86_64.rpm
sshpass-1.06-2.el7.x86_64.rpm
python2-cryptography-1.3.1-3.el7.x86_64.rpm
python-babel-0.9.6-8.el7.noarch.rpm
python-six-1.9.0-2.el7.noarch.rpm
文件
/etc/ansible
/etc/ansible/ansible.cfg
配置文件
roles_path = /etc/ansible/roles:/usr/share/ansible/roles
定义了角色目录 : 分隔两个路径
定义颜色
[colors]

highlight = white

verbose = blue

warn = bright purple

error = red

debug = dark gray

deprecate = purple

skip = cyan

unreachable = red

ok = green

changed = yellow

diff_add = green

diff_remove = red

diff_lines = cyan

            [defaults]

some basic default values…

inventory = /etc/ansible/hosts

library = /usr/share/my_modules/

module_utils = /usr/share/my_module_utils/

remote_tmp = ~/.ansible/tmp

local_tmp = ~/.ansible/tmp

forks = 5 并行执行的主机数

poll_interval = 15

sudo_user = root

ask_sudo_pass = True

ask_pass = True

transport = smart

remote_port = 22 远程主机使用的端口

module_lang = C

module_set_locale = False

        /etc/ansible/hosts

主机清单
只有记录在该主机中的主机才可被管控
可以在主机清单中定义连接的用户名称,以及密码.
同样可以使用ssh 无秘钥连接
/etc/ansible/roles
角色目录
/usr/bin/ansible
主程序
/usr/share/ansible
/usr/share/ansible/roles
存放定义的角色
命令行
命令格式
ansible [options]
常用格式
ansible HOST-PATTERN -m MOD_NAME -a MOD_ARGS -f FORKS -C -u USERNAME -c CONNECTION
选项分为3类
Options:
–ask-vault-pass ask for vault password
-B SECONDS, –background=SECONDS
run asynchronously, failing after X seconds
(default=N/A)

          -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          -h, --help            show this help message and exit          -l SUBSET, --limit=SUBSET                                further limit selected hosts to an additional pattern          --new-vault-password-file=NEW_VAULT_PASSWORD_FILE                                new vault password file for rekey          -o, --one-line        condense output          --output=OUTPUT_FILE  output file name for encrypt or decrypt; use - for                                stdout          -P POLL_INTERVAL, --poll=POLL_INTERVAL                                set the poll interval if using -B (default=15)          -t TREE, --tree=TREE  log output to this directory          --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          -m MODULE_NAME, --module-name=MODULE_NAME                    module name to execute (default=command)

指明使用的模块的名称
-M MODULE_PATH, –module-path=MODULE_PATH
specify path(s) to module library (default=None)
模块的路径?
-a MODULE_ARGS, –args=MODULE_ARGS
module arguments
指定模块的参数
-C, –check don’t make any changes; instead, try to predict some
of the changes that may occur
测试执行
-f FORKS, –forks=FORKS
specify number of parallel processes to use
(default=5)
将所有需要管控的主机进行分批并行处理.默认每批5个.
-i INVENTORY, –inventory-file=INVENTORY
specify inventory host path
(default=/etc/ansible/hosts) or comma separated host
list.
指明主机的清单文件
–list-hosts outputs a list of matching hosts; does not execute
anything else
列出匹配的目标主机
–syntax-check perform a syntax check on the playbook, but do not
execute it
检测play books 的语法是否存在错误.
Connection Options: 连接选项
-k, –ask-pass ask for connection password
–private-key=PRIVATE_KEY_FILE, –key-file=PRIVATE_KEY_FILE
use this file to authenticate the connection

        -T TIMEOUT, --timeout=TIMEOUT                            override the connection timeout in seconds                            (default=10)        --ssh-common-args=SSH_COMMON_ARGS                            specify common arguments to pass to sftp/scp/ssh (e.g.                            ProxyCommand)        --sftp-extra-args=SFTP_EXTRA_ARGS                            specify extra arguments to pass to sftp only (e.g. -f,                            -l)        --scp-extra-args=SCP_EXTRA_ARGS                            specify extra arguments to pass to scp only (e.g. -l)        --ssh-extra-args=SSH_EXTRA_ARGS                            specify extra arguments to pass to ssh only (e.g. -R)        -u REMOTE_USER, --user=REMOTE_USER                connect as this user (default=None)

连接目标主机使用的用户名
-c CONNECTION, –connection=CONNECTION
connection type to use (default=smart)
连接主机的方式
Privilege Escalation Options:权限升级选项
-s, –sudo run operations with sudo (nopasswd) (deprecated, use
become)
-U SUDO_USER, –sudo-user=SUDO_USER
desired sudo user (default=root) (deprecated, use
become)
-S, –su run operations with su (deprecated, use become)
-R SU_USER, –su-user=SU_USER
run operations with su as this user (default=root)
(deprecated, use become)
-b, –become run operations with become (does not imply password
prompting)
–become-method=BECOME_METHOD
privilege escalation method to use (default=sudo),
valid choices: [ sudo | su | pbrun | pfexec | doas |
dzdo | ksu | runas ]
–become-user=BECOME_USER
run operations as this user (default=root)
–ask-sudo-pass ask for sudo password (deprecated, use become)
–ask-su-pass ask for su password (deprecated, use become)
-K, –ask-become-pass
ask for privilege escalation password
ansible-dos
-a, –all Show documentation for all modules
显示所有的模块
-l, –list List available modules
列出所有可用的模块 ansible-doc -l
-s, –snippet Show playbook snippet for specified module(s)
列出指定模块的使用方法 ansible-doc -s acl

-h, –help show this help message and exit

-M MODULE_PATH, –module-path=MODULE_PATH
specify path(s) to module library (default=None)
-v, –verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
–version show program’s version number and exit
模块
ping 模块
探测后端主机是否在线
ansible all -m ping –list-hosts
hosts (3):
192.168.1.130
192.168.1.131
192.168.1.132
ansible all -m ping -C
192.168.1.131 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.132 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.130 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
ansible all -m ping
192.168.1.131 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.130 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.1.132 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

    group 模块

组操作
创建组
ansible-doc -s group
- name: Add or remove groups
action: group
gid # Optional GID' to set for the group.
name= # Name of the group to manage.
state # Whether the group should be present or not on the remote host.
system # If
yes’, indicates that the group created is a system group.
[root@localhost ~]# ansible websrv -m group -a “gid=3000 name=mygrp state=present system=no”
192.168.1.131 | SUCCESS => {
“changed”: true,
“gid”: 3000,
“name”: “mygrp”,
“state”: “present”,
“system”: false
}
192.168.1.132 | SUCCESS => {
“changed”: true,
“gid”: 3000,
“name”: “mygrp”,
“state”: “present”,
“system”: false
}

        删除组            ansible websrv  -m group  -a "gid=3000 name=mygrp state=absent"            [root@localhost ~]# ansible websrv  -m group  -a "gid=3000 name=mygrp state=absent" -C                   

192.168.1.132 | SUCCESS => {
“changed”: true
}
192.168.1.131 | SUCCESS => {
“changed”: true
}
[root@localhost ~]# ansible websrv -m group -a “gid=3000 name=mygrp state=absent”
192.168.1.131 | SUCCESS => {
“changed”: true,
“name”: “mygrp”,
“state”: “absent”
}
192.168.1.132 | SUCCESS => {
“changed”: true,
“name”: “mygrp”,
“state”: “absent”
}

    user 模块

用户操作
创建用户
[root@localhost ~]# ansible websrv -m user -a “uid=5000 name=testuser state=present groups=mygrp shell=/bin/tcsh”
192.168.1.131 | SUCCESS => {
“changed”: true,
“comment”: “”,
“createhome”: true,
“group”: 5000,
“groups”: “mygrp”,
“home”: “/home/testuser”,
“name”: “testuser”,
“shell”: “/bin/tcsh”,
“state”: “present”,
“system”: false,
“uid”: 5000
}
192.168.1.132 | SUCCESS => {
“changed”: true,
“comment”: “”,
“createhome”: true,
“group”: 5000,
“groups”: “mygrp”,
“home”: “/home/testuser”,
“name”: “testuser”,
“shell”: “/bin/tcsh”,
“state”: “present”,
“system”: false,
“uid”: 5000
}

    copy 模块

复制文件
如果源时目录时,默认进行递归复制.如果源路径以/ 结尾代表的是该目录下的所有文件,等价与dir/*
用法:
(1) src=源路径 dest= 目标路径
remote-src=远程主机的源地址
(2) content=”生成目标文本文件的内容” dest=生成的目标文件
owner属主, group属组, mode权限
[root@localhost ~]# ansible websrv -m copy -a “src=/etc/fstab dest=/tmp/fstab mode=600” -C
192.168.1.132 | SUCCESS => {
“changed”: true,
“dest”: “/tmp/fstab”,
“src”: “/etc/fstab”
}
192.168.1.131 | SUCCESS => {
“changed”: true,
“dest”: “/tmp/fstab”,
“src”: “/etc/fstab”
}
[root@localhost ~]# ansible websrv -m copy -a “src=/etc/fstab dest=/tmp/fstab mode=600”

        ansible websrv -m copy -a "src=/etc/pam.d/ dest=/tmp/"

复制目录

        ansible websrv  -m copy  -a "content='hello d' dest=/tmp/haha.txt" 

ansible websrv -m copy -a “content=’hello d\n’ dest=/tmp/haha.txt”
手动指定文件的内容,但是注意默认不添加换行

    fetch 模块

复制远程主机文件至本机
远程主机无法指定多个
子主题 1
fail_on_missing 远程主机不存在指定文件时,报错退出
command 模块
在远程主机上执行命令,但是不是直接传送至shell,
或者说不会做特殊含义字符解析
子主题 1
chdir
切换至远程主机指定目录下执行
creates
executable
指定执行命令的程序,shell
free_form=
removes
warn
ansible websrv -m command -a “ifconfig”

[root@localhost ~]# ansible websrv -m command -a “chdir=/root mkdir aaa”

        并非是直接调用shell 而是通过ansible去执行,所以,shell 特殊字符无法解释        ansible websrv  -m command -a "echo 'aa' |passwd --stdin testuser excutable=/bin/bash"     shell 模块

在远程主机上调用shell 执行命令
ansible websrv -m shell -a “echo ‘aa’ |passwd –stdin testuser”

    file 模块

创建文件,文件存在则改变属性
创建链接文件:*path= src= state=link
修改属性:path= owner= mode= group=
创建目录:path= state=directory
path= 创建文件的路径
创建目录
ansible websrv -m file -a “path=/tmp/hello.dir state=directory”

        创建文件,失败  使用copy contend为空即可

ansible websrv -m file -a “path=/tmp/hello.txt state=file”

        创建连接文件

ansible websrv -m file -a ” src=/etc/fstab path=/tmp/aaa.link state=link”

    cron 模块

定义任务计划
minute=
day=
month=
weekday=
hour=
job= 执行任务的内容
*name= 计划任务的名称
state= 状态
present:创建
absent:删除
user= 指定用户
创建任务
ansible websrv -m cron -a “minute=*/3 job=’/usr/sbin/update 172.16.0.1 &>/dev/null’” -C

        删除任务

ansible websrv -m cron -a “minute=*/3 job=’/usr/sbin/update 172.16.0.1 &>/dev/null’ state=absent name=none” -C

    yum 模块

安装程序包
name=:程序包名称,可以带版本号;
state=
present, latest 安装
absent 卸载
ansible websrv -m yum -a “name=epel-release state=installed”
service 模块
启动服务
*name= 服务名称
state= 指定状态
started
stopped
restarted
enabled= 是否开机自启
runlevel= 开机自启的启动级别
启动nginx
ansible websrv -m service -a “name=nginx state=started”
停止 nginx
ansible websrv -m service -a “name=nginx state=stopped”
script 模块
将本地脚本复制到远程主机并执行
ansible websrv -m script -a “/tmp/haha.sh”
hostname模块
管理远程主机的主机名称
name=
pip模块
安装python 模块
easy_install 模块
安装Python 模块
setup 模块
获取远程主机的信息
ansible 192.168.1.131 -m setup
template 模块
将文件基于模板处理完成后保存至远程服务器
变量依照远程操作的主机
依赖于 python-jinja2 程序
在文本文件中内嵌由python 实现的代码
Jinja2:
字面量:
字符串:使用单引号或双引号;
数字:整数,浮点数;
列表:[item1, item2, …]
元组:(item1, item2, …)
字典:{key1:value1, key2:value2, …}
布尔型:true/false

    算术运算:        +, -, *, /, //, %, **    比较操作:        ==, !=, >, >=, <, <=    逻辑运算:        and, or, not         *src= 模板文件

*dest= 生成的配置文件
owner=用户
group=组
mode=权限
编辑模板文件
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bind {{ ansible_ens37.ipv4.address }}
进行变量调用 即引用setup 生成的变量
可以调用所有可以调用的变量,playbook,清单中的主机变量,命令行变量等
进行模板调用
- hosts: websrv
remote_user: root
tasks:
- name: redis.conf
template: src=/root/redis.conf.j2 dest=/tmp/redis.conf

        复制模板             ansible-playbook  muban.yaml play books    使用YAML语言进行表示    整个文件即是一个大的键值对    格式        - hosts: websrv 运行指定任务的目标主机

remote_user: root 在远程主机上执行任务的用户
tasks: 任务列表
- name: install redis
yum: name=redis state=latest
- name: start redis
service: name=redis state=started enabled=true
模块格式
(1) action: module arguments
(2) module: arguments

        Handlers:由特定条件触发的任务即指定任务发生了change 触发定义的任务            - hosts: websrv

remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest
- name: copy config file
copy: src=/root/redis.conf dest=/etc/redis.conf owner=redis
notify: restart redis 进行调用,调用为 handlers定义的任务名称
- name: start redis
service: name=redis state=started enabled=true
handlers: 定义特定触发任务
- name: restart redis
service: name=redis state=restarted

        对指定的操作设定标签

当存在相同的标签时,执行所有名称相同的标签
- hosts: websrv
remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest
- name: copy config file
copy: src=/root/redis.conf dest=/etc/redis.conf owner=redis
notify: restart redis
tags: config 设定标签###
- name: start redis
service: name=redis state=started enabled=true
handlers:
- name: restart redis
service: name=redis state=restarted
~

        指定变量 variables:            (1) facts:可直接调用;    注意:可使用setup模块直接获取目标主机的facters;            (2) 用户自定义变量:(a) ansible-playbook命令的命令行中的    -e VARS, --extra-vars=VARS                        (b) 在playbook中定义变量的方法:    vars:    - var1: value1    - var2: value2

变量引用:{{ variable }}
[root@localhost ~]# vim gaga.yaml
- name: install packagedd
- hosts: websrv
remote_user: root
vars:
- key: zhizhi
tasks:
- name: zhizhi
shell: echo {{ key }} >/tmp/asd.txt

            (3) 通过roles传递变量;            (4)使用主机清单传递变量(a) 用户自定义变量    (i) 向不同的主机传递不同的变量;        IP/HOSTNAME  varaiable=value var2=value2    (ii) 向组中的主机传递相同的变量;        [groupname:vars]        variable=value          (b) invertory参数        用于定义ansible远程连接目标主机时使用的参数,而非传递给playbook的变量;            ansible_ssh_host            ansible_ssh_port            ansible_ssh_user            ansible_ssh_pass            ansbile_sudo_pass    命令

ansible-playbook
–syntax-check 检测语法
ansible-playbook –list-hosts
列出运行任务的主机;
–list-tasks
列出执行的任务
-C
空运行,而不真正执行
测试
测试
ansible-playbook –check
只检测可能会发生的改变,但不真正执行操作;
-t 指明运行任务的标签
-e 指明变量
- hosts: websrv
remote_user: root
tasks:
- name: install package
yum: name={{ package }} state=latest

            ansible-playbook  gaga.yaml  -C -e package=lrzsz    运行        安装 redis,并启动            ansible-playbook   fire.yaml  -C        安装 redis,并复制本机配置文件,后重启服务            - hosts: websrv

remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest
- name: copy config file
copy: src=/root/redis.conf dest=/etc/redis.conf owner=redis
notify: restart redis
- name: start redis
service: name=redis state=started enabled=true
handlers:
- name: restart redis
service: name=redis state=restarted
ansible-playbook fire.yaml -C
ansible-playbook fire.yaml
设定标签,并支持性指定任务
- hosts: websrv
remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest
- name: copy config file
copy: src=/root/redis.conf dest=/etc/redis.conf owner=redis
notify: restart redis
tags: config
- name: start redis
service: name=redis state=started enabled=true
handlers:
- name: restart redis
service: name=redis state=restarted
ansible-playbook fire.yaml -C -t config
ansible-playbook fire.yaml -t config
使用变量自带变量
- hosts: websrv
remote_user: root
tasks:
- name: copy file
copy: content= {{ ansible_env }} dest=/tmp/ansibles.txt

            ansible-playbook  haha.yaml -C            ansible-playbook  haha.yaml             当出现[DEPRECATION WARNING]: Using variables for task params is unsafe, especially if the variables come from an external source like facts.

This feature will
be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
更改配置文件 vim /etc/ansible/ansible.cfg
添加参数deprecation_warnings=False
无需重启
模板
条件测试:
为真才执行动作
when语句:在task中使用,jinja2的语法格式
tasks:
- name: install conf file to centos7
template: src=files/nginx.conf.c7.j2
when: ansible_distribution_major_version == “7”
- name: install conf file to centos6
template: src=files/nginx.conf.c6.j2
when: ansible_distribution_major_version == “6”
循环:迭代,需要重复执行的任务;
对迭代项的引用,固定变量名为”item“
而后,要在task中使用with_items给定要迭代的元素列表;
列表方法:
字符串
字典

- name: install some packages  yum: name={{ item }} state=present  with_items:  - nginx  - memcached  - php-fpm- name: add some groups  group: name={{ item }} state=present  with_items:  - group11  - group12  - group13- name: add some users  user: name={{ item.name }} group={{ item.group }} state=present  with_items:  - { name: 'user11', group: 'group11' }  - { name: 'user12', group: 'group12' }  - { name: 'user13', group: 'group13' }角色    默认角色在/etc/ansible/roles下定义,每个角色单独创建一个文件夹

角色文件夹通过 ansible配置文件定义
每个角色,以特定的层级目录结构进行组织:
角色目录/
files/ :存放由copy或script模块等调用的文件;
templates/:template模块查找所需要模板文件的目录;
tasks/:至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含;
handlers/:至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含;
vars/:至少应该包含一个名为main.yml的文件;其它的文件需要在此文件中通过include进行包含;
meta/:至少应该包含一个名为main.yml的文件,定义当前角色的特殊设定及其依赖关系;其它的文件需要在此文件中通过include进行包含;
default/:设定默认变量时使用此目录中的main.yml文件;
将在playbooks中定义的yaml段放在,对应的目录下的main.yaml中
YAML
维基百科
https://zh.wikipedia.org/wiki/YAML
使用了缩进 代替了标签
清单(数组)
习惯上清单比较常用区块格式(block format)表示,也就是用短杠+空白字符作为起始。
— # 最喜愛的電影
- Casablanca
- North by Northwest
- Notorious
另外还有一种内置格式(inline format)可以选择──用方括号围住,并用逗号+空白区隔(类似JSON的语法)
— # 購物清單
[milk, pumpkin pie, eggs, juice]
散列表 (字典)
键值和数据由冒号及空白字符分开。区块形式(常使用与YAML数据文档中)使用缩进和换行符分隔key: value对。内置形式(常使用与YAML数据流中)在大括号中使用逗号+空白字符分隔key: value对。
— # 區塊形式
name: John Smith
age: 33
— # 內置形式
{name: John Smith, age: 33}
区块的字符
再次强调,字符串不需要包在引号之内。有两种方法书写多行文字(multi-line strings),一种可以保存新行(使用|字符),另一种可以折叠新行(使用>字符)。
保存新行(Newlines preserved)

data: | # 譯者注:這是一首著名的五行民謠(limerick)
There once was a man from Darjeeling # 這裡曾有一個人來自大吉嶺
Who got on a bus bound for Ealing # 他搭上一班往伊靈的公車
It said on the door # 門上這麼說的
“Please don’t spit on the floor” # “請勿在地上吐痰”
So he carefully spat on the ceiling # 所以他小心翼翼的吐在天花板上

根据设置,前方的引领空白符号(leading white space)必须排成条状,以便和其他数据或是行为(如示例中的缩进)明显区分。
折叠新行(Newlines folded)

data: >
Wrapped text # 摺疊的文字
will be folded # 將會被收
into a single # 進單一一個
paragraph # 段落

Blank lines denote # 空白的行代表
paragraph breaks # 段落之間的區隔

和保存新行不同的是,换行字符会被转换成空白字符。而引领空白字符则会被自动消去。
混合使用
于清单中使用散列表

  • {name: John Smith, age: 33}
  • name: Mary Smith
    age: 27

于散列表中使用清单

men: [John Smith, Bill Jones]
women:
- Mary Smith
- Susan Williams
数据类型

a: 123 # 整數
b: “123” # 字串(使用雙括號)
c: 123.0 # 浮點數
d: !!float 123 # 浮點數,使用!!表達的嚴格型態
e: !!str 123 # 字串,使用嚴格型態
f: !!str Yes # 字串,使用嚴格型態
g: Yes # 布林值”真”
h: Yes we have No bananas # 字串(包含”Yes”和”No”)
实验
配置远程主机无秘钥
15 ssh-keygen -t rsa -P “”
[root@localhost ~]# 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:
c1:b4:ef:fe:77:03:ac:cb:f7:de:47:f3:44:b6:b4:e2 root@localhost.localdomain
The key’s randomart image is:
+–[ RSA 2048]—-+
| . |
| o . |
| + |
| o .o|
| S …oo|
| . + +o|
| . o ooo|
| … E..=|
| .++.o++|
+—————–+
16 ssh-copy-id -i ./.ssh/id_rsa.pub root@192.168.1.131
[root@localhost ~]# ssh-copy-id -i ./.ssh/id_rsa.pub root@192.168.1.131
The authenticity of host ‘192.168.1.131 (192.168.1.131)’ can’t be established.
ECDSA key fingerprint is 85:e6:78:bd:ed:29:07:7f:0b:1f:8f:77:7c:c0:c2:60.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed – if you are prompted now it is to install the new keys
root@192.168.1.131’s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘root@192.168.1.131’”
and check to make sure that only the key(s) you wanted were added.

           17  ssh-copy-id  -i ./.ssh/id_rsa.pub root@192.168.1.132            [root@localhost ~]# ssh-copy-id  -i ./.ssh/id_rsa.pub root@192.168.1.132

The authenticity of host ‘192.168.1.132 (192.168.1.132)’ can’t be established.
ECDSA key fingerprint is 85:e6:78:bd:ed:29:07:7f:0b:1f:8f:77:7c:c0:c2:60.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed – if you are prompted now it is to install the new keys
root@192.168.1.132’s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘root@192.168.1.132’”
and check to make sure that only the key(s) you wanted were added.
19 ssh-copy-id -i ./.ssh/id_rsa.pub root@192.168.1.130
自己管控自己
[root@localhost ~]# ssh-copy-id -i ./.ssh/id_rsa.pub root@192.168.1.130
The authenticity of host ‘192.168.1.130 (192.168.1.130)’ can’t be established.
ECDSA key fingerprint is 85:e6:78:bd:ed:29:07:7f:0b:1f:8f:77:7c:c0:c2:60.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed – if you are prompted now it is to install the new keys
root@192.168.1.130’s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘root@192.168.1.130’”
and check to make sure that only the key(s) you wanted were added.
主机清单定义
vim /etc/ansible/hosts
直接插入
192.168.1.131
192.168.1.132

        分组定义

使用[]定义标签

        分组中使用序列展开,定义主机名称            [1024]

www[1:7].1024.com
[root@localhost ~]# ansible 1024 –list-host
hosts (7):
www1.1024.com
www2.1024.com
www3.1024.com
www4.1024.com
www5.1024.com
www6.1024.com
www7.1024.com
主机清单定义变量
定义主机连接变量
[dbsrv]
192.168.1.130 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_password=jinbus

            [root@localhost ~]# ansible dbsrv -m ping

192.168.1.130 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

        定义主机组变量            [1024]

www[1:7].1024.com

[1024:vars]
http_port=8080

    基于模板安装httpd        编辑httpd 配置文件模板            [root@localhost ~]# cat listen.conf.j2      

Listen {{ httpd_port }}
编辑 清单主机变量
[root@localhost ~]# tail -15 /etc/ansible/hosts

db-[99:101]-node.example.com

[websrv]
192.168.1.131 httpd_port=10080
192.168.1.132 httpd_port=8080

[dbsrv]
192.168.1.130 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_password=jinbus

[1024]
www[1:7].1024.com

[1024:vars]
http_port=8080
b编辑任务
[root@localhost ~]# cat web_install.yaml
- hosts: websrv
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=installed
- name: cp config
template: src=/root/listen.conf.j2 dest=/etc/httpd/conf.d/listen.conf
- name: start httpd
service: name=httpd state=started
执行
ansible-playbook web_install.yaml
nginx 配置工作核心数,
基于模板
示例:
- hosts: websrvs
remote_user: root
tasks:
- name: install nginx
yum: name=nginx state=present
- name: install conf file
template: src=files/nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
tags: instconf
- name: start nginx service
service: name=nginx state=started
handlers:
- name: restart nginx
service: name=nginx state=restarted

模板配置文件 :nginx.conf.j2worker_processes {{ ansible_processor_vcpus }};listen {{ http_port }};    基于条件判定的安装httpd        - hosts: websrv

remote_user: root
tasks:
- name: yum install
yum: name=httpd state=installed
when: ansible_os_family == “RedHat”
- name: get install
apt: name=apache2 state=installed
when: ansible_os_family == “Debian”

    使用迭代安装程序包        - hosts: websrv

remote_user: root
tasks:
- name: install {{ install }}
yum: name={{ item }} state=latest
with_items:
- nginx
- tomcat
- mariadb-server
- redis

    定义角色安装nginx        进入文件夹            [root@localhost ~]# cd /etc/ansible/roles        创建目录             [root@localhost roles]# mkdir nginx/{tasks,vars,templates,files,handlers} -pv        在/etc/ansible/roles/nginx/tasks/文件夹下创建配置文件 

安装nginx
[root@localhost roles]# vim nginx/tasks/main.yaml
- name: install nginx
yum: name=nginx state=latest
when: ansible_os_family == “RedHat

         再次编辑配置文件

nginx/tasks/main.yaml
添加内容,实现复制模板文件
vim nginx/tasks/main.yaml
- name: install nginx
yum: name=nginx state=latest
when: ansible_os_family == “RedHat”
- name: copy nginx
template: src=vhost1.conf.j2 dest=/etc/nginx/conf.d/vhost1.conf
tags: conf
notify: restart nginx

        在/etc/ansible/roles/nginx/templates 

下创建模板文件(远程主机的配置文件)
server {
listen 80;
server_name {{ ansible_fqdn}};
location / {
root “/nginx/vhost1;
}
}

        在handlers/ 下创建文件

实现,文件变更,自动重启服务
- name: restart nginx
service: name=nginx state=restarted

        向添加 nginx/tasks/main.yml内容

创建目录,及默认主页
- name: home
file: path={{ dir }} state=directory
- name: index
copy: src=index.html dest={{ dir }}/

        在 files 文件夹下添加文件index.html

即主页文件
创建 playbook 文件 ,调用角色
[root@localhost roles]# vim nginx/install_nginx.yaml
- hosts: dbsrv
remote_user: root
roles:
- nginx

原创粉丝点击