Programing

Ansible로 .bashrc를 소싱 할 수 없음

lottogame 2020. 10. 30. 07:36
반응형

Ansible로 .bashrc를 소싱 할 수 없음


나는 원격 호스트에 ssh하고 할 수 있습니다 source /home/username/.bashrc-모든 것이 잘 작동합니다. 그러나 내가 할 경우 :

- name: source bashrc
  sudo: no
  action: command source /home/username/.bashrc

나는 얻다:

failed: [hostname] => {"cmd": ["source", "/home/username/.bashrc"], "failed": true, "rc": 2}
msg: [Errno 2] No such file or directory

나는 내가 뭘 잘못하고 있는지 전혀 모른다 ...


ansible과 함께 소스를 사용하는 두 가지 옵션이 있습니다. 하나는 "shell :"명령과 / bin / sh (ansible 기본값)입니다. "소스"는 "." / bin / sh에서. 따라서 명령은 다음과 같습니다.

- name: source bashrc
  sudo: no   
  shell: . /home/username/.bashrc && [the actual command you want run]

bashrc b / c를 소싱 한 후 명령을 실행해야합니다. 각 ssh 세션은 별개입니다. 모든 ansible 명령은 별도의 ssh 트랜잭션에서 실행됩니다.

두 번째 옵션은 Ansible 셸이 bash를 사용하도록 강제하는 것입니다. 그러면 "source"명령을 사용할 수 있습니다.

- name: source bashrc
  sudo: no   
  shell: source /home/username/.bashrc && [the actual command you want run]
  args:
     executable: /bin/bash

마지막으로, Ubuntu 또는 이와 유사한 경우 로컬 로그인을보다 완벽하게 시뮬레이션하는 경우 실제로 "/ etc / profile"을 소스로 지정할 수 있습니다.


따라서 command실행 파일 만 실행됩니다. source그 자체로는 실행 파일이 아닙니다. (내장 쉘 명령입니다). source전체 환경 변수 를 원하는 이유가 있습니까?

Ansible에 환경 변수를 포함하는 다른 방법이 있습니다. 예를 들어, environment지시문 :

- name: My Great Playbook
  hosts: all
  tasks:
    - name: Run my command
      sudo: no
      action: command <your-command>
      environment:
          HOME: /home/myhome

또 다른 방법은 shellAnsible 모듈 을 사용하는 것입니다 .

- name: source bashrc
  sudo: no
  action: shell source /home/username/.bashrc && <your-command>

또는

- name: source bashrc
  sudo: no   
  shell: source /home/username/.bashrc && <your-command>

이러한 경우 Ansible 단계가 실행되면 셸 인스턴스 / 환경이 종료됩니다.


이 답변이 너무 늦었 음을 알고 있지만 sudo 옵션을 사용할 수있는 충분한 코드를 보았습니다 -i.

- name: source bashrc
  shell: sudo -iu {{ansible_user_id}} [the actual command you want run]

문서에서 말했듯이

The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a login shell.  This means that login-specific
               resource files such as .profile or .login will be read by the shell.  If a command is specified, it is passed to the shell for execution via the shell's -c option.
               If no command is specified, an interactive shell is executed.  sudo attempts to change to that user's home directory before running the shell.  It also initializes
               the environment to a minimal set of variables, similar to what is present when a user logs in.  The Command environment section below documents in detail how the -i
               option affects the environment in which a command is run.

Ubuntu 서버에서 virtualenvwrapper가 작동하도록 시도 할 때 이와 동일한 문제가 발생했습니다. 다음과 같이 Ansible을 사용했습니다.

- name: Make virtual environment
  shell: source /home/username/.bashrc && makevirtualenv virenvname
  args:
    executable: /bin/bash

그러나 소스 명령이 작동하지 않았습니다.

결국 .bashrc 파일의 맨 위에 Ansible이 호출 할 때 소스가 작동하지 못하게하는 몇 줄이 있음을 발견했습니다.

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

bashrc에서 해당 줄을 주석 처리했으며 그 후 모든 것이 예상대로 작동했습니다.


글쎄, 나열된 답변을 시도했지만 rbenv 통해 루비를 설치하는 동안 저에게 효과가 없었 습니다 . 나는 아래에서 줄을 구해야했다./root/.bash_profile

PATH=$PATH:$HOME/bin:$HOME/.rbenv/bin:$HOME/.rbenv/plugins/ruby-build/bin
export PATH
eval "$(rbenv init -)"

마침내 나는 이것을 생각해 냈습니다.

- shell: sudo su - root -c 'rbenv install -v {{ ruby_version }}'

어떤 명령으로도 이것을 사용할 수 있습니다.

- shell: sudo su - root -c 'your command'

나는 최고의 해결책이된다는 것을 알았다.

- name: Source .bashrc
  shell: . .bashrc
  become: true

다음을 추가하여 사용자를 변경할 수 있습니다 (기본값 : root).

- name: Source .bashrc
  shell: . .bashrc
  become: true
  become-user: {your_remote_user}

여기에 더 많은 정보 : Ansible이


위의 모든 옵션을 ansible 2.4.1.0으로 시도했으며 다른 두 개까지 아무도 작동하지 않으며 여기에 사례를 재현하는 세부 정보가 있습니다.

$ cat ~/.bash_aliases 
alias ta="echo 'this is test for ansible interactive shell'";

그리고 이것은 ansible 테스트입니다 .

- name: Check the basic string operations
  hosts: 127.0.0.1 
  connection: local

  tasks:
  - name: Test Interactive Bash Failure
    shell: ta
    ignore_errors: True

  - name: Test Interactive Bash Using Source
    shell: source ~/.bash_aliases && ta
    args:
      executable: /bin/bash
    ignore_errors: yes

  - name: Test Interactive Bash Using .
    shell: . ~/.bash_aliases && ta
    ignore_errors: yes

  - name: Test Interactive Bash Using /bin/bash -ci
    shell: /bin/bash -ic 'ta'
    register: result
    ignore_errors: yes

  - debug: msg="{{ result }}"

  - name: Test Interactive Bash Using sudo -ui
    shell: sudo -ui hearen ta
    register: result
    ignore_errors: yes

  - name: Test Interactive Bash Using ssh -tt localhost /bin/bash -ci
    shell: ssh -tt localhost /bin/bash -ci 'ta'
    register: result
    ignore_errors: yes

그리고 이것이 그 결과입니다.

$ ansible-playbook testInteractiveBash.yml 
 [WARNING]: Could not match supplied host pattern, ignoring: all

 [WARNING]: provided hosts list is empty, only localhost is available


PLAY [Check the basic string operations] ************************************************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************************************************
ok: [127.0.0.1]

TASK [Test Interactive Bash Failure] ****************************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": "ta", "delta": "0:00:00.001341", "end": "2018-10-31 10:11:39.485897", "failed": true, "msg": "non-zero return code", "rc": 127, "start": "2018-10-31 10:11:39.484556", "stderr": "/bin/sh: 1: ta: not found", "stderr_lines": ["/bin/sh: 1: ta: not found"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [Test Interactive Bash Using Source] ***********************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": "source ~/.bash_aliases && ta", "delta": "0:00:00.002769", "end": "2018-10-31 10:11:39.588352", "failed": true, "msg": "non-zero return code", "rc": 127, "start": "2018-10-31 10:11:39.585583", "stderr": "/bin/bash: ta: command not found", "stderr_lines": ["/bin/bash: ta: command not found"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [Test Interactive Bash Using .] ****************************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": ". ~/.bash_aliases && ta", "delta": "0:00:00.001425", "end": "2018-10-31 10:11:39.682609", "failed": true, "msg": "non-zero return code", "rc": 127, "start": "2018-10-31 10:11:39.681184", "stderr": "/bin/sh: 1: ta: not found", "stderr_lines": ["/bin/sh: 1: ta: not found"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [Test Interactive Bash Using /bin/bash -ci] ****************************************************************************************************************************************
changed: [127.0.0.1]

TASK [debug] ****************************************************************************************************************************************************************************
ok: [127.0.0.1] => {
    "msg": {
        "changed": true, 
        "cmd": "/bin/bash -ic 'ta'", 
        "delta": "0:00:00.414534", 
        "end": "2018-10-31 10:11:40.189365", 
        "failed": false, 
        "rc": 0, 
        "start": "2018-10-31 10:11:39.774831", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "this is test for ansible interactive shell", 
        "stdout_lines": [
            "this is test for ansible interactive shell"
        ]
    }
}

TASK [Test Interactive Bash Using sudo -ui] *********************************************************************************************************************************************
 [WARNING]: Consider using 'become', 'become_method', and 'become_user' rather than running sudo

fatal: [127.0.0.1]: FAILED! => {"changed": true, "cmd": "sudo -ui hearen ta", "delta": "0:00:00.007906", "end": "2018-10-31 10:11:40.306128", "failed": true, "msg": "non-zero return code", "rc": 1, "start": "2018-10-31 10:11:40.298222", "stderr": "sudo: unknown user: i\nsudo: unable to initialize policy plugin", "stderr_lines": ["sudo: unknown user: i", "sudo: unable to initialize policy plugin"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [Test Interactive Bash Using ssh -tt localhost /bin/bash -ci] **********************************************************************************************************************
hearen@localhost's password: 
changed: [127.0.0.1]

PLAY RECAP ******************************************************************************************************************************************************************************
127.0.0.1                  : ok=8    changed=6    unreachable=0    failed=0  

There are two options worked:

  • shell: /bin/bash -ic 'ta'
  • shell: ssh -tt localhost /bin/bash -ci 'ta' but this one requires password input locally.

My 2 cents, i circumnavigated the problem sourcing ~/.nvm/nvm.sh into ~/.profile and then using sudo -iu as suggested in another answer.

Tried on January 2018 vs Ubuntu 16.04.5

- name: Installing Nvm 
  shell: >
    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
  args:
    creates: "/home/{{ ansible_user }}/.nvm/nvm.sh"
  tags:
    - nodejs    

- name: Source nvm in ~/.profile
  sudo: yes
  sudo_user: "{{ ansible_user }}"
  lineinfile: >
    dest=~/.profile
    line="source ~/.nvm/nvm.sh"
    create=yes
  tags: 
    - nodejs
  register: output    

- name: Installing node 
  command: sudo -iu {{ ansible_user }} nvm install --lts
  args:
     executable: /bin/bash
  tags:
    - nodejs    

The right way should be:

- hosts: all
  tasks:
    - name: source bashrc file
      shell: "{{ item }}"
      with_items:
         - source ~/.bashrc
         - your other command

Note: it's test in ansible 2.0.2 version

참고URL : https://stackoverflow.com/questions/22256884/not-possible-to-source-bashrc-with-ansible

반응형