Ansible:如何从另一个调用剧本?

时间:2017-04-25 11:13:56

标签: ansible

我编写了一个简单的playbook来打印java进程ID和该PID的其他信息

[root@server thebigone]# cat check_java_pid.yaml
---
- hosts: all
  gather_facts: no

  tasks:
    - name: Check PID of existing Java process
      shell: "ps -ef | grep [j]ava"
      register: java_status

    - debug: var=java_status.stdout

当我用ansible-playbook check_java_pid.yaml调用它时,它工作正常。

现在我试图从另一个上面调用上面的剧本,但只针对特定主持人。所以我写了第二部剧本如下

    [root@server thebigone]# cat instance_restart.yaml
    ---
    - hosts: instance_1
      gather_facts: no

      tasks:
        - include: check_java_pid.yaml

但在执行ansible-playbook instance_restart.yaml时,我遇到了错误

    ERROR! no action detected in task. This often indicates a misspelled 
    module name, or incorrect module path.

    The error appears to have been in 
    '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but 
    may be elsewhere in the file depending on the exact syntax problem.

    The offending line appears to be:

     ---
     - hosts: all
       ^ here


      The error appears to have been in 
      '/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, 
      but may be elsewhere in the file depending on the exact syntax problem.

     The offending line appears to be:

      ---
      - hosts: all
        ^ here

它的语法错误,但没有一个真正的AFAIK,因为我已经执行了Playbook check_java_pid.yaml而没有任何问题。

请求您帮助理解此问题。

2 个答案:

答案 0 :(得分:10)

使用include on the task level Ansible期望文件只包含任务,而不是完整的剧本。然而,你提供了一个完整的剧本作为论据。

你可以做到(包括)on a play level,但它不会让你实现你想要的。

定义hosts: all的游戏将始终针对所有目标运行(除非您在命令调用或库存中限制它)。

此外,您将无法访问其他剧本中的java_status值(如果这是您的目标)。

您需要重新考虑您的结构,例如您可以提取任务并将其包含在两个游戏中:

my_tasks.yml

- name: Check PID of existing Java process
  shell: "ps -ef | grep [j]ava"
  register: java_status

  - debug: var=java_status.stdout

check_java_pid.yml

---
- hosts: all
  gather_facts: no

  tasks:
    - include my_tasks.yml

instance_restart.yml

---
- hosts: instance_1
  gather_facts: no

  tasks:
    - include: my_tasks.yml

答案 1 :(得分:0)

这里有官方文档中的示例。

https://docs.ansible.com/ansible/2.4/playbooks_reuse_includes.html

应用经证实的答案后,我和您的错误相同。我通过创建像这样的主剧本解决了问题:

   CREATE FUNCTION dbo.StringBeforeLastIndex(@source nvarchar(80), @pattern char)
   RETURNS nvarchar(80)
   BEGIN  
         DECLARE @lastIndex int
         SET @lastIndex = (LEN(@source)) -  CHARINDEX(@pattern, REVERSE(@source)) 

       RETURN SUBSTRING(@source, 0, @lastindex + 1) 

  END;  
  GO