ansible-playbook
1. 基本用法
-e : 指定变量的值 -t : 指定运行的tag
ansible-playbook 中使用变量
cat user.yml
---
# add user
#
- hosts: mytest
remote_user: root
tasks:
- name: add user1
tags: autouser
user: name=user1 system=true uid=307
- name: add user2
tags: manueuser
user: name={{ userx }} uid={{ userid }}
# 在命令行中通过 -e 来指定变量的值
ansible-playbook -e userx=user3 -e userid=1500 user.yml
# 通过 -t 来指定要运行的tags
ansible-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.10
192.168.2.11 http_port=88
192.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: mytest
remote_user: root
vars:
apis:
- api3
- api2
- api1
tasks:
- name: multi server
template: 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: mytest
remote_user: root
tasks:
- name: install app
yum: name={{ item }} state=installed
with_items:
- nginx
- php
- httpd
ansible-playbook /ansible/yml/install_mul.yml
示例2:
---
# add mul user
- hosts: mytest
remote_user: root
tasks:
- name: groupadd
group: name={{ item }}
with_items:
- group5
- group6
- group7
- name: useradd multi
user: name={{ item.u }} group={{ item.g }}
with_items:
- { u: "user5", g: "group5" }
- { u: "user6", g: "group6" }
- { u: "user7", g: "group7" }