2015-07-20 35 views
1

我正在编写一个Ansible角色以将Docker容器部署到主机。我的库存文件包含CoreOS和Ubuntu服务器,并且Docker已经安装在Ubuntu上,不允许非root用户使用(也就是我需要sudo docker ...)。 CoreOS主机不需要它。Ansible sudo模式取决于变量

我想写一个任务,如果需要,只使用sudo

- name: Start container XX 
    sudo: "{{ ansible_os_family and ansible_os_family == 'Debian' }}" 
    docker: 
    ... 

使用debug模块,我可以看到这个表达式返回“真”。

直接使用sudo: "True"工作正常。

但是使用给定的片段不起作用,sudo模式未启用。

如何有条件地使用sudo来实现我的目标?

+0

您是否尝试过使用'ansible_sudo'变量?检查谷歌,有关于这个错误报告,但它可能工作。 – magnetik

回答

0

我不熟悉docker模块itselve,但我看到了一个解决方案。您需要使用条件when以及任务中的附加参数:

- hosts: all 
    tasks: 
    - name: Debug message 
    debug: msg="{{ ansible_os_family and ansible_os_family == 'Debian' }}" 

    - name: Rooted 
    shell: service docker restart 
    sudo: True 
    when: "{{ ansible_os_family and ansible_os_family == 'Debian' }}|default(false)|bool" 

    - name: Not root 
    shell: service docker restart 
    # This will fail when sudo is needed. 
    # When you remove 'not' in condition you will see that 
    when: "not {{ ansible_os_family and ansible_os_family == 'Debian' }}|default(false)|bool" 
+0

我不喜欢复制代码,尤其是对于已经大约10行(许多docker参数)的任务,并且存在两个稍微不同的版本(用于容器的两种配置)。 Double'when' - > 4倍基本代码 - > meh:/ 但是,感谢解决方法! :) –