ansible-playbook
1. 基本用法
-e : 指定变量的值 -t : 指定运行的tag
ansible-playbook 中使用变量
cat user.yml---# add user#- hosts: mytestremote_user: roottasks:- name: add user1tags: autouseruser: name=user1 system=true uid=307- name: add user2tags: manueuseruser: name={{ userx }} uid={{ userid }}# 在命令行中通过 -e 来指定变量的值ansible-playbook -e userx=user3 -e userid=1500 user.yml# 通过 -t 来指定要运行的tagsansible-playbook -t userauto user.yml
2. template
ansible mytest -m setup # 查看机器信息
2.1 template 中的算术运算
{{ ansible_processor_vcpus-1 }}
2.2 template 中的 for, if, when
使用循环生成多个 nginx server
cat /etc/ansible/hosts
[mytest]192.168.2.10192.168.2.11 http_port=88192.168.2.12 http_port=99
vim nginx_vhost.conf.j2 # 编辑一个模板文件
{% for api_name in apis %}server {# 如果定义了http_port,使用定义的端口, 否则使用80.{% if http_port is defined %}listen {{ http_port }};{% else %}listen 80;{% endif %}server_name {{ api_name }}.zlead.com;root /data/nginx;location / {}}{% endfor %}
接下来, 我们来编辑一个 nginx_vhost.yml
---# nginx mulit vhost- hosts: mytestremote_user: rootvars:apis:- api3- api2- api1tasks:- name: multi servertemplate: src=/TEMPLATE_PATH/nginx_vhost.conf.j2 dest=/etc/nginx/conf.d/web_api.conf# 当系统是 RedHat 时,执行此模板。when: ansible_os_family == "RedHat"
运行模板, 使配置生效.
ansible-playbook nginx_vhost.yml -C # 通过 -C 来检验配置是否正确ansible-playbook nginx_vhost.yml
2.3 template 中的多任务
使用
with_items来配置多个任务
示例1:
cat /ansible/yml/install_mul.yml
---# install nginx,httpd,php- hosts: mytestremote_user: roottasks:- name: install appyum: name={{ item }} state=installedwith_items:- nginx- php- httpd
ansible-playbook /ansible/yml/install_mul.yml
示例2:
---# add mul user- hosts: mytestremote_user: roottasks:- name: groupaddgroup: name={{ item }}with_items:- group5- group6- group7- name: useradd multiuser: name={{ item.u }} group={{ item.g }}with_items:- { u: "user5", g: "group5" }- { u: "user6", g: "group6" }- { u: "user7", g: "group7" }
