Ansible Inventory Variables – ansible_become_flags with Examples
Ansible, as a versatile IT automation tool, offers numerous configuration options defined in an Ansible inventory file. This file determines how Ansible interacts with managed hosts. One of these options, ansible_become_flags
, adds additional flexibility to privilege escalation. This blog post will delve into the ansible_become_flags
variable and provide examples of its usage.
Understanding ansible_become_flags
The ansible_become_flags
variable is used to pass flags to the privilege escalation program. Depending on the privilege escalation method you’re using (e.g., sudo, su, pbrun, etc.), you can pass additional arguments with ansible_become_flags
.
Defining ansible_become_flags in the Inventory File
To use ansible_become_flags
, you need to define it in your inventory file. The format would be alias ansible_host=your_actual_host ansible_user=your_user ansible_become=True ansible_become_flags='-E'
. Here’s an example:
Example with ansible_become_flags
Suppose you have a server with the IP address 192.168.1.100
, and you want Ansible to connect as the user deploy
and pass the -E
flag (which preserves the user environment) to the sudo
command. You would define this in your inventory file as follows:
1 |
my_server ansible_host=192.168.1.100 ansible_user=deploy ansible_become=True ansible_become_flags='-E' |
In this case, Ansible connects to my_server
and runs operations with the sudo
command, passing the -E
flag to preserve the user environment.
Using ansible_become_flags in a Playbook
Once ansible_become_flags
is defined in your inventory file, Ansible uses these settings when it connects to the host. Here’s an example playbook:
1 2 3 4 5 6 7 8 9 10 11 |
--- - hosts: my_server tasks: - name: Create a directory file: path: /opt/my_directory state: directory owner: root group: root mode: '0755' ... |
When you run this playbook, Ansible connects to my_server
(IP: 192.168.1.100
) as the deploy
user, and it uses sudo -E
(because ansible_become_flags='-E'
) for privilege escalation to create the directory.
Conclusion
The ansible_become_flags
inventory variable offers greater customization of Ansible operations by allowing you to specify additional flags to be passed to the privilege escalation program. This flexibility further illustrates Ansible’s capability to adapt to various automation needs.