2

I'm trying to install a package on a list of servers, these have a tag in common so I'm using that tag as they are all having Environment tag set to Dev. But the issue is some of them have OS as Amazon Linux (login works with ec2-user), some of them have Centos(Login works with CentOS user) and others are Ubuntu.

I have an option to execute a particular task using remote_user for that particular task but when I give user: centos the login works only on those servers where OS/user is centos and fails on others.

I'm looking for a solution where I can use an OR clause along with the user like if one user fails to log in it should try logging in with the second user.

1 Answer 1

2

The cleanest way would be to create three separate task files to do whatever you want and include the one for the specific distribution of the machine running the playbook. You can check this with the ansible_distribution condition. For example, add this to your playbook:

- include_tasks: install_amazon.yml
  when: ansible_distribution == 'Amazon'

- include_tasks: install_centos.yml
  when: ansible_distribution == 'CentOS'

- include_tasks: install_ubuntu.yml
  when: ansible_distribution == 'Ubuntu'

Then in the given tasks file you can specify the remote_user parameter. For example your install_centos.yml file could look like this:

---
- name: Install package as CentOS user
  yum:
    name: foo
    state: present
  remote_user: centos

This would install the foo package as user centos. You can do the same for the other tasks files.

3
  • 2
    I would recommend using ansible_distribution instead of ansible_os_family. Amazon Linux and Centos are part of the RedHat family. The ansible_distribution will return "Amazon" and CentOS respectively.
    – kenlukas
    Sep 18, 2018 at 11:59
  • @kenlukas Good point, missed that. Updated the answer accordingly. Thanks.
    – Oldskool
    Sep 18, 2018 at 12:03
  • Although, the solution seems pretty straightforward, I'm stuck with an error while trying to implement this: ERROR! 'when' is not a valid attribute for a Play. I have kept it small for now. My playbook is simply host: tag_Environment_DEV followed by include_tasks with when conditional saying ubuntu. But the error seems to suggest I can't user when with include_tasks. I tried creating a role then and called the role in main playbook but in that case I again tried to login into all servers with the local user with which I'm executing the playbook and gives error unreachable. Sep 21, 2018 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.