【问题标题】:Use the response from shell inside yml for Ansible playbook在 yml 中使用来自 shell 的响应来获取 Ansible 剧本
【发布时间】:2017-10-24 15:23:15
【问题描述】:

我想通过 Ansible playbook 安装 MongoDB,我按照以下说明进行操作: https://www.howtoforge.com/tutorial/install-mongodb-on-ubuntu-16.04/

关于“步骤 2 - 创建源列表文件 MongoDB”的步骤

我应该使用:

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

当它使用以下命令获取 ubuntu 版本时:

$(lsb_release -sc)

如何通过 yml 文件执行并通过 ansible palybook 运行它? 我使用了下面的 yml 命令,但由于我在脚本中使用了 shell 命令“$(lsb_release -sc)”,所以它不起作用并给了我错误

- name: Create source list file MongoDB
  sudo: yes
  lineinfile: >
    line="deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.2 multiverse"
    dest=/etc/apt/sources.list.d/mongodb-org-3.2.list
    state=present
    create=yes

【问题讨论】:

  • 使用lineinfile 总是一个危险信号,您可以而且应该使用template 轻松做到这一点。此外,您可以使用{{ansible_distribution_release|lower }} 代替 lsb_release。

标签: ansible yaml


【解决方案1】:

Ansible 中有apt_repository 模块:

- apt_repository:
    repo: deb http://repo.mongodb.org/apt/ubuntu {{ ansible_distribution_release | lower }}/mongodb-org/3.2 multiverse
    state: present

【讨论】:

    【解决方案2】:

    您可以将一项任务的结果(包括其标准输出)注册为变量,然后在以后的任务中使用它:

    - name: Work out the distribution
      command: lsb_release -sc
      register: result
    
    - name: Create source list file MongoDB
      sudo: yes
      lineinfile: >
        line="deb http://repo.mongodb.org/apt/ubuntu {{ result.stdout }}/mongodb-org/3.2 multiverse"
        dest=/etc/apt/sources.list.d/mongodb-org-3.2.list
        state=present
        create=yes
    

    【讨论】:

    • 我是 yml 新手,从来不知道这个选项,非常感谢。
    • 没问题。您还会发现这是一个 ansible 功能,而不是 yaml 功能。
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2021-02-21
    • 2022-01-23
    相关资源
    最近更新 更多