【devops】devops-ansible模块先容

打印 上一主题 下一主题

主题 845|帖子 845|积分 2537

 本站以分享各种运维经验和运维所需要的技能为主
  《python零基础入门》:python零基础入门学习
  《python运维脚本》: python运维脚本实践
  《shell》:shell学习
  《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战
  《k8》从题目中去学习k8s
  《docker学习》暂未更新
  《ceph学习》ceph一样平常题目解决分享
  《日志收集》ELK+各种中间件
  《运维一样平常》运维一样平常
  《linux》运维口试100问
  《DBA》db的先容使用(mysql、redis、mongodb...)
  命令模块



  • command
  1. # 默认模块, 执行命令
  2. [root@m01 ~]# ansible web_group -a "hostname"
复制代码


  • shell
  1. # 如果需要一些管道操作,则使用shell
  2. [root@m01 ~]# ansible web_group -m shell -a "ps -ef|grep nginx" -f 50
复制代码


  • script
  1. # 编写脚本
  2. [root@m01 ~]# vim /root/yum.sh
  3. #!/usr/bin/bash
  4. yum install -y vsftpd
  5. #在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行
  6. [root@m01 ~]# ansible web_group -m script -a "/root/yum.sh"
复制代码
软件管理模块



  • yum
  1. [root@m01 ~]# ansible web_group -m yum -a "name=httpd state=present"
  2. name                           
  3.     httpd                       #指定要安装的软件包名称
  4.     file://                     #指定本地安装路径(yum localinstall 本地rpm包)
  5.     http://                     #指定yum源(从远程仓库获取rpm包)
  6.    
  7. state                           #指定使用yum的方法
  8.     installed,present           #安装软件包
  9.     removed,absent              #移除软件包
  10.     latest                      #安装最新软件包
  11.    
  12. [root@m01 ~]# ansible-doc yum
  13. exclude=kernel*,foo*            #排除某些包
  14. list=ansible                    #类似于yum list查看是否可以安装
  15. disablerepo="epel,ol7_latest"   #禁用指定的yum仓库
  16. download_only=true              #只下载不安装 yum install d
复制代码


  • yum_repository
  1. #添加yum仓库
  2. [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
  3. #仓库名和配置文件名不同
  4. [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
  5. #添加mirrorlist
  6. [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
  7. #删除yum仓库及文件
  8. [root@m01 ~]# ansible web_group -m yum_repository -a 'name=zls_epel file=test_zls state=absent' -i ./hosts
  9. #开起gpgcheck
  10. [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
  11. name        #指定仓库名,如果没有file则为仓库文件名
  12. baseurl     #指定yum源
  13. gpgcheck    #指定检查秘钥
  14.     no
  15.     yes
  16. enabled     #是否启用仓库
  17.     no
  18.     yes
复制代码
ansible文件管理模块




  1. [root@m01 ~]# ansible backup -m  -a 'src=/root/zls_xxx.conf dest=/etc/rsyncd.conf owner=root group=root mode=0644'
  2. src:指定源文件位置(管理机上的文件)
  3. dest:指定你要推送到主机的目标位置
  4. owner:指定属主
  5. group:指定属组
  6. mode:指定权限
  7. backup:是否备份,第一次推,没有每份,对端机器存在该文件,并且内容不一致,才会做备份
  8.         yes:推送之前,先备份目标主机的源文件
  9.         no:不备份
  10. remote_src:源文件是否在远端的机器上
  11.         yes:是
  12.         no:否
  13. content:往指定目标文件中写入内容
复制代码


  • file
作用:


  • 授权
  • 创建目次
  • 创建文件
  • 创建软毗连
  • 删除目次,文件,软毗连
  1. [root@m01 ~]# ansible all -m file -a 'path=/opt/test/zls owner=www group=www mode=0722 state=directory'
  2. [root@m01 ~]# ansible all -m file -a 'path=/code owner=www group=www recurse=yes'
  3. path:指定文件或目录的路径
  4. owner:指定属主
  5. group:指定数组
  6. mode:指定权限
  7. src:做 软/硬 链接的时候使用,指定源文件
  8. recurse:是否递归授权
  9.         yes:递归授权
  10.         no:仅授权当前目录
  11. state:
  12.         directory:创建目录
  13.         touch:创建文件
  14.         link:做软链接
  15.         hard:做硬链接
  16.         absent:删除
  17.         file:配合 modification_time  access_time  修改文件的属性,stat
复制代码


  • get_url
类似于:wget
  1. [root@m01 ~]# ansible backup -m get_url -a 'url=http://test.driverzeng.com/Nginx_File/nginx.txt dest=/root checksum=md5:8f8dd0f79bc6ef2148ca3494070a86a1'
  2. url:指定下载文件的地址
  3. dest:指定下载的路径
  4. mode:指定权限
  5. checksum:指定加密的算法
  6.         sha256
  7.         md5
复制代码


  • fetch
   将目标主机文件拉取到操控机器
  1. # 批量将日志拉取到操控机器
  2. ansible test -m fetch -a 'src=/opt/apache-tomcat-jtour-chu-code/logs/2021-10/jtour-chu-code-2021-10-11-catalina.tar.gz dest=/tcy'
  3. # 说明
  4. -m 指定模块
  5. src 目标主机源文件
  6. dest 保存槽控机/tcy目录
复制代码
ansible服务管理模块

service、systemd
  1. #启动crond并加入开机自启
  2. [root@m01 ~]# ansible web_group -m service -a "name=crond state=started enabled=yes"
  3. #停止crond并删除开机自启
  4. [root@m01 ~]# ansible web_group -m service -a "name=crond state=stoped enabled=no"
  5. [root@m01 ~]# ansible 'c6,backup' -m service -a 'name=crond state=stopped'
  6. name:指定服务名称
  7. state:
  8.         started:启动服务
  9.         stopped:停止服务
  10.         restarted:重启服务
  11.         reloaded:重新加载服务
  12. enabled:开机自启
复制代码
ansible用户管理模块

user
  1. [root@m01 ~]# ansible all -m user -a 'name=zlsqqq uid=10201 group=root shell=/sbin/nologin create_home=false'
  2. name:指定用户名
  3. uid:指定uid       -u
  4. group:只能指定组名,不能指定gid     -g
  5. shell:指定登录的方式   -s
  6. create_home:是否创建家目录
  7.         true,yes:创建
  8.         false,no:不创建
  9. comment:指定注释   -c
  10. groups:指定附加组(配合append,如果不加append覆盖) -G
  11. append:创建附加组的时候,追加 -a
  12. remove:删除用户的时候,是否同时删除家目录和邮件文件
  13.         true,yes:删除
  14.         fasle,no:不删除
  15. state
  16.         present:创建
  17.         absent:删除
  18. generate_ssh_key:是否创建秘钥对
  19.         yes:创建
  20.         no:不创建
  21. ssh_key_bits:指定秘钥对加密长度
  22. ssh_key_file:指定私钥文件的位置
  23. system:是否是系统用户  -r
  24.         yes:是系统用户
  25.         no:不是系统用户
复制代码
group
  1. [root@m01 ~]# ansible all -m group -a 'name=xxxx gid=10010 state=present'
  2. name:指定组名
  3. gid:指定组id
  4. state:
  5.         present:创建
  6.         absent:删除
复制代码
ansible定时任务模块

cron
  1. # 注意:定时任务这里是根据name来判断被管理端是否被推送,如果删除定时任务某一条的语句也只是删除name就好了
  2. # 创建
  3. [root@m01 ~]# ansible all -m cron -a "name='sync time' minute=*/5 job='ntpdate time1.aliyun.com &>/dev/null'"
  4. # 删除(删除是根据注释来删除的 name)
  5. [root@m01 ~]# ansible all -m cron -a "name='time'  state=absent"
  6. name:指定定时任务的名字(添加一个备注)
  7. state:
  8.         present:创建定时任务
  9.         absent:删除定时任务
  10. minute:分 (0-59) */5     10-20     10,20
  11. hour:时(0-23)
  12. day:日(1-31)
  13. month:月(1-12)
  14. weekday:周(0-6)
复制代码
ansible磁盘挂载模块



  • mount
  1. [root@m01 ~]# ansible web_group -m mount -a 'path=/mnt src=10.0.0.31:/web_data fstype=nfs state=mounted'
  2. path:挂载到本地的目录
  3. src:对端目录
  4. fstype:文件系统类型
  5.         nfs
  6.         ext4
  7.         ext3
  8. state:
  9.         present:只写入开机自动挂载的文件中,不挂载
  10.         mounted:既写入文件,又挂载
  11.        
  12.         absent:卸载设备,并且清理开机自动挂载文件
  13.         unmounted:只卸载不清理文件
  14. 推荐:
  15.         - 挂载的时候:mounted
  16.         - 卸载的时候:absent
复制代码
ansible关闭selinux模块

  1. #修改配置文件关闭selinux,必须重启
  2. [root@m01 ~]# ansible web_group -m selinux -a 'state=disabled' -i ./hosts
  3. [WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'. State change will take effect next reboot.
  4. web01 | CHANGED => {
  5.     "ansible_facts": {
  6.         "discovered_interpreter_python": "/usr/bin/python"
  7.     },
  8.     "changed": true,
  9.     "configfile": "/etc/selinux/config",
  10.     "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
  11.     "policy": "targeted",
  12.     "reboot_required": true,
  13.     "state": "disabled"
  14. }
  15. web02 | CHANGED => {
  16.     "ansible_facts": {
  17.         "discovered_interpreter_python": "/usr/bin/python"
  18.     },
  19.     "changed": true,
  20.     "configfile": "/etc/selinux/config",
  21.     "msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
  22.     "policy": "targeted",
  23.     "reboot_required": true,
  24.     "state": "disabled"
  25. }
  26. #临时关闭
  27. [root@m01 ~]# ansible web_group -m shell -a 'setenforce 0' -i ./hosts
  28. web02 | CHANGED | rc=0 >>
  29. web01 | CHANGED | rc=0 >>
  30. [root@m01 ~]# ansible web_group -m shell -a 'getenforce' -i ./hosts
  31. web02 | CHANGED | rc=0 >>
  32. Permissive
  33. web01 | CHANGED | rc=0 >>
  34. Permissive
复制代码
ansible防火墙模块

  1. [root@m01 ~]# ansible web_group -m firewalld -a 'service=http permanent=yes state=enabled' -i ./hosts
  2. [root@m01 ~]# ansible web_group -m firewalld -a "service=http immediate=yes permanent=yes state=enabled" -i ./hosts
  3. [root@m01 ~]# ansible web_group -m firewalld -a "port=8080-8090/tcp immediate=yes permanent=yes state=enabled" -i ./hosts
  4. service                 #指定开放或关闭的服务名称
  5. port                    #指定开放或关闭的端口
  6. permanent               #是否添加永久生效
  7. state                   #开启或者关闭
  8.     enabled
  9.     disabled
  10. zone                    #指定配置某个区域
  11. rich_rule               #配置辅规则
  12. masquerade              #开启地址伪装
  13. immediate               #临时生效
  14. source                  #指定来源IP
复制代码
ansible主机模块(setup )

为什么要讲这个模块?
做过自动化的小同伴会觉得这个模块非常实用
在公司中总会有一些需求


  • 比如: 1.根据不同主机不同IP创建对应IP的目次 2.根据不同主机不同主机名创建对应主机名的目次 3.自动化运维平台需要自动获取到主机的IP地点,内存信息,磁盘信息,主机名...等 4.如果安装数据库,分配内存为物理内存的80%,此时有3台不同物理内存的机器2G、4G、16G 写一个playbook的情况下,我需要获取到对应主机的内存并作出计算,写判定。
  • 1.setup
  1. [root@m01 ~]# ansible web01 -m setup
  2. 这里显示东西实在太多了,就不放内容了。。。
  3. 所以一般用此模块都会和下面这些操作使用,只过滤有用信息
复制代码


  • 2.获取ip地点(利用setup模块)
  1. [root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_default_ipv4'
  2. web01 | SUCCESS => {
  3.     "ansible_facts": {
  4.         "ansible_default_ipv4": {
  5.             "address": "10.0.0.7",
  6.             "alias": "eth0",
  7.             "broadcast": "10.0.0.255",
  8.             "gateway": "10.0.0.2",
  9.             "interface": "eth0",
  10.             "macaddress": "00:0c:29:f8:98:80",
  11.             "mtu": 1500,
  12.             "netmask": "255.255.255.0",
  13.             "network": "10.0.0.0",
  14.             "type": "ether"
  15.         },
  16.         "discovered_interpreter_python": "/usr/bin/python"
  17.     },
  18.     "changed": false
  19. }
复制代码


  • 3.获取主机名
  1. [root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_fqdn'
  2. web01 | SUCCESS => {
  3.     "ansible_facts": {
  4.         "ansible_fqdn": "web01",
  5.         "discovered_interpreter_python": "/usr/bin/python"
  6.     },
  7.     "changed": false
  8. }
复制代码


  • 4.获取内存信息
  1. [root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_memory_mb'
  2. web01 | SUCCESS => {
  3.     "ansible_facts": {
  4.         "ansible_memory_mb": {
  5.             "nocache": {
  6.                 "free": 1622,
  7.                 "used": 360
  8.             },
  9.             "real": {
  10.                 "free": 1068,
  11.                 "total": 1982,
  12.                 "used": 914
  13.             },
  14.             "swap": {
  15.                 "cached": 0,
  16.                 "free": 1023,
  17.                 "total": 1023,
  18.                 "used": 0
  19.             }
  20.         },
  21.         "discovered_interpreter_python": "/usr/bin/python"
  22.     },
  23.     "changed": false
  24. }
复制代码


  • 5.获取磁盘信息
  1. web01 | SUCCESS => {
  2.     "ansible_facts": {
  3.         "ansible_memory_mb": {
  4.             "nocache": {
  5.                 "free": 1622,
  6.                 "used": 360
  7.             },
  8.             "real": {
  9.                 "free": 1068,
  10.                 "total": 1982,
  11.                 "used": 914
  12.             },
  13.             "swap": {
  14.                 "cached": 0,
  15.                 "free": 1023,
  16.                 "total": 1023,
  17.                 "used": 0
  18.             }
  19.         },
  20.         "discovered_interpreter_python": "/usr/bin/python"
  21.     },
  22.     "changed": false
  23. }
  24. [root@m01 ~]# ansible_devices^C
  25. [root@m01 ~]# ansible web01 -m setup -a 'filter=ansible_devices'
  26. web01 | SUCCESS => {
  27.     "ansible_facts": {
  28.         "ansible_devices": {
  29.             "sda": {
  30.                 "holders": [],
  31.                 "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
  32.                 "links": {
  33.                     "ids": [],
  34.                     "labels": [],
  35.                     "masters": [],
  36.                     "uuids": []
  37.                 },
  38.                 "model": "VMware Virtual S",
  39.                 "partitions": {
  40.                     "sda1": {
  41.                         "holders": [],
  42.                         "links": {
  43.                             "ids": [],
  44.                             "labels": [],
  45.                             "masters": [],
  46.                             "uuids": [
  47.                                 "8e547355-994a-4bad-a941-da93f4f1cdfd"
  48.                             ]
  49.                         },
  50.                         "sectors": "2097152",
  51.                         "sectorsize": 512,
  52.                         "size": "1.00 GB",
  53.                         "start": "2048",
  54.                         "uuid": "8e547355-994a-4bad-a941-da93f4f1cdfd"
  55.                     },
  56.                     "sda2": {
  57.                         "holders": [],
  58.                         "links": {
  59.                             "ids": [],
  60.                             "labels": [],
  61.                             "masters": [],
  62.                             "uuids": [
  63.                                 "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
  64.                             ]
  65.                         },
  66.                         "sectors": "2097152",
  67.                         "sectorsize": 512,
  68.                         "size": "1.00 GB",
  69.                         "start": "2099200",
  70.                         "uuid": "9e4d046c-02cf-47bd-a4bf-1e8b5fa4bed5"
  71.                     },
  72.                     "sda3": {
  73.                         "holders": [],
  74.                         "links": {
  75.                             "ids": [],
  76.                             "labels": [],
  77.                             "masters": [],
  78.                             "uuids": [
  79.                                 "7348b9b1-f2a7-46c6-bede-4f22224dc168"
  80.                             ]
  81.                         },
  82.                         "sectors": "37746688",
  83.                         "sectorsize": 512,
  84.                         "size": "18.00 GB",
  85.                         "start": "4196352",
  86.                         "uuid": "7348b9b1-f2a7-46c6-bede-4f22224dc168"
  87.                     }
  88.                 },
  89.                 "removable": "0",
  90.                 "rotational": "1",
  91.                 "sas_address": null,
  92.                 "sas_device_handle": null,
  93.                 "scheduler_mode": "deadline",
  94.                 "sectors": "41943040",
  95.                 "sectorsize": "512",
  96.                 "size": "20.00 GB",
  97.                 "support_discard": "0",
  98.                 "vendor": "VMware,",
  99.                 "virtual": 1
  100.             },
  101.             "sr0": {
  102.                 "holders": [],
  103.                 "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
  104.                 "links": {
  105.                     "ids": [
  106.                         "ata-VMware_Virtual_IDE_CDROM_Drive_00000000000000000001"
  107.                     ],
  108.                     "labels": [],
  109.                     "masters": [],
  110.                     "uuids": []
  111.                 },
  112.                 "model": "VMware IDE CDR00",
  113.                 "partitions": {},
  114.                 "removable": "1",
  115.                 "rotational": "1",
  116.                 "sas_address": null,
  117.                 "sas_device_handle": null,
  118.                 "scheduler_mode": "deadline",
  119.                 "sectors": "2097151",
  120.                 "sectorsize": "512",
  121.                 "size": "1024.00 MB",
  122.                 "support_discard": "0",
  123.                 "vendor": "NECVMWar",
  124.                 "virtual": 1
  125.             },
  126.             "sr1": {
  127.                 "holders": [],
  128.                 "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
  129.                 "links": {
  130.                     "ids": [
  131.                         "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
  132.                     ],
  133.                     "labels": [],
  134.                     "masters": [],
  135.                     "uuids": []
  136.                 },
  137.                 "model": "VMware IDE CDR10",
  138.                 "partitions": {},
  139.                 "removable": "1",
  140.                 "rotational": "1",
  141.                 "sas_address": null,
  142.                 "sas_device_handle": null,
  143.                 "scheduler_mode": "deadline",
  144.                 "sectors": "2097151",
  145.                 "sectorsize": "512",
  146.                 "size": "1024.00 MB",
  147.                 "support_discard": "0",
  148.                 "vendor": "NECVMWar",
  149.                 "virtual": 1
  150.             }
  151.         },
  152.         "discovered_interpreter_python": "/usr/bin/python"
  153.     },
  154.     "changed": false
  155. }
复制代码


  • 6.其他参数信息
  1. ansible_all_ipv4_addresses:仅显示ipv4的信息。
  2. ansible_devices:仅显示磁盘设备信息。
  3. ansible_distribution:显示是什么系统,例:centos,suse等。
  4. ansible_distribution_major_version:显示是系统主版本。
  5. ansible_distribution_version:仅显示系统版本。
  6. ansible_machine:显示系统类型,例:32位,还是64位。
  7. ansible_eth0:仅显示eth0的信息。
  8. ansible_hostname:仅显示主机名。
  9. ansible_kernel:仅显示内核版本。
  10. ansible_lvm:显示lvm相关信息。
  11. ansible_memtotal_mb:显示系统总内存。
  12. ansible_memfree_mb:显示可用系统内存。
  13. ansible_memory_mb:详细显示内存情况。
  14. ansible_swaptotal_mb:显示总的swap内存。
  15. ansible_swapfree_mb:显示swap内存的可用内存。
  16. ansible_mounts:显示系统磁盘挂载情况。
  17. ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
  18. ansible_processor_vcpus:显示cpu个数(只显示总的个数)。
复制代码
ansible解压模块

  1. ## 注意:unarchive可以解压任何格式的压缩包,前提条件就是远端的机器上必须有该包的解压命令
  2. # 1.包只需要放在管理端,不需要放在被控端
  3. # 2.如果执意要放在被控端,使用remote_src=true
  4. ansible backup -m unarchive -a 'src=/root/wordpress-5.0.3-zh_CN.tar.gz dest=/tmp remote_src=yes'
  5. ansible web02 -m unarchive -a 'src=/root/QQ.zip dest=/root'
  6. src:指定源文件在哪里(压缩包的路径)
  7. dest:指定你要解压的位置在哪里
  8. remote_src:指定该包是否在远端机器
  9.         yes:在
  10.         no:不在
  11. # 案例操作演示:
  12.     - name: unzip php and nginx
  13.       unarchive:
  14.         src: "{{ item.src }}"
  15.         dest: "{{ item.dest }}"
  16.       with_items:
  17.         - { src: "/ansible/nginx/nginx.php.tar.gz" , dest: "/opt" }
  18.         - { src: "/ansible/nginx/wordpress-5.0.3-zh_CN.tar.gz" , dest: "/code" }
复制代码
ansible 数据库模块

  1. grant all on *.* to wp@'%' identified by '123'
  2. # 操作演示 (创建库)
  3. mysql_db:
  4.      name: 库名
  5.      state: prensent
  6. # 操作演示 (创建用户)
  7.     - name: Create WordPress User
  8.       mysql_user:
  9.         #login_user: 'root'           # 如数据库主机连接数据库有设置用户,此处写上连接用户
  10.         #login_password: '123'              # 如数据库主机连接数据库有设置密码,此处写上连接密码
  11.         #login_host: 'localhost'          # 如数据库主机连接数据库有设置仅本地登录,此处写上为本地登录
  12.         name: wp_user                 # 指定创建数据库用户
  13.         password: '123'                                 # 指定创建用户的密码
  14.         host: '%'                                         # 指定用户能在所有主机远程连接使用
  15.         priv: '*.*:ALL'                              # 指定用户具备对所有库中所有表的权限
  16.         state: present                                  # 指定用户状态为安装
复制代码
ansible之template模块

  1. # 简介:
  2. · 和一样,但使用template模块针对脚本时,如脚本中有变量(这里的变量指ansible变量),会将推送主机的不同,从而变量结果也不一样,
  3. 总的来说就是template能识别变量。
  4. ansible之template模块
  5. 趁着最近在搞ansible,现在学习了一波template模块的用法:
  6. 1、使用template模块在jinja2中引用变量,先来目录结构树
  7. [root@master ansible]# tree
  8. .
  9. ├── ansible.cfg
  10. ├── hosts
  11. ├── roles
  12. │   └── temp
  13. │       ├── tasks
  14. │       │   └── main.yaml
  15. │       ├── templates
  16. │       │   ├── test_if.j2
  17. │       │   └── test.j2
  18. │       └── vars
  19. │           └── main.yaml
  20. └── work_dir
  21.    ├── _configfile.retry
  22.    └── _configfile.yaml
  23. 打开定义好的变量:
  24. [root@master ansible]# cat roles/temp/vars/main.yaml
  25. master_ip: 192.168.101.14
  26. master_hostname: master
  27. node1_ip: 192.168.101.15
  28. node1_hostname: node1
  29. 打开hosts文件查看节点信息:
  30. [root@master ansible]# egrep -v "^#|^$" hosts
  31. [nodes]
  32. 192.168.101.14
  33. 192.168.101.15
  34. 现在通过定义好的变量在templates目录下创建j2文件:
  35. [root@master ansible]# cat roles/temp/templates/test.j2
  36. ExecStart=/usr/local/bin/etcd --name {{ master_hostname }} --initial-advertise-peer-urls http://{{ master_ip }}:2380
  37. 查看tasks主任务定义:
  38. [root@master ansible]# cat roles/temp/tasks/main.yaml
  39. - name:  configfile to nodes
  40.   template:
  41.    src: test.j2
  42.    dest: /tmp/test.conf
  43. 查看工作目录下面的执行yaml:
  44. [root@master ansible]# cat work_dir/_configfile.yaml
  45. - hosts: nodes
  46.   remote_user: root
  47.   roles:
  48.    - temp
  49. 在tasks目录下面的main.yaml定义使用了template模块,调用templates目录下面的test.j2文件
  50. 执行:
  51. [root@master ansible]# ansible-playbook work_dir/_configfile.yaml
  52. 然后在两个节点查看:
  53. [root@master ~]# cat /tmp/test.conf    
  54. ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
  55. [root@node1 ~]# cat /tmp/test.conf
  56. ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
  57. 可以看见在各个节点的tem目录下面的文件都用变量替换了
  58. 2、使用template模块调用的j2文件使用{% if %} {% endif %}进行控制:
  59. [root@master ansible]# cat roles/temp/templates/test_if.j2
  60. {% if ansible_hostname == master_hostname %}
  61. ExecStart=/usr/local/bin/etcd --name {{ master_hostname }} --initial-advertise-peer-urls http://{{ master_ip }}:2380
  62. {% elif ansible_hostname == node1_hostname %}
  63. ExecStart=/usr/local/bin/etcd --name {{ node1_hostname }} --initial-advertise-peer-urls http://{{ node1_ip }}:2380
  64. {% endif %}
  65. 在上面中使用if进行了判断,如果ansible_hostname变量与定义的master_hostname变量值相等,那么将此文件到节点上就使用条件1,而过不满足条件1那么执行条件2
  66. ansible_hostname这个变量是setup模块中的值,是节点的固定值
  67. [root@master ~]# ansible all -m setup -a "filter=ansible_hostname"
  68. 192.168.101.15 | SUCCESS => {
  69.    "ansible_facts": {
  70.        "ansible_hostname": "node1"
  71.    },
  72.    "changed": false,
  73.    "failed": false
  74. }
  75. 192.168.101.14 | SUCCESS => {
  76.    "ansible_facts": {
  77.        "ansible_hostname": "master"
  78.    },
  79.    "changed": false,
  80.    "failed": false
  81. }
  82. 现在查看tasks下面的文件:
  83. [root@master ansible]# cat roles/temp/tasks/main.yaml
  84. - name:  configfile to nodes
  85.   template:
  86.    src: test_if.j2
  87.    dest: /tmp/test.conf
  88. 将上面的test.j2改为了if条件的j2,然后执行:
  89. [root@master ansible]# ansible-playbook work_dir/_configfile.yaml
  90. 查看各节点生成的文件内容:
  91. [root@master ~]# cat /tmp/test.conf
  92. ExecStart=/usr/local/bin/etcd --name master --initial-advertise-peer-urls http://192.168.101.14:2380
  93. [root@node1 ~]# cat /tmp/test.conf
  94. ExecStart=/usr/local/bin/etcd --name node1 --initial-advertise-peer-urls http://192.168.101.15:2380
  95. 可以看见生成的文件内容不一样,于是这样就可以将节点的不同内容进行分离开了
  96. 当然还可以使用另外的方式隔离节点的不同:
  97. ExecStart=/usr/local/bin/etcd --name {{ ansible_hostname }} --initial-advertise-peer-urls http://{{ ansible_ens33.ipv4.address }}:2380
  98. 因为各个节点的ansible_hostname和ip都是固定的所以也可以根据上面进行区分不同(不过这种方式限制了一定的范围)
  99. 3、使用template模块调用j2文件使用for循环:
  100. 创建jinja关于for的文件:
  101. [root@master ansible]# cat roles/temp/templates/test_for.j2
  102. {% for i in range(1,10) %}
  103. test{{ i }}
  104. {% endfor %}
  105. [root@master ansible]# cat roles/temp/tasks/main.yaml
  106. - name:  configfile to nodes
  107.   template:
  108.    src: test_for.j2
  109.    dest: /tmp/test.conf
  110. 执行该角色:
  111. [root@master ansible]# ansible-playbook work_dir/_configfile.yaml
  112. 验证两节点的文件内容:
  113. [root@master ~]# cat /tmp/test.conf
  114. test1
  115. test2
  116. test3
  117. test4
  118. test5
  119. test6
  120. test7
  121. test8
  122. test9
  123. [root@node1 ~]# cat /tmp/test.conf
  124. test1
  125. test2
  126. test3
  127. test4
  128. test5
  129. test6
  130. test7
  131. test8
  132. test9
  133. 4、使用default()默认值
  134. 当我们定义了变量的值时,采用变量的值,当我们没有定义变量的值时,那么使用默认给定的值:
  135. 首先查看定义的变量:
  136. [root@master ansible]# cat roles/temp/vars/main.yaml
  137. master_ip: 192.168.101.14
  138. master_hostname: master
  139. node1_ip: 192.168.101.15
  140. node1_hostname: node1
  141. 然后查看jinja2的文件:
  142. [root@master ansible]# cat roles/temp/templates/test_default.j2
  143. Listen: {{ server_port|default(80) }}
  144. 可以看见并没有定义server_port这个变量
  145. 查看tasks文件:
  146. [root@master ansible]# cat roles/temp/tasks/main.yaml
  147. - name:  configfile to nodes
  148.   template:
  149.    src: test_default.j2
  150.    dest: /tmp/test.conf
  151. 执行完成后,查看文件内容:
  152. [root@master ~]# cat /tmp/test.conf
  153. Listen: 80
  154. 现在向vars/main.yaml中定义server_port变量,并给定值:
  155. [root@master ansible]# cat roles/temp/vars/main.yaml    
  156. master_ip: 192.168.101.14
  157. master_hostname: master
  158. node1_ip: 192.168.101.15
  159. node1_hostname: node1
  160. server_port: 8080
  161. 再次执行,然后查看文件内容:
  162. [root@master ~]# cat /tmp/test.conf
  163. Listen: 8080
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

祗疼妳一个

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表