-1

Now in a remote host, there is a file:/root/.c, which define an following alias command:

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

Then in my local host, I execute:

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

How can ansible execute the d command?

phwt
  • 1,356
  • 1
  • 22
  • 42
zhenpin
  • 1
  • 1

1 Answers1

0

Aliases are not expanded in a non-interactive shell.

Aliases are really meant only as a convenience for interactive sessions. If you want to make it easier for your non-interactive connections -- like Ansible -- to run a long command, just put it in a shell script. For example, make /root/connect-to-db.sh with the following content:

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

Make it executable (chmod 755 connect-to-db.sh), and then run your ansible command like this:

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

If you really need alias expansion to work, you could accomplish what you want with the following playbook:

---
- hosts: 10.10.130.30
  gather_facts: false
  tasks:
    - shell: |
        shopt -s expand_aliases
        . /root/.c
        d
      register: output

    - debug:
        msg: "{{ output.stdout_lines }}"

This won't work with the ad-hoc ansible command, because aliases aren't available on the same line or in the same function where they are defined. We need a multiline shell script in order for the shopt command to take effect before sourcing /root/.c.

larsks
  • 277,717
  • 41
  • 399
  • 399