ansible

来源:互联网 发布:搜索引擎优化技巧 编辑:程序博客网 时间:2024/04/29 15:49

PlayBook-(1)

 YAML语言介绍

参考链接:http://docs.ansible.com/ansible/YAMLSyntax.html
ansible里面的配置文件是通过YMAL文件来实现的。下面是YMAL语言的特点:
  1. 可读性高
  2. 和脚本语言交互好
  3. 使用的是实现语言的数据类型
  4. 有一个一致的信息模型
  5. 基于流来处理
  6. 表达能力强,可拓展性比较好
YAML语言语法特点:
  •    下面是一个介绍YAML的 小例子:
  1. name: Tom
  2. age: 35
  3. spouce:
  4. name: Tik
  5. age: 34
  6. children:
  7. - name: JK
  8. age: 19
  9. - name: HK
  10. age: 12
        说明:表示Tom今年35岁,有一个幸福的四口之家,妻子叫做Tik,今年34岁;俩孩子JK和HK活泼可爱。
   接下来就把这上面的代码保存成一个test.yaml的文件放到和test.py同级的目录下,并且用python2.7执行即可。
python代码:    
  1. #!/usr/bin/python
  2. import yaml
  3. file = open('test.yaml')
  4. read_file = yaml.load(file)
  5. print read_file
执行结果:会传递出一个字典的格式出来
  1. [root@bogon ~]# python test.py
  2. {'age': 35, 'spouce': {'age': 34, 'name': 'Tik'}, 'name': 'Tom', 'children': [{'age': 19, 'name': 'JK'}, {'age': 12, 'name': 'HK'}]}
  • YAML文件最常见的层次和结构,对应的就是python中的字典和列表两种类型:
    还是用上面的python读取文件的例子来试试,生成列表 
  1. [root@bogon ~]# cat test2.yaml #yaml文件
  2. - apple
  3. - banana
  4. - orange
  5. - pear
  6. [root@bogon ~]# cat test2.py #python文件
  7. #!/usr/bin/python
  8. import yaml
  9. file = open('test2.yaml')
  10. read_file = yaml.load(file)
  11. print read_file
  12. [root@bogon ~]# python test2.py #执行结果
  13. ['apple', 'banana', 'orange', 'pear']
     再来一发玩玩吧:
  1. node_a:
  2. counttime: 300
  3. external:
  4. iface: eth0
  5. port: 5566
  6. internal:
  7. iface: eth1
  8. port: 5577
  9. broadcast:
  10. client: 1000
  11. server: 99
  12. node_b:
  13. 0:
  14. ip: 10.1.1.1
  15. name: b1
  16. 1:
  17. ip: 10.1.1.2
  18. name: b2   
       不行,老哥最后来一发
  1. name: Example Developer
  2. job: DeveLoper
  3. skill: Elipt
  4. employed: True
  5. foods:
  6. - apple
  7. - orange
  8. - mango
  9. language:
  10. ruby: Elit
  11. python: Elit
  12. dotnet: Lame

PlayBook

    需要一个yaml格式的文件编排一个任务去执行。
  • 组成部分(核心元素):
    • hosts
    • users
    • 任务
    • 变量
    • 模板:包含模板语法的文本文件
    • 处理器:有特定条件触发的任务
    • 角色
  • 基本组件:
    • hosts:运行指定任务的目标主机
    • remote_user:远程主机上执行任务的用户
    • sudo_user:可选方式
    • tasks:任务列表
      • 模块,模块参数
      • 格式:
        • action:module arguments
        • module:arguments
  • 简单的小案例:
    •  创建用户的小playbook:
  1. - hosts: all
  2. remote_user: root
  3. tasks:
  4. - name: create a user user3 #任务名称
  5. user: name=user3 system=true uid=307 #执行任务
  6. - name: create a user user4 #任务名称
  7. user: name=user4 system=true uid=308
  • 检查playbook
  1. [root@bogon ~]# ansible-playbook --check first.yaml
  2. PLAY [all] *********************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [create a user user3] *****************************************************
  7. changed: [172.1.1.7]
  8. changed: [172.1.1.12]
  9. TASK [create a user user4] *****************************************************
  10. changed: [172.1.1.7]
  11. changed: [172.1.1.12]
  12. PLAY RECAP *********************************************************************
  13. 172.1.1.12 : ok=3 changed=2 unreachable=0 failed=0
  14. 172.1.1.7 : ok=3 changed=2 unreachable=0 failed=0
  15. [root@bogon ~]# ansible-playbook --list-hosts first.yaml
  16. playbook: first.yaml
  17. play #1 (all): allTAGS: []
  18. pattern: [u'all']
  19. hosts (2):
  20. 172.1.1.12
  21. 172.1.1.7
  • 运行playbook
  1. [root@bogon ~]# ansible-playbook first.yaml #执行
  2. PLAY [all] *********************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.12]
  5. ok: [172.1.1.7]
  6. TASK [create a user user3] *****************************************************
  7. changed: [172.1.1.7]
  8. changed: [172.1.1.12]
  9. TASK [create a user user4] *****************************************************
  10. changed: [172.1.1.7]
  11. changed: [172.1.1.12]
  12. PLAY RECAP *********************************************************************
  13. 172.1.1.12 : ok=3 changed=2 unreachable=0 failed=0
  14. 172.1.1.7 : ok=3 changed=2 unreachable=0 failed=0
安装httpd使其监听在8080端口,
      yaml文件如下
  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. - name: copy configure file
  7. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  8. - name: start service
  9. service: name=httpd state=started
  10. - name: execute ss command
  11. shell: ss -tnl | grep 80
      准备好httpd的配置文件:
      测试执行:ansible-playbook --check httpd.yaml
      正式执行:ansible-playbook httpd.yaml
  • handlers:在特定条件下触发条件,重启服务
    • 接收到其他任务的通知时才被触发
  • task:任务的状态在运行后为chenged时,可通过notify通知给相应的handles
    • 通过tags打标签,可以结合ansible-playbook -t 标签名称 yaml文件执行
改变配置文件之后重启httpd服务:
  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. - name: copy configure file
  7. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  8. notify: restart httpd
  9. - name: start service
  10. service: name=httpd state=started
  11. handlers:
  12. - name: restart httpd
  13. service: name=httpd state=restarted
  • tag:打标签机制---通过执行标签对应的任务片段执行对应的task
  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install httpd
  5. yum: name=httpd state=present
  6. tags: insthttpd
  7. - name: copy configure file
  8. copy: src=file/httpd.conf dest=/etc/httpd/conf/httpd.conf
  9. tags: instconf
  10. notify: restart httpd
  11. - name: start service
  12. service: name=httpd state=started
  13. tags: restarthttpd
  14. handlers:
  15. - name: restart httpd
  16. service: name=httpd state=restarted
测试:ansible-playbook --check -t restarthttpd httpd3.yaml
执行:ansible-playbook -t restarthtpd httpd3.yaml
  • variables:变量,只能以字母开头
    • facts:用setup模块来获取facts的;可以直接调用
    • ansible-playbook命令的命令行中的自定义变量
      • -e VARS,--extra-vars=VARS
    • 通过roles也能传递变量
    • Host Inventory:实现想不通的主机传递不同的变量
      • 向不同的主机传递不同的变量:IP/HOSTNAME varrable=value1 value2
      • 向组中的主机传递相同的变量:
        • [groupnames:vars]
                                  variable=value
  • inventory参数:用于定义远程连接目标主机需要的参数,而非传递给playbook的参数
    • ansible_ssh_host
    • ansible_ssh_porty
    • ansible_ssh_pass
    • ansible_ssh_user
    • ansible_sudo_pass
  • 模板:
实现自定义安装软件包{{ pkgnames }}:
  1. - hosts: webservers
  2. remote_user: root
  3. tasks:
  4. - name: install {{ pkgs }}
  5. yum: name={{ pkgs }} state=present
测试:ansible-playbook --check -e pkgs=memcached install_var.yaml 
执行:ansible-playbook -e pkgs=memcached install_var.yaml
实现自定义修改主机名的操作:
1. 首先修改/etc/ansbile/hosts文件:
  1. [root@bogon ~]# vim /etc/ansible/hosts
  2. [webservers]
  3. 172.1.1.12 hname=www1
  4. 172.1.1.7 hname=www2
2.其次编写hostname.yaml文件
  1. [root@bogon ~]# vim hostname.yaml
  2. - hosts: webservers remote_user: root tasks: - name: set hostname hostname: name={{ hname }}
3.测试: ansible-playbook --check hostname.yaml 
4.执行: ansible-playbook hostname.yaml 

playbook-(2)

playbook的其他元素

变量

  • 变量:一定要记得{{ varname }}
    • ansible facts
    • ansible-playbook -e "var=value"
      • host variable: host inventory
      • group variable:
                                [groupname:vars]
                                var=value
  • roles
  • 变量的调用:{{ variable }}

模板(templates

  • 文本文件,嵌套有脚本(使用模板编程语言编写)
  • jinjs2:基于Python
    • 字面量:
      • 字符串:使用单引号或者双引号
      • 数字:整数和浮点数
      • 列表
      • 元组
      • 字典
      • 布尔值
    • 算术运算:+    -    *     /           //      %       **n
    • 比较操作:==     !=           >              <                         >=                       <=
    • 逻辑运算:and           or                    not
  • template模块:基于模板的方式生成一个文件复制到远程主机
    • *src:jinjia2文件路径(server端)
    • *dest:客户端文件存放路径
获取虚拟CPU数量:
  1. [root@bogon ~]# ansible all -m setup | grep ansible_processor_vcpus
  2. "ansible_processor_vcpus": 1,
  3. "ansible_processor_vcpus": 1,

nginx使用epel源安装实例:
        1.在主控端下载好nginx的epel文件:
  1. [root@bogon ~]# cat nginx.repo
  2. [nginx]
  3. name=nginx repo
  4. baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
  5. gpgcheck=0
  6. enabled=1
        2.然后epel文件推送到被控端
  1. [root@bogon ~]# ansible all -m copy -a "src=~/nginx.repo dest=/etc/yum.repos.d/"
        3.主控端执行安装命令
  1. [root@bogon ~]# ansible all -m yum -a "name=nginx state=present"
       4.配置文件模板推送
                * 远程复制一个nginx.conf配置文件来当做模板文件,并重命名
  1. [root@bogon ~]# scp 172.1.1.12:/etc/nginx/nginx.conf ./
  2. nginx.conf 100% 643 0.6KB/s 00:00
  3. [root@bogon ~]# mv nginx.conf nginx.conf.j2
                *编辑模板文件:
  1. [root@bogon ~]# egrep -v "^#|^$" nginx.conf.j2 user nginx;worker_processes {{ ansible_processor_vcpus }};events { worker_connections 1024;}http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on;server { listen {{ http_port }}; server_name localhost; charset koi8-r; location / { root /usr/share/nginx/html; index index.html index.htm; }}}
                 *编辑hosts文件:  
  1. [root@bogon ~]# cat /etc/ansible/hosts
  2. # This is the default ansible 'hosts' file.
  3. #
  4. # It should live in /etc/ansible/hosts
  5. #
  6. # - Comments begin with the '#' character
  7. # - Blank lines are ignored
  8. # - Groups of hosts are delimited by [header] elements
  9. # - You can enter hostnames or ip addresses
  10. # - A hostname/ip can be a member of multiple groups
  11. [webservers]
  12. 172.1.1.12 hname=www1
  13. 172.1.1.7 hname=www2
  14. [webservers:vars]
  15. http_port=8080
    或者写成这样以便区分:
  1. [root@bogon ~]# cat /etc/ansible/hosts
  2. # This is the default ansible 'hosts' file.
  3. #
  4. # It should live in /etc/ansible/hosts
  5. #
  6. # - Comments begin with the '#' character
  7. # - Blank lines are ignored
  8. # - Groups of hosts are delimited by [header] elements
  9. # - You can enter hostnames or ip addresses
  10. # - A hostname/ip can be a member of multiple groups
  11. [webservers]
  12. 172.1.1.12 http_port=80
  13. 172.1.1.7 http_port=8080

                 *编辑yaml文件:
  1. [root@bogon ~]# vim nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. tasks:
  5. - name: install nginx
  6. yum: name=nginx state=present
  7. - name: install conf file
  8. template: src=~/nginx.conf.j2 dest=/etc/nginx/nginx.conf
  9. notify: restart nginx
  10. tags: instconf
  11. - name: start nginx service
  12. service: name=nginx state=started
  13. handlers:
  14. - name: restart nginx
  15. service: name=nginx state=restarted
                    *检测执行:
  1. [root@bogon ~]# ansible-playbook --check nginx.yaml
  2. PLAY [webservers] **************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [install nginx] ***********************************************************
  7. ok: [172.1.1.7]
  8. ok: [172.1.1.12]
  9. TASK [install conf file] *******************************************************
  10. ok: [172.1.1.7]
  11. ok: [172.1.1.12]
  12. TASK [start nginx service] *****************************************************
  13. changed: [172.1.1.7]
  14. changed: [172.1.1.12]
  15. PLAY RECAP *********************************************************************
  16. 172.1.1.12 : ok=4 changed=1 unreachable=0 failed=0
  17. 172.1.1.7 : ok=4 changed=1 unreachable=0 failed=0
    没有报错的话就直接执行:ansible-playbook nginx.yaml
  • 条件判断:
    • when语句:在task中使用,jinja2语法格式
    • tasks格式如下:
  1. tasks:
  2. - name: install conf to centos7
  3. templete: src=~/nginx.c7.j2 dest=/etc/nginx/
  4. when: ansible_distribution_major_version == "7"
  5. - name: install conf to centos7
  6. templete: src=~/nginx.c6.j2 dest=/etc/nginx/
  7. when: ansible_distribution_major_version == "6"
根据操作系统的不同来配置和推送不同的配置文件:
       *根据不同的操作系统拉取不同的配置文件:
  1. [root@bogon ~]# scp 172.1.1.7:/etc/nginx/nginx.conf ./nginx.conf.c6.j2
  2. nginx.conf 100% 700 0.7KB/s 00:00
  3. [root@bogon ~]# scp 172.1.1.12:/etc/nginx/nginx.conf ./nginx.conf.c7.j2
  4. nginx.conf 100% 702 0.7KB/s 00:00
       *调整nginx.conf.c6.j2的配置文件;仍然要修改其worker_processor 对应的变量为:
worker_processes {{ ansible_processor_vcpus }};
listen {{ http_port }};
*调整nginx.yaml配置:
  1. [root@bogon ~]# vim nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. tasks:
  5. - name: install nginx
  6. yum: name=nginx state=present
  7. - name: install conf file
  8. template: src=~/nginx.conf.c7.j2 dest=/etc/nginx/nginx.conf
  9. when: ansible_distribution_major_version == "7"
  10. notify: restart nginx
  11. tags: instconf
  12. - name: install conf file
  13. template: src=~/nginx.conf.c6.j2 dest=/etc/nginx/nginx.conf
  14. when: ansible_distribution_major_version == "6"
  15. notify: restart nginx
  16. tags: instconf
  17. - name: start nginx service
  18. service: name=nginx state=started
  19. handlers:
  20. - name: restart nginx
  21. service: name=nginx state=restarted
*执行检查程序:ansible-playbook --check nginx.yaml
*无报错开始执行程序:ansible-playbook nginx.yaml
  • 循环:迭代操作,需要执行重复执行的任务
    • 对叠带项的引用,固定变量名为"item"
    • 而后,要在task中使用with_items给定要迭代的元素列表
    • with_items的形式有两种:
      • 列表方法
      • 字典方法
事例:
  1. - name: install some package
  2. yum: name={{ items }} state=present
  3. with_items:
  4. - nginx
  5. - memcached
  6. - php-fpm
迭代安装程序事例:
        *编写yaml文件:
  1. - host: all
  2. remote_user: root
  3. tasks:
  4. - name: install some packages
  5. yum: name={{ item }} state=present
  6. with_items:
  7. - nginx
  8. - memcached
  9. - php-fpm
       开始测试:ansible-playbook --check loop_test.yaml
       执行任务:ansible-playbook loop_test.yaml
迭代创建用户和组,并进行关联(with_items的形式有两种的具体应用)
       *编写yaml文件:
  1. [root@bogon ~]#vim with_items.yaml
  2. - host: all
  3. remote_user: root
  4. tasks:
  5. - name: add some groups
  6. group: name={{ item }} state=present
  7. with_items:
  8. - group11
  9. - group12
  10. - group13
  11. - name: add some users
  12. user: name={{ item.name }} group={{ item.group }} state=present
  13. with_items:
  14. - { name: 'user11',group: 'group11' }
  15. - { name: 'user11',group: 'group11' }
  16. - { name: 'user11',group: 'group11' }
        *测试执行:ansible-playbook --check with_items.yaml
*无报错最终执行:ansible-playbook with_items.yaml

playbook-(3)

角色

  •   在网络中的主机如果要协调的过程,实现不同的分组之间的公共任务的执行,以减少重复执行。比如时间同步;
  •    每一个角色就是一个目录;
   (1): 角色的集合:
  
  1. roles/
  2. mysql/
  3. httpd/
  4. nginx/
  5. memcached/
   (2):  每个角色,以特定的层级目录结构进行组织
  1. mysql/
  2. files/ #存放由copy或者script模块等调用的文件
  3. templates/ #template模块查找所需要的模板文件位置
  4. tasks/ #至少包含一个main.yaml文件,其他文件的执行需要通过include包含
  5. handlers/ #至少包含一个main.yaml的文件,其他文件的执行需要通过include包含
  6. vars/ #至少包含一个main.yaml的文件,其他文件的执行需要通过include包含
  7. meta/ #至少包含一个main.yaml的文件,定义当前角色的特殊设定及其依赖关系
  8. default/ #设定默认变量时使用此目录中的main.yaml文件

 (3): 在playbook中调用角色:通过roles指定的任务,然后从上面的两个对应的角色集合中找到自己的角色和对应的任务进行执行           
  1. - hosts: webservers
  2. remoute_user: root
  3. roles:
  4. - mysql
  5. - ngins
  6. - memcached
  7. - redis

  实例:创建一个nginx实例

(1)task文件
  1. [root@bogon ~]# mkdir /etc/ansible/roles/nginx/{files,tasks,templates,handlers,vars,default,meta} -pv
  2. [root@bogon ~]# cd /etc/ansible/roles/nginx/
  3. [root@bogon nginx]# vim tasks/main.yaml
  4. - name: install nginx package
  5. yum: name=nginx state=present
  6. - name: install conf file
  7. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  8. - name: start nginx
  9. service: name=nginx state=started enabled=true
(2)templates文件
  1. [root@bogon ~]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user nginx;
  3. worker_processes {{ ansible_processor_vcpus }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }
(3)写一个role文件
  1. [root@bogon ~]# mkdir /ansible
  2. [root@bogon ansible]# vim nginx.yaml
  3. - hosts: webservers
  4. remote_user: root
  5. roles:
  6. - nginx
(4)删除被控主机的nginx服务和配置
  1. [root@www1 ~]# rpm -e nginx
  2. warning: /etc/nginx/nginx.conf saved as /etc/nginx/nginx.conf.rpmsave
  3. warning: file /etc/nginx/conf.d/default.conf: remove failed: No such file or directory
  4. [root@www1 ~]# rm -fr /etc/nginx/
  5. [root@www1 ~]# rpm -e nginx
  6. error: package nginx is not installed
(5)测试和执行
  1. [root@bogon ~]# cd /ansible/
  2. [root@bogon ansible]# ansible-playbook --check nginx.yaml #测试
  3. [root@bogon ansible]# ansible-playbook nginx.yaml #执行
(6)触发器的创建 
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/handlers/main.yaml
  2. - name: restart nginx
  3. service: name=nginx state=restarted
(7)tasks创建通知
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/tasks/main.yaml
  2. - name: install nginx package
  3. yum: name=nginx state=present
  4. - name: install conf file
  5. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  6. notify: restart nginx
  7. - name: start nginx
  8. service: name=nginx state=started enabled=true
(8)模拟配置文件发生改变(修改j2文件
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user nginx;
  3. worker_processes {{ ansible_processor_vcpus-1 }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }
(9)测试和执行
  1. [root@bogon ~]# cd /ansible/
  2. [root@bogon ansible]# ansible-playbook --check nginx.yaml #测试
  3. [root@bogon ansible]# ansible-playbook nginx.yaml #执行

添加通知

(1)修改tasks配置
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/tasks/main.yaml
  2. - name: install nginx package
  3. yum: name=nginx state=present
  4. - name: install conf file
  5. template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  6. notify: restart nginx
  7. tags: instconf
  8. - name: start nginx
  9. service: name=nginx state=started enabled=true
(2)测试和执行
  1. [root@bogon ~]# cd /ansible/
  2. [root@bogon ansible]# ansible-playbook -t instconf --check nginx.yaml #测试
  3. [root@bogon ansible]# ansible-playbook -t instconf nginx.yaml #执行

var变量的使用

  1. [root@bogon ansible]# vim /ansible/useradd.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. vars:
  5. - groupname: testgroup1
  6. - username: testuser1
  7. tasks:
  8. - name: create group
  9. group: name={{ groupname }} state=present
  10. - name: create user
  11. user: name={{ username }} state=present
       测试和执行
  1. [root@bogon ~]# cd /ansible/
  2. [root@bogon ansible]# ansible-playbook -t instconf --check useradd.yaml #测试
  3. [root@bogon ansible]# ansible-playbook -t instconf useradd.yaml #执行

在playbook中定义变量的方式:

还是结合上述的ngin实例:
(1)定义vars变量文件
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/vars/main.yaml
  2. username: daemon
(2)修改j2文件:
  1. [root@bogon ansible]# vim /etc/ansible/roles/nginx/templates/nginx.conf.j2
  2. user {{ username }};
  3. worker_processes {{ ansible_processor_vcpus-1 }};
  4. events {
  5. worker_connections 1024;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. sendfile on;
  15. #tcp_nopush on;
  16. keepalive_timeout 65;
  17. #gzip on;
  18. server {
  19. listen {{ http_port }};
  20. server_name localhost;
  21. charset koi8-r;
  22. location / {
  23. root /usr/share/nginx/html;
  24. index index.html index.htm;
  25. }
  26. }
  27. }
(3)测试和执行
  1. [root@bogon ~]# cd /ansible/
  2. [root@bogon ansible]# ansible-playbook -t instconf --check nginx.yaml #测试
  3. [root@bogon ansible]# ansible-playbook -t instconf nginx.yaml #执行在

在playbook中调用角色的方法:

(1)在playbook中调用角色:通过roles指定的任务,然后从上面的两个对应的角色集合中找到自己的角色和对应的任务进行执行           
  1. - hosts: webservers
  2. remoute_user: root
  3. roles:
  4. - mysql
  5. - ngins
  6. - memcached
  7. - redis
(2)通过变量指明方法:其中键role用于指定角色名称;后续的k/v用于传递变量给角色
                                            还可以基于条件测试实现角色调用,
  1. - hosts: webservers
  2. remote_user: root
  3. roles:
  4. - { role: nginx,username :nginx }
第二种方法的实例(不指定条件):
  1. [root@bogon ~]# vim /ansible/nginx.yaml
  2. - hosts: webservers
  3. remote_user: root
  4. roles:
  5. - { role: nginx,username :nginx }
执行程序:
  1. [root@bogon ~]# ansible-playbook --check nginx.yaml #执行
  2. PLAY [webservers] **************************************************************
  3. TASK [setup] *******************************************************************
  4. ok: [172.1.1.7]
  5. ok: [172.1.1.12]
  6. TASK [install nginx] ***********************************************************
  7. ok: [172.1.1.7]
  8. ok: [172.1.1.12]
  9. TASK [install conf file] *******************************************************
  10. ok: [172.1.1.7]
  11. ok: [172.1.1.12]
  12. TASK [start nginx service] *****************************************************
  13. ok: [172.1.1.7]
  14. ok: [172.1.1.12]
  15. PLAY RECAP *********************************************************************
  16. 172.1.1.12 : ok=4 changed=0 unreachable=0 failed=0
  17. 172.1.1.7 : ok=4 changed=0 unreachable=0 failed=0
  18. [root@bogon ~]# ansible all -m shell -a "ps -ef | grep nginx" #返回结果
  19. 172.1.1.7 | SUCCESS | rc=0 >>
  20. root 10412 1 0 10:21 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
  21. nginx 10414 10412 0 10:21 ? 00:00:00 nginx: worker process
  22. root 12949 12948 0 11:00 pts/1 00:00:00 /bin/sh -c ps -ef | grep nginx
  23. root 12951 12949 0 11:00 pts/1 00:00:00 grep nginx
  24. 172.1.1.12 | SUCCESS | rc=0 >>
  25. root 4080 1 0 18:06 ? 00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
  26. nginx 4081 4080 0 18:06 ? 00:00:00 nginx: worker process
  27. root 5013 5008 0 18:54 pts/2 00:00:00 /bin/sh -c ps -ef | grep nginx
  28. root 5015 5013 0 18:54 pts/2 00:00:00 grep nginx
第二种方法的实例(指定条件)
  1. - hosts: webservers
  2. remote_user: root
  3. roles:
  4. - { role: nginx,username: nginx,when:"ansible_distribution_major_version == '7'" }按条件安装
按条件安装memcached软件:
创建角色:
  1. [root@bogon ~]# mkdir -pv /etc/ansible/roles/memcached/tasks
  2. [root@bogon tasks]# cd /etc/ansible/roles/memcached
  3. [root@bogon memcached]# vim tasks/main.yaml
  4. - name: install package
  5. yum: name=memcached state=present
  6. - name: start memcached
  7. service: name=memcached state=started enabled=true
创建执行入口文件
  1. [root@bogon memcached]# cd /ansible/
  2. [root@bogon memcached]# vim nginx_memcached.yaml
  3. - hosts: all
  4. remote_user: root
  5. roles:
  6. - { role: nginx, when: ansible_distribution_major_version == '7' }
  7. - { role: memcached, when: ansible_hostname == 'memcached' }
模板文件的创建:
  1. [root@bogon ansible]# cd /etc/ansible/roles/memcached/
  2. [root@bogon memcached]# mkdir templates
  3. [root@bogon memcached]# scp 172.1.1.7:/etc/sysconfig/memcached ./templates/
  4. [root@bogon memcached]# vim templates/memcached
  5. PORT="11211"
  6. USER="memcached"
  7. MAXCONN="1024"
  8. CACHESIZE="{{ ansible_memtotal_mb//4 }}"
  9. OPTIONS=""
  10. [root@bogon memcached]# cd templates/
  11. [root@bogon templates]# mv memcached memcached.j2
再次修改角色文件:
  1. [root@bogon templates]# vim ../tasks/main.yaml
  2. - name: install package
  3. yum: name=memcached state=present
  4. - name: install conf
  5. template: src=memcached.j2 dest=/etc/sysconfig/memcached
  6. notify: restart memcached
  7. tags: memconf
  8. - name: start memcached
  9. service: name=memcached state=started enabled=true
创建handlers文件:
  1. [root@bogon memcached]# mkdir handlers
  2. [root@bogon memcached]# vim handlers/main.yaml
  3. - name: restart memched
  4. service: name=memcached state=restarted
执行测试:
  1. [root@bogon ansible]# ansible-playbook --check nginx_memcached.yaml
  2. [root@bogon ansible]# ansible-playbook -t memconf --check nginx_memcached.yaml
验证:
  1. [root@bogon ansible]# ansible all -m shell -a "cat /etc/sysconfig/memcached"
  2. 172.1.1.7 | SUCCESS | rc=0 >>
  3. PORT="11211"
  4. USER="memcached"
  5. MAXCONN="1024"
  6. CACHESIZE="245"
  7. OPTIONS=""
站点:www.ansible.com.cn





原创粉丝点击