Hearen
Hearen

Reputation: 7828

Impossible to source ~/.bash_aliases in Ansible

Using an alias in ~/.bash_aliases while $HOME=/home/ubuntu as:

alias k="kubectl -s http:xxxx"

k here stands for different commands in different servers, I have to use this feature but I just cannot source it in Ansible shell module.

Is there any other ways around it?

I read several posts:

And tried:

No - 1

  shell: ". /home/ubuntu/.bash_aliases && k get pods --all-namespaces | grep {{ serviceName }}"

No - 2

  shell: ". /home/ubuntu/.bashrc && k get pods --all-namespaces | grep {{ serviceName }}"

Result

Both of the above tries give me this error:

"/bin/sh: 1: k: not found"

No - 3

  shell: "source /home/ubuntu/.bash_aliases && k get pods --all-namespaces | grep {{ serviceName }}"
  args:
    executable: /bin/bash

No - 4

  shell: "source /home/ubuntu/.bashrc && k get pods --all-namespaces | grep {{ serviceName }}"
  args:
    executable: /bin/bash

Result

Both of the above tries give me this error:

"/bin/bash: k: command not found"

No - 5

   shell: "sudo -u ubuntu -i k get pods --all-namespaces | grep {{ serviceName }}"

Result

"-bash: k: command not found"

No - 6

shell: ssh -t localhost /bin/bash -ci 'k get pods --all-namespaces | grep {{ serviceName }}'

Result

"Pseudo-terminal will not be allocated because stdin is not a terminal.", "Host key verification failed."

No - 7

  shell: ssh -tt localhost /bin/bash -ci 'k get pods --all-namespaces | grep {{ serviceName }}'
  register: result

Result

"Host key verification failed."

A Walk-Around Solution for Me

  vars:
    - kubeCommand: ""

  tasks:

    - name: Get Command Alias
      shell: cat ~/.bash_aliases  |  awk -F[\"] '{print $2}'
      register: result

    - set_fact: kubeCommand={{ result.stdout }}

    - name: Get service 
      shell: "{{ kubeCommand }} get pods --all-namespaces | grep {{ serviceName }}"

But the question still stands here.

Any help will be appreciated :)

Upvotes: 5

Views: 2902

Answers (1)

JGK
JGK

Reputation: 4148

It's somewhat ugly, but you can put your alias k="kubectl -s http:xxxx" directly in .bashrc or source .bash_aliases from .bashrc and in your play you have to write:

shell: '/bin/bash -i -c "k get pods --all-namespaces | grep {{ serviceName }}"'

Upvotes: 5

Related Questions