ansible - Unable to switch to a different user using become_user
问题描述
I am writing Ansible playbook to create key-based ssh access on several hosts with a particular user. I have following servers:
automation_host
Master
Slave1
Slave2
From automation host I will trigger Ansible to run the playbook which should first login to master with user1, then switch to user2, create ssh keys with user2 and copy the id_rsa.pub to slave nodes.
Inventory file contents:
[master]
172.xxx.xxx.xxx
[slaves]
172.xxx.xxx.xxx
172.xxx.xxx.xxx
[all:vars]
ansible_connection=ssh
ansible_ssh_user=user1
playbook.yml file:
- hosts: master
become_user: user2
become: yes
roles:
- name: passwordless-ssh
User2 is available on all hosts (except automation_host) and is added in sudoers
as well.
In the passwordless-ssh role, I have added the lines included below to check which user is currently executing the tasks.
- name: get the username running the deploy
local_action: command whoami
register: username_on_the_host
- debug: var=username_on_the_host
Debug message shows user1 ( I am expecting it to be user2) ansible version: 2.5.2
I am very new to Ansible.
解决方案
local_action
will run on automation_host, change it to command
- hosts: master
become_user: user2
become: yes
tasks:
- name: get the username running the deploy
command: whoami
register: username_on_the_host
- debug: var=username_on_the_host['stdout']
- name: do something
command: echo 'hello'
when: username_on_the_host['stdout'] == 'user2'
- name: do something else
command: echo 'goodby'
when: username_on_the_host['stdout'] == 'user1'
Output
TASK [debug] *********************************************
ok: [master] => {
"username_on_the_host['stdout']": "user2"
}
TASK [do something] *********************************************
changed: [master]
TASK [do something else] *********************************************
do something else
does not run.
推荐阅读
- ruby-on-rails - Rails:向本地服务器发出获取请求时出错
- mysql - mysql映射两张表
- javascript - 带有 errorPlacement 和隐藏字段的复选框验证
- xamarin.forms - 如何设置 HttpClient 的 Content Type
- r - dplyr:如何按不同列中的单个变量取消分组
- python - 无法在 Python 3.7 中导入 psutil(导入错误)
- python - 谷歌云语音导入错误:无法导入名称“枚举”
- r - 获取一式三份记录的 rowSums 并仅保留具有最高值的记录
- laravel - 如何修复 Laravel 中的文件系统问题
- javascript - 对承诺感到困惑