【问题标题】:How to execute a command which defined in a remote file with ansible?如何使用ansible执行在远程文件中定义的命令?
【发布时间】:2020-01-09 02:47:18
【问题描述】:

现在在远程主机中,有一个file:/root/.c,它定义了以下别名命令:

alias d="mysql -hxxxx -P3306 -uroot  --default-character-set=utf8 db2"

然后在我的本地主机中,我执行:

ansible 10.10.130.30 -m shell -a "source /root/.c && d -e 'show databases;'"
10.10.130.30 | FAILED | rc=127 >>
/bin/sh: d: command not foundnon-zero return code

ansible如何执行d命令?

【问题讨论】:

    标签: bash shell ansible alias


    【解决方案1】:

    Aliases are not expanded in a non-interactive shell.

    别名实际上只是为了方便交互式会话。如果您想让非交互式连接(如 Ansible)更容易运行长命令,只需将其放入 shell 脚本中即可。例如,使/root/connect-to-db.sh 具有以下内容:

    #!/bin/sh
    mysql -hxxxx -P3306 -uroot --default-character-set=utf8 db2 "$@"
    

    使其可执行 (chmod 755 connect-to-db.sh),然后像这样运行 ansible 命令:

    ansible 10.10.130.30 -m command -a "/root/connect-to-db.sh -e 'show databases'"
    

    如果您真的需要别名扩展才能工作,您可以使用以下剧本完成您想要的:

    ---
    - hosts: 10.10.130.30
      gather_facts: false
      tasks:
        - shell: |
            shopt -s expand_aliases
            . /root/.c
            d
          register: output
    
        - debug:
            msg: "{{ output.stdout_lines }}"
    

    这不适用于临时ansible 命令,因为aliases aren't available on the same line or in the same function where they are defined。为了让shopt 命令在获取/root/.c 之前生效,我们需要一个多行shell 脚本。

    【讨论】:

    • 因为远程主机属于其他公司,我不能这样做。还是谢谢
    • 我已经用其他信息更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多