ansible
安装ansible
-
查看当前的系统版本
yum install redhat-lsb-core -y [root@localhost httpd]# lsb_release -a LSB Version: :core-4.1-amd64:core-4.1-noarch Distributor ID: CentOS Description: CentOS Linux release 7.3.1611 (Core) Release: 7.3.1611 Codename: Core
-
安装ansible,ansible在epel中
yum install epel-release yum install ansible
-
公钥的分发
ssh-keygen -t rsa -P '' ssh-copy-id -i .ssh/id_rsa.pub root@192.168.99.120
-
测试:
- 尝试登陆被控制节点的主机,ssh root@192.168.99.120,不用输入密码即可登陆
- 为方便测试验证,将master也同样添加入列表
配置文件
-
/etc/ansible/hosts文件中添加主机
-
/etc/ansible/ansible.cfg
命令执行完的结果显示的颜色 [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
- roles目录
ansible命令集
-
ansible
~]# ansible ansible ansible-doc ansible-playbook ansible-vault ansible-console ansible-galaxy ansible-pull
-
ansible-doc命令
- 查看所有模块:ansible-doc -l
- 查看指定模块(command为例)的说明:ansible-doc commond
-
ansible命令
-
帮助:man ansible
ansible <host-pattern> [-m module_name] [-a args] [options] -m NAME, --module-name=NAME #标识模块 Execute the module called NAME. -a 'ARGUMENTS', --args='ARGUMENTS' #标识所使用的参数 The ARGUMENTS to pass to the module.
-
ping模块
ansible srv1 -m ping示例:
[root@localhost ~]# ansible web -m ping 172.16.251.255 | SUCCESS => { "changed": false, "ping": "pong" } 172.16.251.207 | SUCCESS => { "changed": false, "ping": "pong" } 172.16.251.185 | SUCCESS => { "changed": false, "ping": "pong" }
-
command模块
-
shell模块
-
copy模块
ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab2.log' ansible web -m command -a 'md5sum /tmp/fstab2.log' ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab.log.1 owner=stanley group=httpd' ansible web -m copy -a 'src=/etc/fstab dest=/tmp/fstab.log.2 mode=600' ansible web -m shell -a 'ls -l /tmp/fstab*' ansible web -m copy -a 'src=/root/fstab dest=/tmp/fstab.log.1 backup=yes'
-
cron模块
-
创建定时任务
ansible web -m cron -a ‘name=”harddrive check” minute=”15″ hour=”3″ job=”df -lh >> /tmp/df.log”‘ -
查看定时任务
crontab -l -
删除定时任务
ansible web -m cron -a ‘name=”harddrive check” state=absent’
-
创建定时任务
-
fetch模块 #从远程拉一个文件到本地
ansible web -m fetch -a ‘src=/tmp/df.txt dest=/root/’注意:此模块在拉取时无法进行改名,到本地之后的是主机IP地址的目录
[root@localhost ~]# ls 172.16.251.185 172.16.251.255 fstab 172.16.251.207 anaconda-ks.cfg memcache
-
file模块
-
修改文件属性
ansible web -m file -a ‘path=/tmp/df.txt state=touch mode=”600″ owner=stanley group=httpd’ -
创建一个目录
ansible web -m file -a ‘path=/root/file state=directory’
-
修改文件属性
-
hostname模块
-
修改特定主机的主机名
ansible 172.16.251.185 -m hostname -a ‘name=master185’ -
在底层系统不同的基础上使用相同的指令,改变主机名
-
-
yum模块
安装httpd:ansible web -m yum -a ‘name=httpd’
-
service模块
started、stopped、restarted、reloaded enabled=yes
启动httpd:ansible web -m service -a ‘name=httpd state=started’
-
user模块
-
示例:新增一个用户(先创建一个tom组)
user:tom
comment: tom is tom
/home/tomhome/
/bash/zshell
uid = 1066
group = tom
group = wheel~]# ansible web -m user -a 'name=tom comment="tom is tom" uid=1066 group=tom groups=wheel shell=/bin/zshell home=/home/tomhome'
-
查看tom的信息
~]# getent passwd tom tom:x:1066:1002:tom is tom:/home/tomhome:/bin/zshell ~]# getent group tom tom:x:1002:
-
示例:新增一个用户(先创建一个tom组)
-
group模块
ansible web -m group -a 'name=tom'
-
scripts脚本 #将本地的脚本复制到远程主机并在远程主机执行
编辑一个本地脚本,/root/run.sh #!/bin/bash touch /tmp/run.sh.log echo `date` >> /tmp/run.sh.log
~]# ansible web -m script -a '/root/run.sh' 此脚本在传到远程主机的时候会自动执行一次
-
帮助:man ansible
-
ansible-vault命令
-
参数:
- 加密:encrypt
-
解密:decrypt
创建一个文件进行测试;crypt.yml 加密:encrypt ~]# ansible-vault encrypt crypt.yml Vault password: Encryption successful [root@localhost ansible]# cat crypt.yml $ANSIBLE_VAULT;1.1;AES256 37393130653139316462336338643462393636376638326131353231316635666131333833373731 3633356338303963356636353265396133303535636266620a333133343935326362326231666465 62323038653633616135363532313731663363316433663730386430306635346264343135346631 3339336466613334300a366237656561383635633866356634393265313462323630356338623236 6266
解密: [root@localhost ansible]# ansible-vault view crypt.yml Vault password: [root@localhost ansible]# ansible-vault decrypt crypt.yml Vault password: Decryption successful [root@localhost ansible]# cat crypt.yml
-
-
ansible-galaxy命令
~]# ansible-galaxy -h Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...
-
Options:
-h, --help show this help message and exit -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit
- 搜索:ansible-galaxy search nginx
-
安装:ansible-galaxy install nginx
下载的默认路径是/etc/ansible/roles/
-
Options:
-
ansible-console命令(ansible用户交互界面)
root@all (3)[f:5]$ root:当前的执行用户 @: all:当前所处的默认分组的组名 (3):当前的分组中的主机数 [f:5]:当前开启了多少个线程,对远程主机进行任务操作 root@all (3)[f:5]$ ? 列出所有的可用模块 root@all (3)[f:5]$ cd web 切换到web分组 root@web (3)[f:5]$ list web分组的所有主机列表 172.16.251.185 172.16.251.207 172.16.251.255 root@web (3)[f:5]$ forks 10 调整线程数 root@web (3)[f:10]$
-
示例:
root@web (3)[f:10]$ service name=httpd state=restarted root@web (3)[f:10]$ command ls root@web (3)[f:10]$ ls root@web (3)[f:10]$ pwd 卸载httpd root@all (3)[f:5]$ command yum remove httpd -y
-
-
ansible-playbook命令
-
YAML语法
1)首先以“---”(3个减号)开始,且需顶行首写。 2)次行开始正常写Playbook的内容,但笔者一般建议写明该Playbook的功能。 3)使用#号注释代码。 4)缩进必须是统一的,不能空格和tab混用。 5)缩进的级别也必须是一致的,同样的缩进代表同样的级别,程序判别配置的级别是通过缩进结合换行来实现的。 6)YAML文件内容和Linux系统大小写判断方式保持一致,是别大小写的,k/v的值均需大小写敏感。 7)k/v的值可同行写也可换行写。同行使用:分隔,换行写需要以-分隔。 8)一个完整的代码块功能需最少元素需包括 name: task。 9)一个name只能包括一个task。 10)文件名以.yaml和.yml结尾。
-
Playbook的核心元素
Hosts: 运行指定任务的目标主机;可以是:IP地址、hostname、组名 Tasks: 任务列表 Varniables: 变量 Templates: 模板 Handlers: 由特定条件触发的任务 监控资源改变时才会触发改变 Roles: Playbook的按固定目录结构组成 remote_user: 执行用户,通常使用root用户
-
yml格式示例:使用ansible-playbook添加用户
[root@localhost ansible]# vim user.yml --- - hosts: web remote_user: root tasks: - name: user natasha user: name=natasha shell=/bin/bash home=/home/natasha [root@localhost ansible]# ansible-playbook user.yml
-
运行playbook:
Usage: ansible-playbook playbook.yml-
Options:
-
-t TAGS, –tags=TAGS
only run plays and tasks tagged with these values示例: ~]# ansible-playbook web.yml --tags="confighttpd,reloadhttpd"
-
-l SUBSET, –limit=SUBSET
further limit selected hosts to an additional pattern示例: ~]# ansible-playbook web.yml -l 172.16.251.207
-
-t TAGS, –tags=TAGS
-
Options:
-
handlers和tags
示例: - hosts: web remote_user: root tasks: - name: install httpd tags: installhttpd yum: name=httpd state=latest - name: config httpd tags: confighttpd copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/ backup=yes when: ansible_distribution_major_version == "7" notify: restart httpd handlers: - name: restart httpd service: name=httpd state=restarted - name: reload httpd tags: reloadhttpd service: name=httpd state=reloaded
-
playbook变量的使用
-
变量的优先级
命令行 > 主机变量 > 组变量 -
变量来源:
-
Ansible setup中facts到的信息变量可直接使用
示例:ansible web -m setup -
自定义变量
-
主机变量定义
/etc/ansible/hosts [web] 172.16.251.185 hname=master185 172.16.251.207 hname=node207 172.16.251.32 hname=node32 引用变量 ansible调用变量 ~]# ansible web -m hostname -a 'name={{ hname }}' ansible-playbook调用变量 hostname.yml - hosts: web remote_user: root tasks: - name: change hostname to {{ hname }} hostname: name="H{{ hname }}" ~]# ansible-playbook hostname.yml
-
命令行指定变量
Ansible-playbook –e 调用 -
组变量
[svr1:vars] http_port=808 [srv1] 192.168.99.120 http_port=8080 hname=www120 192.168.99.178 http_port=80 hname=www178
-
-
Ansible setup中facts到的信息变量可直接使用
-
Inventory参数(ansible内置变量)
ansible_ssh_host
ansible_ssh_port
ansible_ssh_user
ansible_ssh_pass
ansible_sudo_pass示例:提取本机的hostname变量
[root@Hmaster185 ~]# ansible 172.16.251.207 -m setup | grep hostname "ansible_hostname": "localhost",
-
变量的优先级
-
template
-
功能同copy模块,但是可以实现变量的引用。在.yml文件中定义变量,在.j2文件中引用变量
步骤:
- /etc/ansible/hosts,定义变量
- 服务的配置文件(.j2)。编辑.j2的文件,在.j2文件中引用变量
- ansible-playbook的执行文件(.yml)。编辑.yml文件,在.yml文件中引用.j2文件
- 命令行执行.yml文件
-
-
for循环、if条件判断、when条件判断
示例: 编辑vhostj2.yml文件,(在.yml文件中定义变量) - hosts: web remote_user: root vars: - vports: - 80 - 443 tasks: - name: install httpd yum: name=httpd state=latest - name: config httpd copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/ backup=yes when: ansible_distribution_major_version == "7" - name: reload httpd service: name=httpd state=reloaded 编辑vhost.conf.j2文件 {% for vport in vports %} <VirtualHost> Listen {{ vport }} ServerName {{ ansible_hostname }}.magedu.com DocumentRoot /var/www/html {% if accesslog is not defined %} Accesslog {{ accesslog | default('/var/log/access.log')}} {% endif %} <Directory "/var/www/html/"> Require All granted </Directory> </VirtualHOst> {% endfor %} 执行效果,/etc/httpd/conf.d/vhost.conf <VirtualHost> Listen 80 ServerName Hmaster185.magedu.com DocumentRoot /var/www/html Accesslog /var/log/access.log <Directory "/var/www/html/"> Require All granted </Directory> </VirtualHost> <VirtualHost> Listen 443 ServerName Hmaster185.magedu.com DocumentRoot /var/www/html Accesslog /var/log/access.log <Directory "/var/www/html/"> Require All granted </Directory> </VirtualHost>
-
debug
-
Options:
- msg The customized message that is printed. If omitted, prints a generic message. [Default: Hello world!] - var A variable name to debug. Mutually exclusive with the 'msg' option. [Default: (null)]
vim webj2.yml - name: show message debug: msg={{ ansible_distribution_major_version }} 执行效果:ansible-playbook webj2.yml TASK [show message] ************************************************************ ok: [172.16.251.185] => { "msg": "7" } ok: [172.16.251.207] => { "msg": "7" } ok: [172.16.251.32] => { "msg": "6" }
-
-
with_items
迭代,重复执行的任务,对迭代项的引用,固定变量名为item,而后在task中使用with_items给定迭代的元素列表;示例: - name: Create rsyncd config copy: src={{ item }} dest=/etc/{{ item }} with_items: - rsyncd.secrets - rsyncd.conf
示例: - hosts: mageduweb remote_user: root tasks: - name: add several users user: name={{ item.name }} state=present groups={{ item.groups }} with_items: - { name: 'testuser1' , groups: 'wheel'} - { name: 'testuser2' , groups: 'root'}
-
YAML语法
-
roles
-
实验:使用roles实现httpd的安装配置
[root@Hmaster185 ansible]# mkdir /root/ansible/roles/httpd/{tasks,handlers,templates,files,vars} -pv mkdir: created directory ‘roles/httpd’ mkdir: created directory ‘roles/httpd/tasks’ mkdir: created directory ‘roles/httpd/handlers’ mkdir: created directory ‘roles/httpd/templates’ mkdir: created directory ‘roles/httpd/files’ mkdir: created directory ‘roles/httpd/vars’ vi /root/ansible/roles/httpd/tasks/install.yml --- - name: install httpd yum: name=httpd state=present vi /root/ansible/roles/httpd/tasks/init.yml --- - name: init httpd copy: src=README dest=/etc/httpd/conf/ - name: init vhost.conf template: src=vhost.conf.j2 dest=/etc/httpd/conf.d/vhost.conf vi /root/ansible/roles/httpd/handlers/main.yml --- - name: restart httpd service: name=httpd state=restarted 将需要的资源文件拷贝到指定的目录中 ~]# cp /etc/httpd/conf.d/README files/ ~]# cp /root/ansible/httpd.conf.j2 templates/ 引用tasks中的文件 vi /root/ansible/roles/httpd/tasks/main.yml --- - include: install.yml - include: init.yml 编辑执行的.yml文件 vi /root/ansible/httpdrole.yml --- - hosts: web remote_user: root vars: - vports: - 80 - 443 - 808 roles: - httpd
-
实验:使用roles实现创建用户
创建目录 [root@Hmaster185 roles]# mkdir useradd/{tasks,vars,files,templates,handlers} -pv mkdir: created directory ‘useradd’ mkdir: created directory ‘useradd/tasks’ mkdir: created directory ‘useradd/vars’ mkdir: created directory ‘useradd/files’ mkdir: created directory ‘useradd/templates’ mkdir: created directory ‘useradd/handlers’ vi /root/ansible/useradd/tasks/main.ymml --- - name: mul add user user: name={{ item.name }} groups={{ item.groups }} state=present with_items: - { name: 'tom11' , groups: 'wheel' } - { name: 'tom22' , groups: 'root' } 编辑执行文件的userrole.yml --- - hosts: web remote_user: root roles: - useradd ~]# ansible-playbook userrole.yml
-
实验:使用roles的tags功能
--- - hosts: web remote_user: root vars: - vports: - 80 - 443 - 808 roles: - { role: httpd ,tags: [ 'httpd','web' ] } - { role: useradd ,tags: [ 'useradd','web' ] }
-
原创文章,作者:s,如若转载,请注明出处:http://www.178linux.com/79624