Loading

ansible playbook模式及语法

一、什么是playbook及其组成

什么是playbook

playbook 翻译过来就是"剧本"

playbook的组成

play:定义的是主机的角色
task:定义的是具体执行的任务
playbook:由一个或多个play组成,一个play可以包含多个task

 

二、playbook的优势

1、功能比adhoc更全
2、控制好依赖
3、展现更直观
4、持久使用

三、playbook的配置语法

基本使用

playbook基础使用

ansible-playbook playbook.yml [options]

-u REMOTE_USER, --user=REMOTE_USER 
# ssh 连接的用户名 
-k, --ask-pass 
#ssh登录认证密码 
-s, --sudo 
#sudo 到root用户,相当于Linux系统下的sudo命令
-U SUDO_USER, --sudo-user=SUDO_USER 
#sudo 到对应的用户 
-K, --ask-sudo-pass #用户的密码(—sudo时使用) 
-T TIMEOUT, --timeout=TIMEOUT 
# ssh 连接超时,默认 10-C, --check # 指定该参数后,执行 playbook 文件不会真正去执行,而是模拟执行一遍,然后输出本次执行会对远程主机造成的修改 
-e EXTRA_VARS, --extra-vars=EXTRA_VARS 
# 设置额外的变量如:key=value 形式 或者 YAML or JSON,以空格分隔变量,或用多个-e 
-f FORKS, --forks=FORKS # 进程并发处理,默认 5
-i INVENTORY, --inventory-file=INVENTORY
# 指定 hosts 文件路径,默认 default=/etc/ansible/hosts
-l SUBSET, --limit=SUBSET
# 指定一个 pattern,对- hosts:匹配到的主机再过滤一次
--list-hosts # 只打印有哪些主机会执行这个 playbook 文件,不是实际执行该 playbook
--list-tasks # 列出该 playbook 中会被执行的 task
--private-key=PRIVATE_KEY_FILE # 私钥路径
--step # 同一时间只执行一个 task,每个 task 执行前都会提示确认一遍
--syntax-check # 只检测 playbook 文件语法是否有问题,不会执行该 playbook
-t TAGS, --tags=TAGS #当 play 和 task 的 tag 为该参数指定的值时才执行,多个 tag 以逗号分隔
--skip-tags=SKIP_TAGS # 当 play 和 task 的 tag 不匹配该参数指定的值时,才执行
-v, --verbose #输出更详细的执行过程信息,-vvv可得到所有执行过程信息。 原文链接:https://www.imooc.com/article/22729

使用场景

1、playbook的配置

示例:

---
- hosts : 192.168.56.11
  remote_user : root
  vars :
          touch_file : devops.file
  tasks :
          - name : touch file
            shell: "touch /tmp/{{touch_file}}"

 

 

2、执行

devops@devops-virtual-machine:/etc/ansible$ cat /etc/ansible/hosts
[test_group1]
#192.168.56.11:22 ansible_ssh_user=root ansible_ssh_pass='1234567'
#192.168.56.11:22 ansible_ssh_user=root ansible_ssh_key_file=/home/devops/.ssh/id_rsa
192.168.56.11:22 ansible_ssh_user=root

#列出f1.yml指的的主机与/etc/ansible/hosts匹配到的主机
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook -i /etc/ansible/hosts --list-hosts ./f1.yml

playbook: ./f1.yml

  play #1 (192.168.56.11): 192.168.56.11    TAGS: []
    pattern: ['192.168.56.11']
    hosts (1):
      192.168.56.11




devops@devops-virtual-machine:/etc/ansible$ ansible-playbook -i /etc/ansible/hosts ./f1.yml

PLAY [192.168.56.11] ***********************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************
ok: [192.168.56.11]

TASK [touch file] **************************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

PLAY RECAP *********************************************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0

 

3、执行结果返回

  • 红色:表示有task执行失败或者提醒的信息
  • 黄色:表示执行了且改变了远程主机状态
  • 绿色:表示执行成功

主机匹配

 

 

 

yaml语法和变量

yaml语法

  • 大小写敏感
  • 使用缩进表示层级关系(只能空格不能使用tab)
  • yaml文件"---"作为文档的开始

yaml支持的数据结构

 

yaml变量的应用

 

playbook变量

  1. playbook的yaml文件中的定义变量赋值
  2. --extra-vars执行参数赋给变量 

 示例:

devops@devops-virtual-machine:/etc/ansible$ cat f1.yml
---
- hosts : 192.168.56.11
  remote_user : root
  #  vars :           # 注册这两行
          #          touch_file : devops.file
  tasks :
          - name : touch file
            shell: "touch /tmp/{{touch_file}}"


# 执行
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f1.yml --extra-vars "touch_file=json2"

PLAY [192.168.56.11] ***********************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************
ok: [192.168.56.11]

TASK [touch file] **************************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

PLAY RECAP *********************************************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0

查看执行结果

devops@devops-virtual-machine:/etc/ansible$ ansible  all -a 'ls /tmp'
192.168.56.11 | SUCCESS | rc=0 >>
devops.file
json2

  3、在文件中定义变量

在资产清单中定义变量

devops@devops-virtual-machine:/etc/ansible$ cat /etc/ansible/hosts
[test_group1]
#192.168.56.11:22 ansible_ssh_user=root ansible_ssh_pass='1234567'
#192.168.56.11:22 ansible_ssh_user=root ansible_ssh_key_file=/home/devops/.ssh/id_rsa
192.168.56.11:22 ansible_ssh_user=root


# 添加两行内容如下: 当f1.yaml执行时会引用(touch_file)这个变量
[test_group1:vars]
touch_file=json3

# 执行
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f1.yml

PLAY [192.168.56.11] ***********************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************
ok: [192.168.56.11]

TASK [touch file] **************************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

PLAY RECAP *********************************************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0


# 查看执行服务器(192.168.56.11 )上是否有json3文件
devops@devops-virtual-machine:/etc/ansible$ ansible  all -a 'ls /tmp'
192.168.56.11 | SUCCESS | rc=0 >>
json2
json3
示例

  4、注册变量

register关键字可以存储指定的命令的输出结果到一个自定义的变量中

- name: get time

  command:date

  register:date_output

devops@devops-virtual-machine:/etc/ansible$ cat f4.yml
---
- hosts : 192.168.56.11
  remote_user : root
  vars :
      touch_file : devops.file
  tasks :
      - name : get date
        command : date              # 执行date命令
        register : date_output      # 把date的执行结果赋值给date_output
      - name : touch file
        shell : "touch /tmp/{{touch_file}}"
      - name : echo date_output
        shell : "echo {{date_output.stdout}}>/tmp/{{touch_file}}"

# 执行 加vvv显示详细信息
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f4.yml -vvv
ansible-playbook 2.4.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/devops/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.6/dist-packages/ansible-2.4.1.0-py3.6.egg/ansible
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.6.5 (default, Apr  1 2018, 05:46:30) [GCC 7.3.0]
Using /etc/ansible/ansible.cfg as config file
Parsed /etc/ansible/hosts inventory source with ini plugin

PLAYBOOK: f4.yml ***********************************************************************************************
1 plays in ./f4.yml

PLAY [192.168.56.11] *******************************************************************************************

TASK [Gathering Facts] *****************************************************************************************
Using module file /usr/local/lib/python3.6/dist-packages/ansible-2.4.1.0-py3.6.egg/ansible/modules/system/setup.py
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<192.168.56.11> (0, b'/root\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231 `" && echo ansible-tmp-1531396830.9463239-175629470926231="` echo /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231 `" ) && sleep 0'"'"''
<192.168.56.11> (0, b'ansible-tmp-1531396830.9463239-175629470926231=/root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231\n', b'')
<192.168.56.11> PUT /tmp/tmpihpjzcgr TO /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/setup.py
<192.168.56.11> SSH: EXEC sftp -b - -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 '[192.168.56.11]'
<192.168.56.11> (0, b'sftp> put /tmp/tmpihpjzcgr /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/setup.py\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/ /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/setup.py && sleep 0'"'"''
<192.168.56.11> (0, b'', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 -tt 192.168.56.11 '/bin/sh -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/setup.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1531396830.9463239-175629470926231/" > /dev/null 2>&1 && sleep 0'"'"''
<192.168.56.11> (0, b'\r\n{"invocation": {"module_args": {"filter": "*", "gather_subset": ["all"], "fact_path": "/etc/ansible/facts.d", "gather_timeout": 10}}, "ansible_facts": {"ansible_product_serial": "VMware-56 4d ba ea 2a 14 bd 0e-90 3f 06 a4 d2 a0 10 ca", "ansible_form_factor": "Other", "ansible_distribution_file_parsed": true, "ansible_fips": false, "ansible_service_mgr": "systemd", "ansible_user_id": "root", "ansible_selinux_python_present": true, "ansible_userspace_bits": "64", "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDvGRGyqSELPCWRxOyhXtCk8HvSnKH82paTv3gVgfkmD9wI7eVXXQDXOoTXYJZzKK5bDy3fsSZg7BpHDLysHff1fUh3oexfzUepT440VAonQl9cWSdUgSQUPZdJuj+o+9teIbkT4yWxh+ou+59uC1z0zwWWs99aIn4Ul/RdAjJJr0O+iTYcdHsnupAxf9T/bpsW49cTRXhhzkQW9gUpyanfVU94Y+cKb/D178V//zL4/Km/90WSFQGMW0xWTSxh1QbqZge639K3BR/wL5VUJhy8Nv6HQPgV9aTkCLNERk4sjrMWQWP4jsT0VPQ0VpS7iE7GQZrbPx3qE/49vcQNIwG3", "gather_subset": ["all"], "ansible_real_user_id": 0, "ansible_architecture": "x86_64", "ansible_local": {}, "ansible_distribution_version": "7.3.1611", "ansible_domain": "example.com", "ansible_distribution_file_path": "/etc/redhat-release", "ansible_user_shell": "/bin/bash", "ansible_date_time": {"weekday_number": "4", "iso8601_basic_short": "20180712T200057", "tz": "CST", "weeknumber": "28", "hour": "20", "year": "2018", "minute": "00", "tz_offset": "+0800", "month": "07", "epoch": "1531396857", "iso8601_micro": "2018-07-12T12:00:57.933420Z", "weekday": "\\u661f\\u671f\\u56db", "time": "20:00:57", "date": "2018-07-12", "iso8601": "2018-07-12T12:00:57Z", "day": "12", "iso8601_basic": "20180712T200057933342", "second": "57"}, "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIDG1zxZJmUXAcaboS6in1sWqmzxiu0mqwHsr0wzF2khq", "ansible_processor_cores": 1, "ansible_virtualization_role": "guest", "ansible_distribution_file_variety": "RedHat", "ansible_env": {"LANG": "zh_CN.UTF-8", "TERM": "xterm-256color", "SHELL": "/bin/bash", "XDG_RUNTIME_DIR": "/run/user/0", "SHLVL": "2", "SSH_TTY": "/dev/pts/0", "HOME": "/root", "SSH_CLIENT": "192.168.56.133 44790 22", "LESSOPEN": "||/usr/bin/lesspipe.sh %s", "PWD": "/root", "LOGNAME": "root", "USER": "root", "MAIL": "/var/mail/root", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "LS_COLORS": "rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:", "XDG_SESSION_ID": "5", "_": "/usr/bin/python", "SSH_CONNECTION": "192.168.56.133 44790 192.168.56.11 22"}, "ansible_effective_group_id": 0, "ansible_bios_version": "6.00", "ansible_processor": ["0", "GenuineIntel", "Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz"], "ansible_virtualization_type": "VMware", "ansible_lo": {"features": {"tx_checksum_ipv4": "off [fixed]", "generic_receive_offload": "on", "tx_checksum_ipv6": "off [fixed]", "tx_scatter_gather_fraglist": "on [fixed]", "rx_all": "off [fixed]", "highdma": "on [fixed]", "rx_fcs": "off [fixed]", "tx_lockless": "on [fixed]", "tx_tcp_ecn_segmentation": "on", "tx_tcp6_segmentation": "on", "tx_gso_robust": "off [fixed]", "tx_ipip_segmentation": "off [fixed]", "tx_checksumming": "on", "vlan_challenged": "on [fixed]", "loopback": "on [fixed]", "fcoe_mtu": "off [fixed]", "scatter_gather": "on", "tx_checksum_sctp": "on [fixed]", "tx_vlan_stag_hw_insert": "off [fixed]", "rx_vlan_stag_hw_parse": "off [fixed]", "rx_vlan_stag_filter": "off [fixed]", "large_receive_offload": "off [fixed]", "tx_scatter_gather": "on [fixed]", "rx_checksumming": "on [fixed]", "tx_tcp_segmentation": "on", "netns_local": "on [fixed]", "busy_poll": "off [fixed]", "generic_segmentation_offload": "on", "tx_udp_tnl_segmentation": "off [fixed]", "tcp_segmentation_offload": "on", "l2_fwd_offload": "off [fixed]", "rx_vlan_offload": "off [fixed]", "ntuple_filters": "off [fixed]", "tx_vlan_offload": "off [fixed]", "tx_nocache_copy": "off [fixed]", "tx_mpls_segmentation": "off [fixed]", "udp_fragmentation_offload": "on", "tx_sctp_segmentation": "on", "tx_sit_segmentation": "off [fixed]", "tx_checksum_fcoe_crc": "off [fixed]", "hw_tc_offload": "off [fixed]", "tx_checksum_ip_generic": "on [fixed]", "tx_fcoe_segmentation": "off [fixed]", "rx_vlan_filter": "off [fixed]", "receive_hashing": "off [fixed]", "tx_gre_segmentation": "off [fixed]"}, "hw_timestamp_filters": [], "mtu": 65536, "device": "lo", "promisc": false, "timestamping": ["rx_software", "software"], "ipv4": {"broadcast": "host", "netmask": "255.0.0.0", "network": "127.0.0.0", "address": "127.0.0.1"}, "ipv6": [{"scope": "host", "prefix": "128", "address": "::1"}], "active": true, "type": "loopback"}, "ansible_memtotal_mb": 976, "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPb+x6CxAv1fn1DdrTK9Gn1AetZc+7Z1fNOmHTKK5YLW9AcE1dNj7ch7XzP98BpgJjkwuqig3TzYuzSajNi7qVg=", "ansible_device_links": {"masters": {"sda2": ["dm-0", "dm-1"]}, "labels": {"sr0": ["CentOS\\\\x207\\\\x20x86_64"]}, "ids": {"sr0": ["ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"], "sda2": ["lvm-pv-uuid-6PpuNw-P0Sl-vgrG-eph3-vPgV-80rS-kVO4nk"], "dm-0": ["dm-name-cl-root", "dm-uuid-LVM-yZVSxca2orueczI165YImVDpRd6Uy7HQ7Qpv8yMY9esqgrnFTcf8dbPKaZ5DK7j1"], "dm-1": ["dm-name-cl-swap", "dm-uuid-LVM-yZVSxca2orueczI165YImVDpRd6Uy7HQJsBOsjYPBRT6yKFLgQcHw9IcENdrUaD0"]}, "uuids": {"sr0": ["2016-12-05-13-55-45-00"], "sda1": ["bd203c5e-8ff1-4060-bcaf-990e2ccb61c1"], "dm-0": ["8d886d43-1ef5-451a-951c-4170c89c9412"], "dm-1": ["2b2df9d8-6c15-4c0e-a4cb-9e25edbf17b8"]}}, "ansible_default_ipv4": {"macaddress": "00:0c:29:a0:10:ca", "network": "192.168.56.0", "mtu": 1500, "broadcast": "192.168.56.255", "alias": "eth0", "netmask": "255.255.255.0", "address": "192.168.56.11", "interface": "eth0", "type": "ether", "gateway": "192.168.56.2"}, "ansible_swapfree_mb": 2047, "ansible_default_ipv6": {}, "ansible_distribution_release": "Core", "ansible_system_vendor": "VMware, Inc.", "ansible_apparmor": {"status": "disabled"}, "ansible_cmdline": {"LANG": "en_US.UTF-8", "BOOT_IMAGE": "/vmlinuz-3.10.0-514.el7.x86_64", "quiet": true, "net.ifnames": "0", "rhgb": true, "biosdevname": "0", "crashkernel": "auto", "rd.lvm.lv": "cl/swap", "ro": true, "root": "/dev/mapper/cl-root"}, "ansible_effective_user_id": 0, "ansible_user_gid": 0, "ansible_selinux": {"status": "disabled"}, "ansible_product_version": "None", "ansible_os_family": "RedHat", "ansible_userspace_architecture": "x86_64", "ansible_product_uuid": "EABA4D56-142A-0EBD-903F-06A4D2A010CA", "ansible_system": "Linux", "ansible_pkg_mgr": "yum", "ansible_memfree_mb": 192, "ansible_devices": {"sr0": {"scheduler_mode": "cfq", "rotational": "1", "vendor": "NECVMWar", "sectors": "8554496", "links": {"masters": [], "labels": ["CentOS\\\\x207\\\\x20x86_64"], "ids": ["ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"], "uuids": ["2016-12-05-13-55-45-00"]}, "sas_device_handle": null, "sas_address": null, "virtual": 1, "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)", "sectorsize": "2048", "removable": "1", "support_discard": "0", "model": "VMware IDE CDR10", "partitions": {}, "holders": [], "size": "16.32 GB"}, "sda": {"scheduler_mode": "deadline", "rotational": "1", "vendor": "VMware,", "sectors": "104857600", "links": {"masters": [], "labels": [], "ids": [], "uuids": []}, "sas_device_handle": null, "sas_address": null, "virtual": 1, "host": "SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)", "sectorsize": "512", "removable": "0", "support_discard": "0", "model": "VMware Virtual S", "partitions": {"sda2": {"sectorsize": 512, "uuid": null, "links": {"masters": ["dm-0", "dm-1"], "labels": [], "ids": ["lvm-pv-uuid-6PpuNw-P0Sl-vgrG-eph3-vPgV-80rS-kVO4nk"], "uuids": []}, "sectors": "102758400", "start": "2099200", "holders": ["cl-root", "cl-swap"], "size": "49.00 GB"}, "sda1": {"sectorsize": 512, "uuid": "bd203c5e-8ff1-4060-bcaf-990e2ccb61c1", "links": {"masters": [], "labels": [], "ids": [], "uuids": ["bd203c5e-8ff1-4060-bcaf-990e2ccb61c1"]}, "sectors": "2097152", "start": "2048", "holders": [], "size": "1.00 GB"}}, "holders": [], "size": "50.00 GB"}, "dm-0": {"scheduler_mode": "", "rotational": "1", "vendor": null, "sectors": "98549760", "links": {"masters": [], "labels": [], "ids": ["dm-name-cl-root", "dm-uuid-LVM-yZVSxca2orueczI165YImVDpRd6Uy7HQ7Qpv8yMY9esqgrnFTcf8dbPKaZ5DK7j1"], "uuids": ["8d886d43-1ef5-451a-951c-4170c89c9412"]}, "sas_device_handle": null, "sas_address": null, "virtual": 1, "host": "", "sectorsize": "512", "removable": "0", "support_discard": "0", "model": null, "partitions": {}, "holders": [], "size": "46.99 GB"}, "dm-1": {"scheduler_mode": "", "rotational": "1", "vendor": null, "sectors": "4194304", "links": {"masters": [], "labels": [], "ids": ["dm-name-cl-swap", "dm-uuid-LVM-yZVSxca2orueczI165YImVDpRd6Uy7HQJsBOsjYPBRT6yKFLgQcHw9IcENdrUaD0"], "uuids": ["2b2df9d8-6c15-4c0e-a4cb-9e25edbf17b8"]}, "sas_device_handle": null, "sas_address": null, "virtual": 1, "host": "", "sectorsize": "512", "removable": "0", "support_discard": "0", "model": null, "partitions": {}, "holders": [], "size": "2.00 GB"}}, "ansible_user_uid": 0, "ansible_lvm": {"pvs": {"/dev/sda2": {"free_g": "0.00", "size_g": "49.00", "vg": "cl"}}, "lvs": {"root": {"size_g": "46.99", "vg": "cl"}, "swap": {"size_g": "2.00", "vg": "cl"}}, "vgs": {"cl": {"free_g": "0.00", "size_g": "49.00", "num_lvs": "2", "num_pvs": "1"}}}, "ansible_distribution": "CentOS", "ansible_user_dir": "/root", "ansible_dns": {"nameservers": ["192.168.56.2"]}, "ansible_distribution_major_version": "7", "module_setup": true, "ansible_processor_count": 1, "ansible_hostname": "linux-node1", "ansible_processor_vcpus": 1, "ansible_swaptotal_mb": 2047, "ansible_lsb": {}, "ansible_real_group_id": 0, "ansible_bios_date": "05/19/2017", "ansible_all_ipv6_addresses": ["fe80::20c:29ff:fea0:10ca"], "ansible_interfaces": ["lo", "eth0"], "ansible_uptime_seconds": 695, "ansible_machine_id": "9460c222be194212b2efa3c8edde3c95", "ansible_kernel": "3.10.0-514.el7.x86_64", "ansible_memory_mb": {"real": {"total": 976, "used": 784, "free": 192}, "swap": {"cached": 0, "total": 2047, "free": 2047, "used": 0}, "nocache": {"used": 464, "free": 512}}, "ansible_user_gecos": "root", "ansible_system_capabilities_enforced": "True", "ansible_python": {"executable": "/usr/bin/python", "version": {"micro": 5, "major": 2, "releaselevel": "final", "serial": 0, "minor": 7}, "type": "CPython", "has_sslcontext": true, "version_info": [2, 7, 5, "final", 0]}, "ansible_processor_threads_per_core": 1, "ansible_fqdn": "linux-node1.example.com", "ansible_mounts": [{"block_used": 576476, "uuid": "8d886d43-1ef5-451a-951c-4170c89c9412", "size_total": 50432839680, "block_total": 12312705, "mount": "/", "block_available": 11736229, "size_available": 48071593984, "fstype": "xfs", "inode_total": 24637440, "options": "rw,relatime,attr2,inode64,noquota", "device": "/dev/mapper/cl-root", "inode_used": 57053, "block_size": 4096, "inode_available": 24580387}, {"block_used": 35407, "uuid": "bd203c5e-8ff1-4060-bcaf-990e2ccb61c1", "size_total": 1063256064, "block_total": 259584, "mount": "/boot", "block_available": 224177, "size_available": 918228992, "fstype": "xfs", "inode_total": 524288, "options": "rw,relatime,attr2,inode64,noquota", "device": "/dev/sda1", "inode_used": 330, "block_size": 4096, "inode_available": 523958}], "ansible_eth0": {"macaddress": "00:0c:29:a0:10:ca", "features": {"tx_checksum_ipv4": "off [fixed]", "generic_receive_offload": "on", "tx_checksum_ipv6": "off [fixed]", "tx_scatter_gather_fraglist": "off [fixed]", "rx_all": "off", "highdma": "off [fixed]", "rx_fcs": "off", "tx_lockless": "off [fixed]", "tx_tcp_ecn_segmentation": "off [fixed]", "tx_tcp6_segmentation": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_segmentation": "off [fixed]", "tx_checksumming": "on", "vlan_challenged": "off [fixed]", "loopback": "off [fixed]", "fcoe_mtu": "off [fixed]", "scatter_gather": "on", "tx_checksum_sctp": "off [fixed]", "tx_vlan_stag_hw_insert": "off [fixed]", "rx_vlan_stag_hw_parse": "off [fixed]", "rx_vlan_stag_filter": "off [fixed]", "large_receive_offload": "off [fixed]", "tx_scatter_gather": "on", "rx_checksumming": "off", "tx_tcp_segmentation": "on", "netns_local": "off [fixed]", "busy_poll": "off [fixed]", "generic_segmentation_offload": "on", "tx_udp_tnl_segmentation": "off [fixed]", "tcp_segmentation_offload": "on", "l2_fwd_offload": "off [fixed]", "rx_vlan_offload": "on", "ntuple_filters": "off [fixed]", "tx_vlan_offload": "on [fixed]", "tx_nocache_copy": "off", "tx_mpls_segmentation": "off [fixed]", "udp_fragmentation_offload": "off [fixed]", "tx_sctp_segmentation": "off [fixed]", "tx_sit_segmentation": "off [fixed]", "tx_checksum_fcoe_crc": "off [fixed]", "hw_tc_offload": "off [fixed]", "tx_checksum_ip_generic": "on", "tx_fcoe_segmentation": "off [fixed]", "rx_vlan_filter": "on [fixed]", "receive_hashing": "off [fixed]", "tx_gre_segmentation": "off [fixed]"}, "type": "ether", "pciid": "0000:02:01.0", "module": "e1000", "mtu": 1500, "device": "eth0", "promisc": false, "timestamping": ["tx_software", "rx_software", "software"], "ipv4": {"broadcast": "192.168.56.255", "netmask": "255.255.255.0", "network": "192.168.56.0", "address": "192.168.56.11"}, "ipv6": [{"scope": "link", "prefix": "64", "address": "fe80::20c:29ff:fea0:10ca"}], "active": true, "speed": 1000, "hw_timestamp_filters": []}, "ansible_nodename": "linux-node1.example.com", "ansible_product_name": "VMware Virtual Platform", "ansible_machine": "x86_64", "ansible_system_capabilities": ["cap_chown", "cap_dac_override", "cap_dac_read_search", "cap_fowner", "cap_fsetid", "cap_kill", "cap_setgid", "cap_setuid", "cap_setpcap", "cap_linux_immutable", "cap_net_bind_service", "cap_net_broadcast", "cap_net_admin", "cap_net_raw", "cap_ipc_lock", "cap_ipc_owner", "cap_sys_module", "cap_sys_rawio", "cap_sys_chroot", "cap_sys_ptrace", "cap_sys_pacct", "cap_sys_admin", "cap_sys_boot", "cap_sys_nice", "cap_sys_resource", "cap_sys_time", "cap_sys_tty_config", "cap_mknod", "cap_lease", "cap_audit_write", "cap_audit_control", "cap_setfcap", "cap_mac_override", "cap_mac_admin", "cap_syslog", "35", "36+ep"], "ansible_all_ipv4_addresses": ["192.168.56.11"], "ansible_python_version": "2.7.5"}}\r\n', b'Connection to 192.168.56.11 closed.\r\n')
ok: [192.168.56.11]
META: ran handlers

TASK [get date] ************************************************************************************************
task path: /etc/ansible/f4.yml:7
Using module file /usr/local/lib/python3.6/dist-packages/ansible-2.4.1.0-py3.6.egg/ansible/modules/commands/command.py
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<192.168.56.11> (0, b'/root\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949 `" && echo ansible-tmp-1531396858.131543-153072002529949="` echo /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949 `" ) && sleep 0'"'"''
<192.168.56.11> (0, b'ansible-tmp-1531396858.131543-153072002529949=/root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949\n', b'')
<192.168.56.11> PUT /tmp/tmpvtmja2wo TO /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/command.py
<192.168.56.11> SSH: EXEC sftp -b - -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 '[192.168.56.11]'
<192.168.56.11> (0, b'sftp> put /tmp/tmpvtmja2wo /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/command.py\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/ /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/command.py && sleep 0'"'"''
<192.168.56.11> (0, b'', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 -tt 192.168.56.11 '/bin/sh -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/command.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1531396858.131543-153072002529949/" > /dev/null 2>&1 && sleep 0'"'"''
<192.168.56.11> (0, b'\r\n{"changed": true, "end": "2018-07-12 20:00:58.966945", "stdout": "2018\\u5e74 07\\u6708 12\\u65e5 \\u661f\\u671f\\u56db 20:00:58 CST", "cmd": ["date"], "rc": 0, "start": "2018-07-12 20:00:58.964445", "stderr": "", "delta": "0:00:00.002500", "invocation": {"module_args": {"warn": true, "executable": null, "_uses_shell": false, "_raw_params": "date", "removes": null, "creates": null, "chdir": null, "stdin": null}}}\r\n', b'Connection to 192.168.56.11 closed.\r\n')
changed: [192.168.56.11] => {
    "changed": true,
    "cmd": [
        "date"
    ],
    "delta": "0:00:00.002500",
    "end": "2018-07-12 20:00:58.966945",
    "failed": false,
    "invocation": {
        "module_args": {
            "_raw_params": "date",
            "_uses_shell": false,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2018-07-12 20:00:58.964445",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "2018年 07月 12日 星期四 20:00:58 CST",
    "stdout_lines": [
        "2018年 07月 12日 星期四 20:00:58 CST"
    ]
}

TASK [touch file] **********************************************************************************************
task path: /etc/ansible/f4.yml:10
Using module file /usr/local/lib/python3.6/dist-packages/ansible-2.4.1.0-py3.6.egg/ansible/modules/commands/command.py
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<192.168.56.11> (0, b'/root\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299 `" && echo ansible-tmp-1531396858.9646013-174118352784299="` echo /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299 `" ) && sleep 0'"'"''
<192.168.56.11> (0, b'ansible-tmp-1531396858.9646013-174118352784299=/root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299\n', b'')
<192.168.56.11> PUT /tmp/tmpo3kyh0pw TO /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/command.py
<192.168.56.11> SSH: EXEC sftp -b - -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 '[192.168.56.11]'
<192.168.56.11> (0, b'sftp> put /tmp/tmpo3kyh0pw /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/command.py\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/ /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/command.py && sleep 0'"'"''
<192.168.56.11> (0, b'', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 -tt 192.168.56.11 '/bin/sh -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/command.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1531396858.9646013-174118352784299/" > /dev/null 2>&1 && sleep 0'"'"''
<192.168.56.11> (0, b'\r\n{"changed": true, "end": "2018-07-12 20:00:59.818106", "stdout": "", "cmd": "touch /tmp/devops.file", "rc": 0, "start": "2018-07-12 20:00:59.815108", "stderr": "", "delta": "0:00:00.002998", "invocation": {"module_args": {"warn": true, "executable": null, "_uses_shell": true, "_raw_params": "touch /tmp/devops.file", "removes": null, "creates": null, "chdir": null, "stdin": null}}, "warnings": ["Consider using file module with state=touch rather than running touch"]}\r\n', b'Connection to 192.168.56.11 closed.\r\n')
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11] => {
    "changed": true,
    "cmd": "touch /tmp/devops.file",
    "delta": "0:00:00.002998",
    "end": "2018-07-12 20:00:59.818106",
    "failed": false,
    "invocation": {
        "module_args": {
            "_raw_params": "touch /tmp/devops.file",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2018-07-12 20:00:59.815108",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "",
    "stdout_lines": []
}

TASK [echo date_output] ****************************************************************************************
task path: /etc/ansible/f4.yml:12
Using module file /usr/local/lib/python3.6/dist-packages/ansible-2.4.1.0-py3.6.egg/ansible/modules/commands/command.py
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<192.168.56.11> (0, b'/root\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393 `" && echo ansible-tmp-1531396859.8218389-268766387785393="` echo /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393 `" ) && sleep 0'"'"''
<192.168.56.11> (0, b'ansible-tmp-1531396859.8218389-268766387785393=/root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393\n', b'')
<192.168.56.11> PUT /tmp/tmp__kyifmp TO /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/command.py
<192.168.56.11> SSH: EXEC sftp -b - -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 '[192.168.56.11]'
<192.168.56.11> (0, b'sftp> put /tmp/tmp__kyifmp /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/command.py\n', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 192.168.56.11 '/bin/sh -c '"'"'chmod u+x /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/ /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/command.py && sleep 0'"'"''
<192.168.56.11> (0, b'', b'')
<192.168.56.11> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.56.11> SSH: EXEC ssh -o StrictHostKeyChecking=no -o StrictHostKeyChecking=no -o Port=22 -o 'IdentityFile="/home/devops/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=20 -tt 192.168.56.11 '/bin/sh -c '"'"'/usr/bin/python /root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/command.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1531396859.8218389-268766387785393/" > /dev/null 2>&1 && sleep 0'"'"''
<192.168.56.11> (0, b'\r\n{"changed": true, "end": "2018-07-12 20:01:00.692177", "stdout": "", "cmd": "echo 2018\\u5e74 07\\u6708 12\\u65e5 \\u661f\\u671f\\u56db 20:00:58 CST>/tmp/devops.file", "rc": 0, "start": "2018-07-12 20:01:00.689318", "stderr": "", "delta": "0:00:00.002859", "invocation": {"module_args": {"warn": true, "executable": null, "_uses_shell": true, "_raw_params": "echo 2018\\u5e74 07\\u6708 12\\u65e5 \\u661f\\u671f\\u56db 20:00:58 CST>/tmp/devops.file", "removes": null, "creates": null, "chdir": null, "stdin": null}}}\r\n', b'Connection to 192.168.56.11 closed.\r\n')
changed: [192.168.56.11] => {
    "changed": true,
    "cmd": "echo 2018年 07月 12日 星期四 20:00:58 CST>/tmp/devops.file",
    "delta": "0:00:00.002859",
    "end": "2018-07-12 20:01:00.692177",
    "failed": false,
    "invocation": {
        "module_args": {
            "_raw_params": "echo 2018年 07月 12日 星期四 20:00:58 CST>/tmp/devops.file",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2018-07-12 20:01:00.689318",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "",
    "stdout_lines": []
}
META: ran handlers
META: ran handlers

PLAY RECAP *****************************************************************************************************
192.168.56.11              : ok=4    changed=3    unreachable=0    failed=0

# 到执行服务器上查看文件内容
[root@linux-node1 tmp]# cat devops.file
2018年 07月 12日 星期四 20:00:58 CST
示例

基本语句

1、条件语句

  • when条件语句
devops@devops-virtual-machine:/etc/ansible$ cat f6.yml
---
- hosts : 192.168.56.11,192.168.56.131
  remote_user : root
  tasks:
  - name: "touch flag file"
    command: "touch /tmp/this_is_{{ansible_distribution}}_system"
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "7") or
          (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6")


# 执行
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f6.yml

PLAY [192.168.56.11,192.168.56.131] ****************************************************************************

TASK [Gathering Facts] *****************************************************************************************
ok: [192.168.56.131]
ok: [192.168.56.11]

TASK [touch flag file] *****************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]
changed: [192.168.56.131]

PLAY RECAP *****************************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0
192.168.56.131             : ok=2    changed=1    unreachable=0    failed=0
示例

2、循环语句

 

3、条件循环语句复用 

 示例:http://www.imooc.com/article/22753

 

异常处理和相关操作

 1、异常处理

  • 忽略错误

默认会检查命令和模块的返回状态,遇到错误就中断playbook的执行

加入参数:ignore_errors:yes

devops@devops-virtual-machine:/etc/ansible$ cat f11.yml
---
- hosts : 192.168.56.11
  remote_user : root
  tasks :
      - name : ignore false
        command : /bin/false
        ignore_errors: yes
      - name : touch a file
        file : path=/tmp/test2 state=touch mode=0700 owner=root group=root


# 执行
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f11.yml

PLAY [192.168.56.11] ***********************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.56.11]

TASK [ignore false] ************************************************************
fatal: [192.168.56.11]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.006306", "end": "2018-07-13 14:43:58.815566", "failed": true, "msg": "non-zero return code", "rc": 1, "start": "2018-07-13 14:43:58.809260", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
...ignoring

TASK [touch a file] ************************************************************
changed: [192.168.56.11]

PLAY RECAP *********************************************************************
192.168.56.11              : ok=3    changed=2    unreachable=0    failed=0
示例
  • 自定义错误

failed_when自定义错误

  • 自定义change状态
devops@devops-virtual-machine:/etc/ansible$ cat f13.yml
---
- hosts : 192.168.56.11
  remote_user : root
  tasks :
      - name : get process
        shell : touch /tmp/change_test
        changed_when : false


# 执行就没有change状态了
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f13.yml

PLAY [192.168.56.11] ************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************
ok: [192.168.56.11]

TASK [get process] **************************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

ok: [192.168.56.11]

PLAY RECAP **********************************************************************************************************************
192.168.56.11              : ok=2    changed=0    unreachable=0    failed=0
示例

tags标签处理

意义:通过tags和任务对象进行捆绑,控制部分或者指定的task执行

  • 打标签
对一个对象打一个标签
对一个对象打多个标签
打标签的对象包括:单个task任务、include对象、roles对象等
  • 标签使用
-t : 执行指定的tag标签任务
--skip-tags : 执行--skip-tags之外的标签任务

# 示例
devops@devops-virtual-machine:/etc/ansible$ cat f14.yml
---
- hosts : 192.168.56.11
  remote_user : root
  tasks :
      - name: create file 1
        shell: touch /tmp/file1.txt
        tags:
            - cfile1
            - cfile3
      - name: create file 2
        shell : touch /tmp/file2.txt
        tags:
            - cfile2


# 执行剧本
# 执行剧本,只执行tags为cfile1的任务
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f14.yml -t cfile1

PLAY [192.168.56.11] ************************************************************************************

TASK [Gathering Facts] **********************************************************************************
ok: [192.168.56.11]

TASK [create file 1]  ************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

PLAY RECAP **********************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0

# 执行剧本不包含tags为cfile1的任务
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f14.yml --skip-tags cfile1

PLAY [192.168.56.11] ************************************************************************************

TASK [Gathering Facts] **********************************************************************************
ok: [192.168.56.11]

TASK [create file 2] ************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

PLAY RECAP **********************************************************************************************
192.168.56.11              : ok=2    changed=1    unreachable=0    failed=0
示例

四、roles角色和场景演练

使用roles

1、include的用法

include_tasks/include: 动态的包含tasks任务列表执行
devops@devops-virtual-machine:/etc/ansible$ cat touchfile.yml
---
- name : create file 1
  shell : touch /tmp/file1.txt
  tags :
       - cfile1
       - cfile3
devops@devops-virtual-machine:/etc/ansible$ cat touchfile2.yml
---
- name : create file 2
  shell : touch /tmp/file2.txt
  tags :
       - cfile2

# 把touchfile.yml和touchfile2.yml两个剧本用include_tasks导入
devops@devops-virtual-machine:/etc/ansible$ cat f15.yml
---
- hosts : 192.168.56.11
  remote_user : root
  tasks :
        - include_tasks : touchfile.yml
        - include_tasks : touchfile2.yml


# 执行
devops@devops-virtual-machine:/etc/ansible$ ansible-playbook ./f15.yml

PLAY [192.168.56.11] ********************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************
ok: [192.168.56.11]

TASK [include_tasks] ********************************************************************************************************
included: /etc/ansible/touchfile.yml for 192.168.56.11

TASK [create file 1] ********************************************************************************************************
 [WARNING]: Consider using file module with state=touch rather than running touch

changed: [192.168.56.11]

TASK [include_tasks] ********************************************************************************************************
included: /etc/ansible/touchfile2.yml for 192.168.56.11

TASK [create file 2] ********************************************************************************************************
changed: [192.168.56.11]

PLAY RECAP ******************************************************************************************************************
192.168.56.11              : ok=5    changed=2    unreachable=0    failed=0
示例

2、为什么需要用到roles

  • 什么是roles
是一种利用在大型playbook中的剧本配置模式,有这自己特定结构
  • 为什么需要用到roles
和面向对象开发思想相似
利用大型的项目任务中,尽可能的将公共的任务、变量等内容独立

3、官方建议的剧本结构

原文:http://www.imooc.com/article/22924

大型项目中ansible playbook官方建议的目录结构

图片描述

ansible官方网站的建议playbook剧本结构如下:

production # 正式环境的inventory文件 
staging #测试环境用得inventory文件
group_vars/ # 机器组的变量文件
group1
group2
host_vars/ #执行机器成员的变量
hostname1
hostname2
================================================
site.yml # 主要的playbook剧本
webservers.yml # webserver类型服务所用的剧本
dbservers.yml # 数据库类型的服务所用的剧本
roles/
webservers/ #webservers这个角色相关任务和自定义变量
tasks/ # 任务存放目录
main.yml # 存放任务信息
handlers/
main.yml
vars/ # 存放变量的目录
main.yml # 存放变量信息
dbservers/ #dbservers这个角色相关任务和定义变量
...
common/ # 公共的
tasks/ #
main.yml #
handlers/ #
main.yml # handlers file.
vars/ # 角色所用到的变量
main.yml #
===============================================
templates/ #
ntp.conf.j2 # 模版文件
files/ # 用于上传存放文件的目录
bar.txt #
foo.sh #
meta/ # 角色的依赖
main.yml #

 

 

4、剧本设计思路

剧本roles设计思路一

剧本roles设计思路二

将公共任务、资源、变量等对象尽可能独立

五、场景演练

 Nginx工程方式的编译安装

剧本结构

devops@devops-virtual-machine:/etc/ansible$ tree ./
./
├── ansible.cfg
├── files                                      # 存放上传文件的目录
│   ├── imoocc.html                     # 测试用的html文件
│   ├── nginx                               # 系统init中,控制nginx启动脚本
│   └── nginx-1.9.11.tar.gz           # nginx的安装包文件
├── production                            # 线上的主机配置文件
├── roles                                    # roles角色执行的目录
│   ├── apache                           # 空目录可以定义不同角色如:apache、Nginx、MySQL等
│   ├── common                         # 存放公共信息目录
│   │   └── tasks
│   │   │     └── main.yaml
│   │   └── vars                          # 存放一些临时的变量,如:目录服务器(Nginx)压缩包文件存放临时目录,可以把这个临时目录当成变量存放在此目录下
│   │          └── main.yml
│   │  
│   ├── handlers
│   ├── meta                              # 存放不同角色依赖的的目录
│   ├── nginx
│   │   ├── handlers                    # handlers通过notify触发
│   │   │   └── main.yml              # 如:nginx的重启行为
│   │   ├── tasks                         # 任务存放目录
│   │   │   ├── basic.yml
│   │   │   ├── main.yml 
│   │   │   └── nginx.yml
│   │   └── vars
│   │       └── main.yml              # 存放nginx相关的变量
│   ├── tasks
│   │   └── main.yml
│   └── vars
│       └── main.yml
├── staging                                # 线下测试环境使用的主机配置文件
├── templates                            # 模版目录(配置、html)
│   └── imoocc_n.conf                    # nginx的自定义conf文件
├── webserver.retry
└── webserver.yml                     # web服务相关主执行文件

14 directories, 16 files

 

posted @ 2018-07-12 18:19  KubeSec  阅读(15656)  评论(0编辑  收藏  举报