ansible模块介绍--day02

命令模块

  • command
# 默认模块, 执行命令
[root@m01 ~]# ansible web_group -a "hostname"
  • shell
# 如果需要一些管道操作,则使用shell
[root@m01 ~]# ansible web_group -m shell -a "ps -ef|grep nginx" -f 50
  • script
# 编写脚本
[root@m01 ~]# vim /root/yum.sh
#!/usr/bin/bash
yum install -y vsftpd

#在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行
[root@m01 ~]# ansible web_group -m script -a "/root/yum.sh"

软件管理模块

  • yum
[root@m01 ~]# ansible web_group -m yum -a "name=httpd state=present"
name                            
    httpd                       #指定要安装的软件包名称
    file://                     #指定本地安装路径(yum localinstall 本地rpm包)
    http://                     #指定yum源(从远程仓库获取rpm包)
    
state                           #指定使用yum的方法
    installed,present           #安装软件包
    removed,absent              #移除软件包
    latest                      #安装最新软件包
    

[root@m01 ~]# ansible-doc yum
exclude=kernel*,foo*            #排除某些包
list=ansible                    #类似于yum list查看是否可以安装
disablerepo="epel,ol7_latest"   #禁用指定的yum仓库
download_only=true              #只下载不安装 yum install d
  • yum_repository
#添加yum仓库
[root@m01 ~]# ansible web_group -m yum_repository -a "name=zls_epel description=EPEL baseurl=https://download.fedoraproject.org/pub/epel/$releasever/$basearch/" -i ./hosts

#仓库名和配置文件名不同
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=zls_epel description=EPEL file=test_zls baseurl=https://download.fedoraproject.org/pub/base/$releasever/$basearch/ gpgcheck=no' -i ./hosts

#添加mirrorlist
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=zls_epel description=EPEL file=test_zls baseurl=https://download.fedoraproject.org/pub/base/$releasever/$basearch/ gpgcheck=no mirrorlist=http://mirrorlist.repoforge.org/el7/mirrors-rpmforge enabled=no' -i ./hosts

#删除yum仓库及文件
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=zls_epel file=test_zls state=absent' -i ./hosts

#开起gpgcheck
[root@m01 ~]# ansible web_group -m yum_repository -a 'name=zls_epel description=EPEL file=test_zls baseurl=https://download.fedoraproject.org/pub/base/$releasever/$basearch/ gpgcheck=yes gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7' -i ./hosts

name        #指定仓库名,如果没有file则为仓库文件名
baseurl     #指定yum源
gpgcheck    #指定检查秘钥
    no
    yes

enabled     #是否启用仓库
    no
    yes

ansible文件管理模块

  • copy
[root@m01 ~]# ansible backup -m copy -a 'src=/root/zls_xxx.conf dest=/etc/rsyncd.conf owner=root group=root mode=0644'

src:指定源文件位置(管理机上的文件)
dest:指定你要推送到主机的目标位置
owner:指定属主
group:指定属组
mode:指定权限
backup:是否备份,第一次推,没有每份,对端机器存在该文件,并且内容不一致,才会做备份
	yes:推送之前,先备份目标主机的源文件
	no:不备份
remote_src:源文件是否在远端的机器上
	yes:是
	no:否
content:往指定目标文件中写入内容
  • file

作用:

  • 授权
  • 创建目录
  • 创建文件
  • 创建软连接
  • 删除目录,文件,软连接
[root@m01 ~]# ansible all -m file -a 'path=/opt/test/zls owner=www group=www mode=0722 state=directory'
[root@m01 ~]# ansible all -m file -a 'path=/code owner=www group=www recurse=yes'

path:指定文件或目录的路径
owner:指定属主
group:指定数组
mode:指定权限
src:做 软/硬 链接的时候使用,指定源文件
recurse:是否递归授权
	yes:递归授权
	no:仅授权当前目录
state:
	directory:创建目录
	touch:创建文件
	link:做软链接
	hard:做硬链接
	absent:删除
	file:配合 modification_time  access_time  修改文件的属性,stat
  • get_url

类似于:wget

[root@m01 ~]# ansible backup -m get_url -a 'url=http://test.driverzeng.com/Nginx_File/nginx.txt dest=/root checksum=md5:8f8dd0f79bc6ef2148ca3494070a86a1'

url:指定下载文件的地址
dest:指定下载的路径
mode:指定权限
checksum:指定加密的算法
	sha256
	md5

ansible服务管理模块

service、systemd

#启动crond并加入开机自启
[root@m01 ~]# ansible web_group -m service -a "name=crond state=started enabled=yes"

#停止crond并删除开机自启
[root@m01 ~]# ansible web_group -m service -a "name=crond state=stoped enabled=no"
[root@m01 ~]# ansible 'c6,backup' -m service -a 'name=crond state=stopped'
name:指定服务名称
state:
	started:启动服务
	stopped:停止服务
	restarted:重启服务
	reloaded:重新加载服务
enabled:开机自启

ansible用户管理模块

user

[root@m01 ~]# ansible all -m user -a 'name=zlsqqq uid=10201 group=root shell=/sbin/nologin create_home=false'

name:指定用户名
uid:指定uid       -u
group:只能指定组名,不能指定gid     -g
shell:指定登录的方式   -s
create_home:是否创建家目录
	true,yes:创建
	false,no:不创建
comment:指定注释   -c
groups:指定附加组(配合append,如果不加append覆盖) -G
append:创建附加组的时候,追加 -a
remove:删除用户的时候,是否同时删除家目录和邮件文件
	true,yes:删除
	fasle,no:不删除
state
	present:创建
	absent:删除

generate_ssh_key:是否创建秘钥对
	yes:创建
	no:不创建
ssh_key_bits:指定秘钥对加密长度
ssh_key_file:指定私钥文件的位置
system:是否是系统用户  -r
	yes:是系统用户
	no:不是系统用户

group

[root@m01 ~]# ansible all -m group -a 'name=xxxx gid=10010 state=present'

name:指定组名
gid:指定组id
state:
	present:创建
	absent:删除

ansible定时任务模块

cron

# 注意:定时任务这里是根据name来判断被管理端是否被推送,如果删除定时任务某一条的语句也只是删除name就好了
# 创建
[root@m01 ~]# ansible all -m cron -a "name='sync time' minute=*/5 job='ntpdate time1.aliyun.com &>/dev/null'"

# 删除(删除是根据注释来删除的 name)
[root@m01 ~]# ansible all -m cron -a "name='time'  state=absent"

name:指定定时任务的名字(添加一个备注)
state:
	present:创建定时任务
	absent:删除定时任务

minute:分 (0-59) */5     10-20     10,20
hour:时(0-23)
day:日(1-31)
month:月(1-12)
weekday:周(0-6)

ansible磁盘挂载模块

  • mount
[root@m01 ~]# ansible web_group -m mount -a 'path=/mnt src=10.0.0.31:/web_data fstype=nfs state=mounted'

path:挂载到本地的目录
src:对端目录
fstype:文件系统类型
	nfs
	ext4
	ext3
state:
	present:只写入开机自动挂载的文件中,不挂载
	mounted:既写入文件,又挂载
	
	absent:卸载设备,并且清理开机自动挂载文件
	unmounted:只卸载不清理文件

推荐:
	- 挂载的时候:mounted
	- 卸载的时候:absent

ansible关闭selinux模块

#修改配置文件关闭selinux,必须重启
[root@m01 ~]# ansible web_group -m selinux -a 'state=disabled' -i ./hosts
 [WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'. State change will take effect next reboot.

web01 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "configfile": "/etc/selinux/config",
    "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
    "policy": "targeted",
    "reboot_required": true,
    "state": "disabled"
}
web02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "configfile": "/etc/selinux/config",
    "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
    "policy": "targeted",
    "reboot_required": true,
    "state": "disabled"
}

#临时关闭
[root@m01 ~]# ansible web_group -m shell -a 'setenforce 0' -i ./hosts
web02 | CHANGED | rc=0 >>
web01 | CHANGED | rc=0 >>


[root@m01 ~]# ansible web_group -m shell -a 'getenforce' -i ./hosts
web02 | CHANGED | rc=0 >>
Permissive

web01 | CHANGED | rc=0 >>
Permissive

ansible防火墙模块

[root@m01 ~]# ansible web_group -m firewalld -a 'service=http permanent=yes state=enabled' -i ./hosts
[root@m01 ~]# ansible web_group -m firewalld -a "service=http immediate=yes permanent=yes state=enabled" -i ./hosts

[root@m01 ~]# ansible web_group -m firewalld -a "port=8080-8090/tcp immediate=yes permanent=yes state=enabled" -i ./hosts

service                 #指定开放或关闭的服务名称
port                    #指定开放或关闭的端口
permanent               #是否添加永久生效
state                   #开启或者关闭
    enabled
    disabled

zone                    #指定配置某个区域
rich_rule               #配置辅规则
masquerade              #开启地址伪装
immediate               #临时生效
source                  #指定来源IP

ansible主机模块(setup )

为什么要讲这个模块?

做过自动化的小伙伴会觉得这个模块非常实用

在公司中总会有一些需求

  • 比如:
    1.根据不同主机不同IP创建对应IP的目录
    2.根据不同主机不同主机名创建对应主机名的目录
    3.自动化运维平台需要自动获取到主机的IP地址,内存信息,磁盘信息,主机名...等
    4.如果安装数据库,分配内存为物理内存的80%,此时有3台不同物理内存的机器2G、4G、16G
    写一个playbook的情况下,我需要获取到对应主机的内存并作出计算,写判断。
  • 1.setup
[root@m01 ~]# ansible web01 -m setup

这里显示东西实在太多了,就不放内容了。。。
所以一般用此模块都会和下面这些操作使用,只过滤有用信息

  • 2.获取ip地址(利用setup模块)
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_default_ipv4": {
            "address": "10.0.0.7",
            "alias": "eth0",
            "broadcast": "10.0.0.255",
            "gateway": "10.0.0.2",
            "interface": "eth0",
            "macaddress": "00:0c:29:f8:98:80",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "10.0.0.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
  • 3.获取主机名
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_fqdn'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_fqdn": "web01",
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
  • 4.获取内存信息
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_memory_mb'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 1622,
                "used": 360
            },
            "real": {
                "free": 1068,
                "total": 1982,
                "used": 914
            },
            "swap": {
                "cached": 0,
                "free": 1023,
                "total": 1023,
                "used": 0
            }
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
  • 5.获取磁盘信息
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 1622,
                "used": 360
            },
            "real": {
                "free": 1068,
                "total": 1982,
                "used": 914
            },
            "swap": {
                "cached": 0,
                "free": 1023,
                "total": 1023,
                "used": 0
            }
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
[root@m01 ~]# ansible_devices^C
[root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_devices'
web01 | SUCCESS => {
    "ansible_facts": {
        "ansible_devices": {
            "sda": {
                "holders": [],
                "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
                "links": {
                    "ids": [],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware Virtual S",
                "partitions": {
                    "sda1": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "8e547355-994a-4bad-a941-da93f4f1cdfd"
                            ]
                        },
                        "sectors": "2097152",
                        "sectorsize": 512,
                        "size": "1.00 GB",
                        "start": "2048",
                        "uuid": "8e547355-994a-4bad-a941-da93f4f1cdfd"
                    },
                    "sda2": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
                            ]
                        },
                        "sectors": "2097152",
                        "sectorsize": 512,
                        "size": "1.00 GB",
                        "start": "2099200",
                        "uuid": "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
                    },
                    "sda3": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "7348b9b1-f2a7-46c6-bede-4f22224dc168"
                            ]
                        },
                        "sectors": "37746688",
                        "sectorsize": 512,
                        "size": "18.00 GB",
                        "start": "4196352",
                        "uuid": "7348b9b1-f2a7-46c6-bede-4f22224dc168"
                    }
                },
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "41943040",
                "sectorsize": "512",
                "size": "20.00 GB",
                "support_discard": "0",
                "vendor": "VMware,",
                "virtual": 1
            },
            "sr0": {
                "holders": [],
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_00000000000000000001"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware IDE CDR00",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "2097151",
                "sectorsize": "512",
                "size": "1024.00 MB",
                "support_discard": "0",
                "vendor": "NECVMWar",
                "virtual": 1
            },
            "sr1": {
                "holders": [],
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware IDE CDR10",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "2097151",
                "sectorsize": "512",
                "size": "1024.00 MB",
                "support_discard": "0",
                "vendor": "NECVMWar",
                "virtual": 1
            }
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}
  • 6.其他参数信息
ansible_all_ipv4_addresses:仅显示ipv4的信息。
ansible_devices:仅显示磁盘设备信息。
ansible_distribution:显示是什么系统,例:centos,suse等。
ansible_distribution_major_version:显示是系统主版本。
ansible_distribution_version:仅显示系统版本。
ansible_machine:显示系统类型,例:32位,还是64位。
ansible_eth0:仅显示eth0的信息。
ansible_hostname:仅显示主机名。
ansible_kernel:仅显示内核版本。
ansible_lvm:显示lvm相关信息。
ansible_memtotal_mb:显示系统总内存。
ansible_memfree_mb:显示可用系统内存。
ansible_memory_mb:详细显示内存情况。
ansible_swaptotal_mb:显示总的swap内存。
ansible_swapfree_mb:显示swap内存的可用内存。
ansible_mounts:显示系统磁盘挂载情况。
ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus:显示cpu个数(只显示总的个数)。

ansible解压模块

## 注意:unarchive可以解压任何格式的压缩包,前提条件就是远端的机器上必须有该包的解压命令
# 1.包只需要放在管理端,不需要放在被控端
# 2.如果执意要放在被控端,使用remote_src=true

ansible backup -m unarchive -a 'src=/root/wordpress-5.0.3-zh_CN.tar.gz dest=/tmp remote_src=yes'

ansible web02 -m unarchive -a 'src=/root/QQ.zip dest=/root'

src:指定源文件在哪里(压缩包的路径)
dest:指定你要解压的位置在哪里
remote_src:指定该包是否在远端机器
	yes:在
	no:不在

# 案例操作演示:
    - name: unzip php and nginx
      unarchive:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
      with_items:
        - { src: "/ansible/nginx/nginx.php.tar.gz" , dest: "/opt" }
        - { src: "/ansible/nginx/wordpress-5.0.3-zh_CN.tar.gz" , dest: "/code" }

ansible 数据库模块

grant all on *.* to wp@'%' identified by '123'

# 操作演示 (创建库)
mysql_db:
     name: 库名
     state: prensent

# 操作演示 (创建用户)
    - name: Create WordPress User
      mysql_user:
        #login_user: 'root'           # 如数据库主机连接数据库有设置用户,此处写上连接用户
        #login_password: '123'	      # 如数据库主机连接数据库有设置密码,此处写上连接密码
        #login_host: 'localhost'	  # 如数据库主机连接数据库有设置仅本地登录,此处写上为本地登录
        name: wp_user                 # 指定创建数据库用户
        password: '123'				 # 指定创建用户的密码
        host: '%'					 # 指定用户能在所有主机远程连接使用
        priv: '*.*:ALL'			      # 指定用户具备对所有库中所有表的权限
        state: present				  # 指定用户状态为安装

ansible之template模块

# 简介:
· 和copy一样,但使用template模块针对脚本时,如脚本中有变量(这里的变量指ansible变量),会将推送主机的不同,从而变量结果也不一样,
总的来说就是template能识别变量。

ansible之template模块 
趁着最近在搞ansible,现在学习了一波template模块的用法:
1、使用template模块在jinja2中引用变量,先来目录结构树

[root@master ansible]# tree
.
├── ansible.cfg
├── hosts
├── roles
│   └── temp
│       ├── tasks
│       │   └── main.yaml
│       ├── templates
│       │   ├── test_if.j2
│       │   └── test.j2
│       └── vars
│           └── main.yaml
└── work_dir
    ├── copy_configfile.retry
    └── copy_configfile.yaml

打开定义好的变量:
[root@master ansible]# cat roles/temp/vars/main.yaml 
master_ip: 192.168.101.14
master_hostname: master
node1_ip: 192.168.101.15
node1_hostname: node1
打开hosts文件查看节点信息:
[root@master ansible]# egrep -v "^#|^$" hosts 
[nodes]
192.168.101.14 
192.168.101.15
现在通过定义好的变量在templates目录下创建j2文件:
[root@master ansible]# cat roles/temp/templates/test.j2 
ExecStart=/usr/local/bin/etcd --name {{ master_hostname }} --initial-advertise-peer-urls http://{{ master_ip }}:2380
查看tasks主任务定义:
[root@master ansible]# cat roles/temp/tasks/main.yaml 
- name: copy configfile to nodes
  template:
    src: test.j2
    dest: /tmp/test.conf
查看工作目录下面的执行yaml:
[root@master ansible]# cat work_dir/copy_configfile.yaml 
- hosts: nodes
  remote_user: root
  roles: 
    - temp
在tasks目录下面的main.yaml定义使用了template模块,调用templates目录下面的test.j2文件
执行:
[root@master ansible]# ansible-playbook work_dir/copy_configfile.yaml
然后在两个节点查看:
[root@master ~]# cat /tmp/test.conf     
ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
[root@node1 ~]# cat /tmp/test.conf
ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
可以看见在各个节点的tem目录下面的文件都用变量替换了
 
2、使用template模块调用的j2文件使用{% if %} {% endif %}进行控制:
[root@master ansible]# cat roles/temp/templates/test_if.j2 
{% if ansible_hostname == master_hostname %}
ExecStart=/usr/local/bin/etcd --name {{ master_hostname }} --initial-advertise-peer-urls http://{{ master_ip }}:2380
{% elif ansible_hostname == node1_hostname %}
ExecStart=/usr/local/bin/etcd --name {{ node1_hostname }} --initial-advertise-peer-urls http://{{ node1_ip }}:2380
{% endif %}
在上面中使用if进行了判断,如果ansible_hostname变量与定义的master_hostname变量值相等,那么将此文件copy到节点上就使用条件1,而过不满足条件1那么执行条件2
ansible_hostname这个变量是setup模块中的值,是节点的固定值

[root@master ~]# ansible all -m setup -a "filter=ansible_hostname"
192.168.101.15 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "node1"
    }, 
    "changed": false, 
    "failed": false
}
192.168.101.14 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "master"
    }, 
    "changed": false, 
    "failed": false
}

现在查看tasks下面的文件:
[root@master ansible]# cat roles/temp/tasks/main.yaml 
- name: copy configfile to nodes
  template:
    src: test_if.j2
    dest: /tmp/test.conf
将上面的test.j2改为了if条件的j2,然后执行:
[root@master ansible]# ansible-playbook work_dir/copy_configfile.yaml
查看各节点生成的文件内容:
[root@master ~]# cat /tmp/test.conf 
ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
[root@node1 ~]# cat /tmp/test.conf
ExecStart=/usr/local/bin/etcd --name node1 --initial-advertise-peer-urls http://192.168.101.15:2380
可以看见生成的文件内容不一样,于是这样就可以将节点的不同内容进行分离开了
当然还可以使用另外的方式隔离节点的不同:
ExecStart=/usr/local/bin/etcd --name {{ ansible_hostname }} --initial-advertise-peer-urls http://{{ ansible_ens33.ipv4.address }}:2380
因为各个节点的ansible_hostname和ip都是固定的所以也可以根据上面进行区分不同(不过这种方式限制了一定的范围)
 
3、使用template模块调用j2文件使用for循环:
 创建jinja关于for的文件:
[root@master ansible]# cat roles/temp/templates/test_for.j2 
{% for i in range(1,10) %}
test{{ i }}
{% endfor %}
[root@master ansible]# cat roles/temp/tasks/main.yaml 
- name: copy configfile to nodes
  template:
    src: test_for.j2
    dest: /tmp/test.conf
执行该角色:
[root@master ansible]# ansible-playbook work_dir/copy_configfile.yaml
验证两节点的文件内容:

[root@master ~]# cat /tmp/test.conf 
test1
test2
test3
test4
test5
test6
test7
test8
test9


[root@node1 ~]# cat /tmp/test.conf 
test1
test2
test3
test4
test5
test6
test7
test8
test9

 
4、使用default()默认值
当我们定义了变量的值时,采用变量的值,当我们没有定义变量的值时,那么使用默认给定的值:
首先查看定义的变量:
[root@master ansible]# cat roles/temp/vars/main.yaml 
master_ip: 192.168.101.14
master_hostname: master
node1_ip: 192.168.101.15
node1_hostname: node1
然后查看jinja2的文件:
[root@master ansible]# cat roles/temp/templates/test_default.j2 
Listen: {{ server_port|default(80) }}
可以看见并没有定义server_port这个变量
查看tasks文件:
[root@master ansible]# cat roles/temp/tasks/main.yaml 
- name: copy configfile to nodes
  template:
    src: test_default.j2
    dest: /tmp/test.conf
执行完成后,查看文件内容:
[root@master ~]# cat /tmp/test.conf 
Listen: 80
现在向vars/main.yaml中定义server_port变量,并给定值:
[root@master ansible]# cat roles/temp/vars/main.yaml    
master_ip: 192.168.101.14
master_hostname: master
node1_ip: 192.168.101.15
node1_hostname: node1
server_port: 8080
再次执行,然后查看文件内容:
[root@master ~]# cat /tmp/test.conf 
Listen: 8080
转自:https://www.cnblogs.com/jsonhc/p/7895399.html
原文地址:https://www.cnblogs.com/tcy1/p/13080400.html