ansible-playbook

1. 基本用法

-e : 指定变量的值 -t : 指定运行的tag

ansible-playbook 中使用变量

  1. cat user.yml
  2. ---
  3. # add user
  4. #
  5. - hosts: mytest
  6. remote_user: root
  7. tasks:
  8. - name: add user1
  9. tags: autouser
  10. user: name=user1 system=true uid=307
  11. - name: add user2
  12. tags: manueuser
  13. user: name={{ userx }} uid={{ userid }}
  14. # 在命令行中通过 -e 来指定变量的值
  15. ansible-playbook -e userx=user3 -e userid=1500 user.yml
  16. # 通过 -t 来指定要运行的tags
  17. ansible-playbook -t userauto user.yml

2. template

ansible mytest -m setup # 查看机器信息

2.1 template 中的算术运算

  1. {{ ansible_processor_vcpus-1 }}

2.2 template 中的 for, if, when

使用循环生成多个 nginx server

cat /etc/ansible/hosts

  1. [mytest]
  2. 192.168.2.10
  3. 192.168.2.11 http_port=88
  4. 192.168.2.12 http_port=99

vim nginx_vhost.conf.j2 # 编辑一个模板文件

  1. {% for api_name in apis %}
  2. server {
  3. # 如果定义了http_port,使用定义的端口, 否则使用80.
  4. {% if http_port is defined %}
  5. listen {{ http_port }};
  6. {% else %}
  7. listen 80;
  8. {% endif %}
  9. server_name {{ api_name }}.zlead.com;
  10. root /data/nginx;
  11. location / {}
  12. }
  13. {% endfor %}

接下来, 我们来编辑一个 nginx_vhost.yml

  1. ---
  2. # nginx mulit vhost
  3. - hosts: mytest
  4. remote_user: root
  5. vars:
  6. apis:
  7. - api3
  8. - api2
  9. - api1
  10. tasks:
  11. - name: multi server
  12. template: src=/TEMPLATE_PATH/nginx_vhost.conf.j2 dest=/etc/nginx/conf.d/web_api.conf
  13. # 当系统是 RedHat 时,执行此模板。
  14. when: ansible_os_family == "RedHat"

运行模板, 使配置生效.

  1. ansible-playbook nginx_vhost.yml -C # 通过 -C 来检验配置是否正确
  2. ansible-playbook nginx_vhost.yml

2.3 template 中的多任务

使用 with_items 来配置多个任务

示例1:

cat /ansible/yml/install_mul.yml

  1. ---
  2. # install nginx,httpd,php
  3. - hosts: mytest
  4. remote_user: root
  5. tasks:
  6. - name: install app
  7. yum: name={{ item }} state=installed
  8. with_items:
  9. - nginx
  10. - php
  11. - httpd

ansible-playbook /ansible/yml/install_mul.yml

示例2:

  1. ---
  2. # add mul user
  3. - hosts: mytest
  4. remote_user: root
  5. tasks:
  6. - name: groupadd
  7. group: name={{ item }}
  8. with_items:
  9. - group5
  10. - group6
  11. - group7
  12. - name: useradd multi
  13. user: name={{ item.u }} group={{ item.g }}
  14. with_items:
  15. - { u: "user5", g: "group5" }
  16. - { u: "user6", g: "group6" }
  17. - { u: "user7", g: "group7" }