ansible 中的playbook剧本模块使用

playbook支持的文件为.yml格式,也支持字典方式key:value 和列表格式 -abc   支持的文件格式为yml yaml

对格式要求比较严格:

1.冒号后面必须有空格

2.等号后面不能有空格

3. -后面也要有空格

为了灵活使用.yml配置文件,一般会采用模板输出方式取值

- hosts :web

  tasks:

  - name:creat{{ user }}

  user:name={{ user }}

[{hosts:web}, {task:[name:creat{{ user }},user:name={{ user }}]}]

----------------------------------------------------------------------------------------------------------

传参方式:

第一种:ansible-playbook -e 'user=kevin' p1.yml

第二种直接在ansible配置文件中设置

[web]

192.168.1.112  user=kevin

192.168.1.112  user=lisa

 第三种传参方式:

[web:vars]  表示组的参数

user=Kevin 

第四种传参方式:

- hosts :web

   vars:

 - name:creat{{ user }}

 user:name={{ user }}

第五种传参方法:

- hosts :web

   tasks:

 - name:sum

 shell:echo 7+8|bc

 register:user

 - name:createuser

 user:name={{ user.stdout }}

如果采用语句传参的方式,则优先级高于playbook中的配置

ansible-playbook -e 'user=kevin17' p1.yml       则执行结果是user=kevin17

传递参数的优先级:-e playbook varshostswen

----------------------------------------------------------------------------------------

setup信息:(被控机的相关信息)ansible cache -m setup

ansible_all_ipv4_addresses  ipv4的所有地址

ansible_all_ipv6_addresses  ipv6的所有地址

ansible_date_time  获取控制节点的时间

ansible_default_ipv4  默认的ipv4地址

ansible_distribution  系统

ansible_distribution_major_version  系统的大版本

ansible_distribution_version  系统的版本号

ansible_domain  系统所在的域

ansible_env  系统的环境变量

ansible_hostname  系统的主机名

ansible_fqdn  系统的全名

ansible_machine  系统的架构

ansible_memory_mb  系统的内存信息

ansible_os_family  系统的家族

ansible_pkg_mgr  系统的包管理工具

ansible_processor_cores  系统的cpu核数(单颗数)

ansible_processor_count  cpu颗数

ansible_processor_vcpus  处理器的总数量

ansible cache -m setup -a 'filter=*processor*'  模糊查询

--------------------------------------------------------------------------------------------

条件判断:

- hosts:web

  remote_user: root

  tasks:

  - name: createfile

    copy: content="碧玉妆成一树高" dest=/tmp/a.txt

    when: a="2"

  - name: createfile

  copy: content="万条垂下绿丝绦" dest=/tmp/a.txt

  when: a="3"

---------------------------------------------------------------------------------

循环with_item:

一次性创建多个

- hosts: gb

  tasks:

  - name: gbqc

    dong:{{ item }}

 with_items:

 - qbqc

 - cyf

 - ssfj

 -----------------------------------------------------------------------

嵌套循环:

- hosts: web

  tasks:

  - name:creategroup

    group: name={{ item }}

 with_items:

 - lisa1

 - lisa2

 - lisa3

  - name:createuser

  user: name={{ item.name }} group={{ item.group }}

  with_items:

  - {'name':kevin1,'group':lisa1}

     - {'name':kevin2,'group':lisa2}

     - {'name':kevin3,'group':lisa3}

语法检测:ansible-playbook --syntax-check t1.yml  

运行脚本:ansible-playbook t1.yml