ansible use timestamp as vars

ansible 使用时间戳作为变量

- hosts: app_group
  remote_user: root
  gather_facts: yes    # 需要设定为yes(也可以省略),不然会提示ansible_date_time' is undefined
  vars:
    - VERSION:  v1.0.0
    - GIT_APP_NAME: HelloWorld
    - GIT_ADDR: git@github.com/yourname/helloworld.git
    - LOCAL_CODE_DIR: '/opt/ansible/yourname/code'
    - CMD_TIME: "{{ ansible_date_time.iso8601_basic_short }}"    # 获取系统时间戳
  tasks:

    - name: sync code to build server
      synchronize:
        src: "{{ LOCAL_CODE_DIR }}/{{ GIT_APP_NAME }}/" 
        dest: "/opt/src-{{ VERSION }}-{{ CMD_TIME }}"

    - name: 编译
      shell: "cd /opt/src-{{ VERSION }}-{{ CMD_TIME }}; make clean && make -j12;"

    - name: 同步新版本文件到本地
      synchronize
        src: "/opt/src-{{ VERSION }}-{{ CMD_TIME }}/helloworld"
        dest: "{{ LOCAL_CODE_DIR }}/helloworld_online/"
        mode: pull

    - name: 同步新版本文件到线上
      synchronize:
        src: "{{ LOCAL_CODE_DIR }}/helloworld_online/helloworld"
        dest: "/opt/helloworld/helloworld"

    - name: 计算线上md5值
      shell: "md5sum /opt/helloworld/helloworld |awk '{print $1}'"
      register: helloworld_online

    - name: 计算本地md5值
      shell: "md5sum {{ LOCAL_CODE_DIR }}/helloworld_online/helloworld | awk '{print $1}'"
      register: helloworld_local
      connection: local    # 表示在本地执行相关命令

    - name: md5 check
      debug:
        msg: 'remote: {{ helloworld_online.stdout }} local: {{ helloworld_local.stdout }}'

    - name: 本地与线上md5值对比成功重启服务(随机sleep 5秒,确保服务可用率)
      when: helloworld_online.stdout == helloworld_local.stdout
      shell: "sleep $((RANDOM % 5)) && cd /opt/helloworld/ && sh ./start.sh"
      args:
        executable: /bin/bash

ansible use timestamp as vars》上有1条评论

发表评论

电子邮件地址不会被公开。