'How to chain two Ansible module in one task
There is something I need to achieve in Ansible that I found no where to start.
I need to
- Login as a non-root user (remote_user: jane)
- Switch user to root after login (This user cannot login from SSH)
- Then switch to another user(nginx_user) from root to avoid password
- Execute a custom command using command module in Ansible
The reason that I have step2 and step3 is because if I switch from jane to nginx_user, the system will ask for password. While if I switch from root, then no password input is needed. The other fact is nginx_user has no password, if you just press enter while the system ask for password, it will fail to authenticate.
I started something like this, assume remote_user is set to jane.
- name: Task name
sudo_user: root
sudo: yes
# Need to switch to **nginx_user** before executing this command below
command: cp /var/www/a /var/www/b
The problem is, after the account is switched to root, I need to change the user to nginx_user before I can execute the command, is there a way to do this in Ansible?
Update:
The command module is just an example, I may need to use other module in my case instead, but it would require you to switch to nginx_user first, so I couldn't hack in the bash command.
Solution 1:[1]
If we talk about the problem rather than the attempted solution, things will become clear.
see 'the xy problem' (meta.stackexchange link).
From your attempt, it seems you want to copy /var/www/a
to /var/www/b
using nginx
instead of your ansible_user. I assume because you want to preserve ownership and permissions.
Fortunately, Ansible has an idempotent module which will do what you need.
- name: Copy 'a' to 'b'
become: yes
ansible.builtin.copy:
src: '/var/www/a'
dest: '/var/www/b'
owner: nginx
group: nginx
mode: '0644' # or whatever you want,
# but security best practice
# makes this the max for a file
backup: no # change to yes if you need to
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html
Solution 2:[2]
The usual aproach to this task is following:
Your remote user (I'd recommend an extra user solely for ansible tasks) should have passwordless sudo:
jane ALL=NOPASSWD: ALL
Keep your task as is, with sudo_user: nginx_user.
- name: Task name
sudo_user: nginx_user
sudo: yes
command: cp /var/www/a /var/www/b
Ansible does something like sudo su nginx_user
in that case, and as your remote user has passwordless sudo, no password is required.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jeter-work |
Solution 2 |