如何在项目中使用Ansible命令?

Ray*_*Ray 4 ansible

我想将Ansible剧本配置为将某些行从/etc/hosts文件中复制到临时文件中。这应该很容易做到:

---
hosts: 127.0.0.1
gather_facts: False
tasks:
  - command: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup
    with_items:
      - web
      - database
Run Code Online (Sandbox Code Playgroud)

我认为这会起作用,但出现错误:

TypeError:字符串索引必须是整数,而不是str

我知道Ansible对于不加括号的括号很挑剔,因此我在整个命令行中都用双引号引起了注意,但仍然出现错误。

- command: "grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup"
Run Code Online (Sandbox Code Playgroud)

tec*_*raf 6

我不知道为什么会收到您声称得到的错误(如果您的系统向Ansible返回了奇怪的错误消息,则可能是与OS相关的事情)。

可以肯定的一件事是您不能在command模块中使用文件重定向。相反,您需要使用shell模块,因此将操作替换为:

- shell: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup
Run Code Online (Sandbox Code Playgroud)

除此之外with_items,您的任务没有问题。虽然没有-戏。

以下代码有效:

---
- hosts: 127.0.0.1
  gather_facts: False
  tasks:
    - shell: grep {{ item }} /etc/hosts >> /tmp/hosts_to_backup
      with_items:
        - web
        - database
Run Code Online (Sandbox Code Playgroud)