IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    ansible文件内容替换+在远程主机上运行多个command

    bear发表于 2017-05-02 08:25:12
    love 0

    ansible在远程主机上进行文件内容替换可以使用lineinfile来实现,可以使用正则筛选到所需要的行,然后进行替换,本文进行了演示。

    ansible在远程主机上运行多个command,标准写法为

      - name: install an apple
        command: "{{item}}"
        with_items:
         - tar -xvzf /tmp/apple.tar.gz creates=/tmp/apple
         - /tmp/apple/install.sh --default creates=/etc/apple
         - rm -rf /tmp/apple
    

    实例
    假设有一个process.ymal

    - hosts: new
      user: admin
      vars:
         ps_env: "{{ ps_env }}"
      tasks:
       - name: push ~/.ssh/id_rsa/pub to remote .ssh/authorized_keys
         authorized_key: user=admin state=present key="{{ lookup('file', '/home/admin/.ssh/id_rsa.pub') }}"
    
       - name: push ump_agent_code to remote
         copy: src=/opt/zhukun/ump_agent/bin dest=/home/admin/zhukun owner=admin group=admin mode=644 backup=yes follow=yes
    
       - name: prepare the product/test enviroment of PS
         command: sed -i "s,stage,{{ ps_env }},g" /home/admin/zhukun/bin/config.json
    
       - name: prepare the product/test enviroment of PS
         lineinfile:
           dest: /home/admin/zhukun/bin/config.json
           regexp: '^.*[PRODUCT].*$'
           line: '"PRODUCT": "{{ ps_env }}"'
    
       - name: reboot the observer-agent service
         command: "{{ item }}"
         with_items:
          - ps -ef | grep /export/App/observer-agent.jd.local/bin | grep -v grep | awk '{ print $2}' | xargs kill
          - /export/App/observer-agent.jd.local/bin/start.sh
    
       - name: reboot the PS service
         command: ps -ef | grep /export/Packages/prediction_service/latest/prediction_service | grep -v grep | awk '{ print $2}' | xargs kill
    


    说明:
    第1个task是用来Push ssh公钥,第2个task是用来push文件到远程主机,关于详细使用请参考这篇文章;
    第3个task,调用远程command命令进行文件内容替换;
    第4个task,使用ansible自带的lineinfile模块,进行文件内容替换。使用regexp筛选出包含PRODUCT的行,并将该行修改为”PRODUCT”: “{{ ps_env }}”,其中ps_env会被ansible-playbook命令传递的参数替换掉

    ansible-playbook -i /opt/list process.ymal -e ps_env=rec_test -k
    

    此时,lineinfile模块,会将包含PRODUCT的行,并将该行修改为”PRODUCT”: “=rec_test”。



沪ICP备19023445号-2号
友情链接