首页 > 解决方案 > 如何使用ansible替换环境变量

问题描述

我正在使用 ansible 自动化我的 DevOps 任务。在我的远程机器上,我有一个用于不同任务的配置文件。

env.conf文件有以下内容

IP=192.168.1.100
PORT=5250

#Other details here

我想做的是将 IP 值192.168.1.100和端口值 '5250' 替换为其他一些值

IP=NEW_IP
PORT=NEW_PORT

#Other details here

如何使用 ansible-playbook 文件实现这一点?

我知道 ansible 文件模块,但如何使用 ansible-playbook 文件替换环境变量的内容。

标签: ansible

解决方案


您正在寻找的是Ansible 模块 lineinfile。作为剧本,您可以使用以下内容:

- hosts: all
  vars:
    new_ip: 1.1.1.1
    new_port: 1234
  tasks:
    - file:
        path: /etc/env.conf
        state: touch
    - name: Substitute ip
      lineinfile:
        path: /etc/enc.conf
        regexp: '^IP='
        line: 'IP={{ new_ip }}'
    - name: Substitute port
      lineinfile:
        path: /etc/env.conf
        regexp: '^PORT='
        line: 'PORT={{ new_port }}'

推荐阅读