Best Practices

Tips and tricks

These tips and tricks have helped us optimize our Ansible usage, and we offer them here as suggestions. We hope they will help you organize content, write playbooks, maintain inventory, and execute Ansible. Ultimately, though, you should use Ansible in the way that makes most sense for your organization and your goals.

General tips

These concepts apply to all Ansible activities and artifacts.

Keep it simple

Whenever you can, do things simply. Use advanced features only when necessary, and select the feature that best matches your use case. For example, you will probably not need varsvars_filesvars_prompt and --extra-vars all at once, while also using an external inventory file. If something feels complicated, it probably is. Take the time to look for a simpler solution.

Use version control

Keep your playbooks, roles, inventory, and variables files in git or another version control system and make commits to the repository when you make changes. Version control gives you an audit trail describing when and why you changed the rules that automate your infrastructure.

Playbook tips

These tips help make playbooks and roles easier to read, maintain, and debug.

Use whitespace

Generous use of whitespace, for example, a blank line before each block or task, makes a playbook easy to scan.

Always name tasks

Task names are optional, but extremely useful. In its output, Ansible shows you the name of each task it runs. Choose names that describe what each task does and why.

Always mention the state

For many modules, the ‘state’ parameter is optional. Different modules have different default settings for ‘state’, and some modules support several ‘state’ settings. Explicitly setting ‘state=present’ or ‘state=absent’ makes playbooks and roles clearer.

Use comments

Even with task names and explicit state, sometimes a part of a playbook or role (or inventory/variable file) needs more explanation. Adding a comment (any line starting with ‘#’) helps others (and possibly yourself in future) understand what a play or task (or variable setting) does, how it does it, and why.

Inventory tips

These tips help keep your inventory well organized.

Use dynamic inventory with clouds

With cloud providers and other systems that maintain canonical lists of your infrastructure, use dynamic inventory to retrieve those lists instead of manually updating static inventory files. With cloud resources, you can use tags to differentiate production and staging environments.

Group inventory by function

A system can be in multiple groups. See How to build your inventory and Patterns: targeting hosts and groups. If you create groups named for the function of the nodes in the group, for example webservers or dbservers, your playbooks can target machines based on function. You can assign function-specific variables using the group variable system, and design Ansible roles to handle function-specific use cases. See Roles.

Separate production and staging inventory

You can keep your production environment separate from development, test, and staging environments by using separate inventory files or directories for each environment. This way you pick with -i what you are targeting. Keeping all your environments in one file can lead to surprises!

 

Keep vaulted variables safely visible

You should encrypt sensitive or secret variables with Ansible Vault. However, encrypting the variable names as well as the variable values makes it hard to find the source of the values. You can keep the names of your variables accessible (by grep, for example) without exposing any secrets by adding a layer of indirection:

  1. Create a group_vars/ subdirectory named after the group.

  2. Inside this subdirectory, create two files named vars and vault.

  3. In the vars file, define all of the variables needed, including any sensitive ones.

  4. Copy all of the sensitive variables over to the vault file and prefix these variables with vault_.

  5. Adjust the variables in the vars file to point to the matching vault_ variables using jinja2 syntax: db_password: {{ vault_db_password }}.

  6. Encrypt the vault file to protect its contents.

  7. Use the variable name from the vars file in your playbooks.

When running a playbook, Ansible finds the variables in the unencrypted file, which pulls the sensitive variable values from the encrypted file. There is no limit to the number of variable and vault files or their names.

Execution tricks

These tips apply to using Ansible, rather than to Ansible artifacts.

Try it in staging first

Testing changes in a staging environment before rolling them out in production is always a great idea. Your environments need not be the same size and you can use group variables to control the differences between those environments.

Update in batches

Use the ‘serial’ keyword to control how many machines you update at once in the batch. See Controlling where tasks run: delegation and local actions.

 

Handling OS and distro differences

Group variables files and the group_by module work together to help Ansible execute across a range of operating systems and distributions that require different settings, packages, and tools. The group_by module creates a dynamic group of hosts matching certain criteria. This group does not need to be defined in the inventory file. This approach lets you execute different tasks on different operating systems or distributions. For example:

---

 - name: talk to all hosts just so we can learn about them
   hosts: all
   tasks:
     - name: Classify hosts depending on their OS distribution
       group_by:
         key: os_{{ ansible_facts['distribution'] }}

 # now just on the CentOS hosts...

 - hosts: os_CentOS
   gather_facts: False
   tasks:
     - # tasks that only happen on CentOS go in this play

The first play categorizes all systems into dynamic groups based on the operating system name. Later plays can use these groups as patterns on the hosts line. You can also add group-specific settings in group vars files. All three names must match: the name created by the group_by task, the name of the pattern in subsequent plays, and the name of the group vars file. For example:

---
# file: group_vars/all
asdf: 10

---
# file: group_vars/os_CentOS.yml
asdf: 42

In this example, CentOS machines get the value of ‘42’ for asdf, but other machines get ‘10’. This can be used not only to set variables, but also to apply certain roles to only certain systems.

You can use the same setup with include_vars when you only need OS-specific variables, not tasks:

- hosts: all
  tasks:
    - name: Set OS distribution dependent variables
      include_vars: "os_{{ ansible_facts['distribution'] }}.yml"
    - debug:
        var: asdf

This pulls in variables from the group_vars/os_CentOS.yml file.

See also

YAML Syntax

Learn about YAML syntax

Working with playbooks

Review the basic playbook features

Collection Index

Browse existing collections, modules, and plugins

Should you develop a module?

Learn how to extend Ansible by writing your own modules

Patterns: targeting hosts and groups

Learn about how to select hosts

GitHub examples directory

Complete playbook files from the github project source

Mailing List

Questions? Help? Ideas? Stop by the list on Google Groups

Understanding privilege escalation: become

Ansible uses existing privilege escalation systems to execute tasks with root privileges or with another user’s permissions. Because this feature allows you to ‘become’ another user, different from the user that logged into the machine (remote user), we call it become. The become keyword leverages existing privilege escalation tools like sudosupfexecdoaspbrundzdoksurunasmachinectl and others.

    •  

Using become

You can control the use of become with play or task directives, connection variables, or at the command line. If you set privilege escalation properties in multiple ways, review the general precedence rules to understand which settings will be used.

A full list of all become plugins that are included in Ansible can be found in the Plugin List.

Become directives

You can set the directives that control become at the play or task level. You can override these by setting connection variables, which often differ from one host to another. These variables and directives are independent. For example, setting become_user does not set become.

become

set to yes to activate privilege escalation.

become_user

set to user with desired privileges — the user you become, NOT the user you login as. Does NOT imply become: yes, to allow it to be set at host level. Default value is root.

become_method

(at play or task level) overrides the default method set in ansible.cfg, set to use any of the Become Plugins.

become_flags

(at play or task level) permit the use of specific flags for the tasks or role. One common use is to change the user to nobody when the shell is set to nologin. Added in Ansible 2.2.

For example, to manage a system service (which requires root privileges) when connected as a non-root user, you can use the default value of become_user (root):

- name: Ensure the httpd service is running
  service:
    name: httpd
    state: started
  become: yes

To run a command as the apache user:

- name: Run a command as the apache user
  command: somecommand
  become: yes
  become_user: apache

To do something as the nobody user when the shell is nologin:

- name: Run a command as nobody
  command: somecommand
  become: yes
  become_method: su
  become_user: nobody
  become_flags: '-s /bin/sh'

To specify a password for sudo, run ansible-playbook with --ask-become-pass (-K for short). If you run a playbook utilizing become and the playbook seems to hang, most likely it is stuck at the privilege escalation prompt. Stop it with CTRL-c, then execute the playbook with -K and the appropriate password.

Become connection variables

You can define different become options for each managed node or group. You can define these variables in inventory or use them as normal variables.

ansible_become

equivalent of the become directive, decides if privilege escalation is used or not.

ansible_become_method

which privilege escalation method should be used

ansible_become_user

set the user you become through privilege escalation; does not imply ansible_become: yes

ansible_become_password

set the privilege escalation password. See Using encrypted variables and files for details on how to avoid having secrets in plain text

For example, if you want to run all tasks as root on a server named webserver, but you can only connect as the manager user, you could use an inventory entry like this:

webserver ansible_user=manager ansible_become=yes

Note

The variables defined above are generic for all become plugins but plugin specific ones can also be set instead. Please see the documentation for each plugin for a list of all options the plugin has and how they can be defined. A full list of become plugins in Ansible can be found at Become Plugins.

Become command-line options

--ask-become-pass-K

ask for privilege escalation password; does not imply become will be used. Note that this password will be used for all hosts.

--become-b

run operations with become (no password implied)

--become-method=BECOME_METHOD

privilege escalation method to use (default=sudo), valid choices: [ sudo | su | pbrun | pfexec | doas | dzdo | ksu | runas | machinectl ]

--become-user=BECOME_USER

run operations as this user (default=root), does not imply –become/-b

Risks and limitations of become

Although privilege escalation is mostly intuitive, there are a few limitations on how it works. Users should be aware of these to avoid surprises.

Risks of becoming an unprivileged user

Ansible modules are executed on the remote machine by first substituting the parameters into the module file, then copying the file to the remote machine, and finally executing it there.

Everything is fine if the module file is executed without using become, when the become_user is root, or when the connection to the remote machine is made as root. In these cases Ansible creates the module file with permissions that only allow reading by the user and root, or only allow reading by the unprivileged user being switched to.

However, when both the connection user and the become_user are unprivileged, the module file is written as the user that Ansible connects as, but the file needs to be readable by the user Ansible is set to become. In this case, Ansible makes the module file world-readable for the duration of the Ansible module execution. Once the module is done executing, Ansible deletes the temporary file.

If any of the parameters passed to the module are sensitive in nature, and you do not trust the client machines, then this is a potential danger.

Ways to resolve this include:

  • Use pipelining. When pipelining is enabled, Ansible does not save the module to a temporary file on the client. Instead it pipes the module to the remote python interpreter’s stdin. Pipelining does not work for python modules involving file transfer (for example: copyfetchtemplate), or for non-python modules.

  • Install POSIX.1e filesystem acl support on the managed host. If the temporary directory on the remote host is mounted with POSIX acls enabled and the setfacl tool is in the remote PATH then Ansible will use POSIX acls to share the module file with the second unprivileged user instead of having to make the file readable by everyone.

  • Avoid becoming an unprivileged user. Temporary files are protected by UNIX file permissions when you become root or do not use become. In Ansible 2.1 and above, UNIX file permissions are also secure if you make the connection to the managed machine as root and then use become to access an unprivileged account.

Warning

Although the Solaris ZFS filesystem has filesystem ACLs, the ACLs are not POSIX.1e filesystem acls (they are NFSv4 ACLs instead). Ansible cannot use these ACLs to manage its temp file permissions so you may have to resort to allow_world_readable_tmpfiles if the remote machines use ZFS.

Changed in version 2.1.

Ansible makes it hard to unknowingly use become insecurely. Starting in Ansible 2.1, Ansible defaults to issuing an error if it cannot execute securely with become. If you cannot use pipelining or POSIX ACLs, you must connect as an unprivileged user, you must use become to execute as a different unprivileged user, and you decide that your managed nodes are secure enough for the modules you want to run there to be world readable, you can turn on allow_world_readable_tmpfiles in the ansible.cfg file. Setting allow_world_readable_tmpfiles will change this from an error into a warning and allow the task to run as it did prior to 2.1.

Not supported by all connection plugins

Privilege escalation methods must also be supported by the connection plugin used. Most connection plugins will warn if they do not support become. Some will just ignore it as they always run as root (jail, chroot, and so on).

Only one method may be enabled per host

Methods cannot be chained. You cannot use sudo /bin/su - to become a user, you need to have privileges to run the command as that user in sudo or be able to su directly to it (the same for pbrun, pfexec or other supported methods).

Privilege escalation must be general

You cannot limit privilege escalation permissions to certain commands. Ansible does not always use a specific command to do something but runs modules (code) from a temporary file name which changes every time. If you have ‘/sbin/service’ or ‘/bin/chmod’ as the allowed commands this will fail with ansible as those paths won’t match with the temporary file that Ansible creates to run the module. If you have security rules that constrain your sudo/pbrun/doas environment to running specific command paths only, use Ansible from a special account that does not have this constraint, or use Red Hat Ansible Tower to manage indirect access to SSH credentials.

May not access environment variables populated by pamd_systemd

For most Linux distributions using systemd as their init, the default methods used by become do not open a new “session”, in the sense of systemd. Because the pam_systemd module will not fully initialize a new session, you might have surprises compared to a normal session opened through ssh: some environment variables set by pam_systemd, most notably XDG_RUNTIME_DIR, are not populated for the new user and instead inherited or just emptied.

This might cause trouble when trying to invoke systemd commands that depend on XDG_RUNTIME_DIR to access the bus:

$ echo $XDG_RUNTIME_DIR

$ systemctl --user status
Failed to connect to bus: Permission denied

To force become to open a new systemd session that goes through pam_systemd, you can use become_method: machinectl.

For more information, see this systemd issue.

 

Become and network automation

As of version 2.6, Ansible supports become for privilege escalation (entering enable mode or privileged EXEC mode) on all Ansible-maintained network platforms that support enable mode. Using become replaces the authorize and auth_pass options in a provider dictionary.

You must set the connection type to either connection: ansible.netcommon.network_cli or connection: ansible.netcommon.httpapi to use become for privilege escalation on network devices. Check the Platform Options documentation for details.

You can use escalated privileges on only the specific tasks that need them, on an entire play, or on all plays. Adding become: yes and become_method: enable instructs Ansible to enter enable mode before executing the task, play, or playbook where those parameters are set.

If you see this error message, the task that generated it requires enable mode to succeed:

Invalid input (privileged mode required)

To set enable mode for a specific task, add become at the task level:

- name: Gather facts (eos)
  arista.eos.eos_facts:
    gather_subset:
      - "!hardware"
  become: yes
  become_method: enable

To set enable mode for all tasks in a single play, add become at the play level:

- hosts: eos-switches
  become: yes
  become_method: enable
  tasks:
    - name: Gather facts (eos)
      arista.eos.eos_facts:
        gather_subset:
          - "!hardware"

Setting enable mode for all tasks

Often you wish for all tasks in all plays to run using privilege mode, that is best achieved by using group_vars:

group_vars/eos.yml

ansible_connection: ansible.netcommon.network_cli
ansible_network_os: arista.eos.eos
ansible_user: myuser
ansible_become: yes
ansible_become_method: enable

Passwords for enable mode

If you need a password to enter enable mode, you can specify it in one of two ways:

  • providing the --ask-become-pass command line option

  • setting the ansible_become_password connection variable

Warning

As a reminder passwords should never be stored in plain text. For information on encrypting your passwords and other secrets with Ansible Vault, see Encrypting content with Ansible Vault.

authorize and auth_pass

Ansible still supports enable mode with connection: local for legacy network playbooks. To enter enable mode with connection: local, use the module options authorize and auth_pass:

- hosts: eos-switches
  ansible_connection: local
  tasks:
    - name: Gather facts (eos)
      eos_facts:
        gather_subset:
          - "!hardware"
      provider:
        authorize: yes
        auth_pass: " {{ secret_auth_pass }}"

We recommend updating your playbooks to use become for network-device enable mode consistently. The use of authorize and of provider dictionaries will be deprecated in future. Check the Platform Options and Network modules documentation for details.

 

Become and Windows

Since Ansible 2.3, become can be used on Windows hosts through the runas method. Become on Windows uses the same inventory setup and invocation arguments as become on a non-Windows host, so the setup and variable names are the same as what is defined in this document.

While become can be used to assume the identity of another user, there are other uses for it with Windows hosts. One important use is to bypass some of the limitations that are imposed when running on WinRM, such as constrained network delegation or accessing forbidden system calls like the WUA API. You can use become with the same user as ansible_user to bypass these limitations and run commands that are not normally accessible in a WinRM session.

Administrative rights

Many tasks in Windows require administrative privileges to complete. When using the runas become method, Ansible will attempt to run the module with the full privileges that are available to the remote user. If it fails to elevate the user token, it will continue to use the limited token during execution.

A user must have the SeDebugPrivilege to run a become process with elevated privileges. This privilege is assigned to Administrators by default. If the debug privilege is not available, the become process will run with a limited set of privileges and groups.

To determine the type of token that Ansible was able to get, run the following task:

- Check my user name
  ansible.windows.win_whoami:
  become: yes

The output will look something similar to the below:

ok: [windows] => {
    "account": {
        "account_name": "vagrant-domain",
        "domain_name": "DOMAIN",
        "sid": "S-1-5-21-3088887838-4058132883-1884671576-1105",
        "type": "User"
    },
    "authentication_package": "Kerberos",
    "changed": false,
    "dns_domain_name": "DOMAIN.LOCAL",
    "groups": [
        {
            "account_name": "Administrators",
            "attributes": [
                "Mandatory",
                "Enabled by default",
                "Enabled",
                "Owner"
            ],
            "domain_name": "BUILTIN",
            "sid": "S-1-5-32-544",
            "type": "Alias"
        },
        {
            "account_name": "INTERACTIVE",
            "attributes": [
                "Mandatory",
                "Enabled by default",
                "Enabled"
            ],
            "domain_name": "NT AUTHORITY",
            "sid": "S-1-5-4",
            "type": "WellKnownGroup"
        },
    ],
    "impersonation_level": "SecurityAnonymous",
    "label": {
        "account_name": "High Mandatory Level",
        "domain_name": "Mandatory Label",
        "sid": "S-1-16-12288",
        "type": "Label"
    },
    "login_domain": "DOMAIN",
    "login_time": "2018-11-18T20:35:01.9696884+00:00",
    "logon_id": 114196830,
    "logon_server": "DC01",
    "logon_type": "Interactive",
    "privileges": {
        "SeBackupPrivilege": "disabled",
        "SeChangeNotifyPrivilege": "enabled-by-default",
        "SeCreateGlobalPrivilege": "enabled-by-default",
        "SeCreatePagefilePrivilege": "disabled",
        "SeCreateSymbolicLinkPrivilege": "disabled",
        "SeDebugPrivilege": "enabled",
        "SeDelegateSessionUserImpersonatePrivilege": "disabled",
        "SeImpersonatePrivilege": "enabled-by-default",
        "SeIncreaseBasePriorityPrivilege": "disabled",
        "SeIncreaseQuotaPrivilege": "disabled",
        "SeIncreaseWorkingSetPrivilege": "disabled",
        "SeLoadDriverPrivilege": "disabled",
        "SeManageVolumePrivilege": "disabled",
        "SeProfileSingleProcessPrivilege": "disabled",
        "SeRemoteShutdownPrivilege": "disabled",
        "SeRestorePrivilege": "disabled",
        "SeSecurityPrivilege": "disabled",
        "SeShutdownPrivilege": "disabled",
        "SeSystemEnvironmentPrivilege": "disabled",
        "SeSystemProfilePrivilege": "disabled",
        "SeSystemtimePrivilege": "disabled",
        "SeTakeOwnershipPrivilege": "disabled",
        "SeTimeZonePrivilege": "disabled",
        "SeUndockPrivilege": "disabled"
    },
    "rights": [
        "SeNetworkLogonRight",
        "SeBatchLogonRight",
        "SeInteractiveLogonRight",
        "SeRemoteInteractiveLogonRight"
    ],
    "token_type": "TokenPrimary",
    "upn": "vagrant-domain@DOMAIN.LOCAL",
    "user_flags": []
}

Under the label key, the account_name entry determines whether the user has Administrative rights. Here are the labels that can be returned and what they represent:

  • Medium: Ansible failed to get an elevated token and ran under a limited token. Only a subset of the privileges assigned to user are available during the module execution and the user does not have administrative rights.

  • High: An elevated token was used and all the privileges assigned to the user are available during the module execution.

  • System: The NT AUTHORITY\System account is used and has the highest level of privileges available.

The output will also show the list of privileges that have been granted to the user. When the privilege value is disabled, the privilege is assigned to the logon token but has not been enabled. In most scenarios these privileges are automatically enabled when required.

If running on a version of Ansible that is older than 2.5 or the normal runas escalation process fails, an elevated token can be retrieved by:

  • Set the become_user to System which has full control over the operating system.

  • Grant SeTcbPrivilege to the user Ansible connects with on WinRM. SeTcbPrivilege is a high-level privilege that grants full control over the operating system. No user is given this privilege by default, and care should be taken if you grant this privilege to a user or group. For more information on this privilege, please see Act as part of the operating system. You can use the below task to set this privilege on a Windows host:

    - name: grant the ansible user the SeTcbPrivilege right
      ansible.windows.win_user_right:
        name: SeTcbPrivilege
        users: '{{ansible_user}}'
        action: add
    
  • Turn UAC off on the host and reboot before trying to become the user. UAC is a security protocol that is designed to run accounts with the least privilege principle. You can turn UAC off by running the following tasks:

    - name: turn UAC off
      win_regedit:
        path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system
        name: EnableLUA
        data: 0
        type: dword
        state: present
      register: uac_result
    
    - name: reboot after disabling UAC
      win_reboot:
      when: uac_result is changed
    

Note

Granting the SeTcbPrivilege or turning UAC off can cause Windows security vulnerabilities and care should be given if these steps are taken.

Local service accounts

Prior to Ansible version 2.5, become only worked on Windows with a local or domain user account. Local service accounts like System or NetworkService could not be used as become_user in these older versions. This restriction has been lifted since the 2.5 release of Ansible. The three service accounts that can be set under become_user are:

  • System

  • NetworkService

  • LocalService

Because local service accounts do not have passwords, the ansible_become_password parameter is not required and is ignored if specified.

Become without setting a password

As of Ansible 2.8, become can be used to become a Windows local or domain account without requiring a password for that account. For this method to work, the following requirements must be met:

  • The connection user has the SeDebugPrivilege privilege assigned

  • The connection user is part of the BUILTIN\Administrators group

  • The become_user has either the SeBatchLogonRight or SeNetworkLogonRight user right

Using become without a password is achieved in one of two different methods:

  • Duplicating an existing logon session’s token if the account is already logged on

  • Using S4U to generate a logon token that is valid on the remote host only

In the first scenario, the become process is spawned from another logon of that user account. This could be an existing RDP logon, console logon, but this is not guaranteed to occur all the time. This is similar to the Run only when user is logged on option for a Scheduled Task.

In the case where another logon of the become account does not exist, S4U is used to create a new logon and run the module through that. This is similar to the Run whether user is logged on or not with the Do not store password option for a Scheduled Task. In this scenario, the become process will not be able to access any network resources like a normal WinRM process.

To make a distinction between using become with no password and becoming an account that has no password make sure to keep ansible_become_password as undefined or set ansible_become_password:.

Note

Because there are no guarantees an existing token will exist for a user when Ansible runs, there’s a high change the become process will only have access to local resources. Use become with a password if the task needs to access network resources

Accounts without a password

Warning

As a general security best practice, you should avoid allowing accounts without passwords.

Ansible can be used to become a Windows account that does not have a password (like the Guest account). To become an account without a password, set up the variables like normal but set ansible_become_password: ''.

Before become can work on an account like this, the local policy Accounts: Limit local account use of blank passwords to console logon only must be disabled. This can either be done through a Group Policy Object (GPO) or with this Ansible task:

- name: allow blank password on become
  ansible.windows.win_regedit:
    path: HKLM:\SYSTEM\CurrentControlSet\Control\Lsa
    name: LimitBlankPasswordUse
    data: 0
    type: dword
    state: present

Note

This is only for accounts that do not have a password. You still need to set the account’s password under ansible_become_password if the become_user has a password.

Become flags for Windows

Ansible 2.5 added the become_flags parameter to the runas become method. This parameter can be set using the become_flags task directive or set in Ansible’s configuration using ansible_become_flags. The two valid values that are initially supported for this parameter are logon_type and logon_flags.

Note

These flags should only be set when becoming a normal user account, not a local service account like LocalSystem.

The key logon_type sets the type of logon operation to perform. The value can be set to one of the following:

  • interactive: The default logon type. The process will be run under a context that is the same as when running a process locally. This bypasses all WinRM restrictions and is the recommended method to use.

  • batch: Runs the process under a batch context that is similar to a scheduled task with a password set. This should bypass most WinRM restrictions and is useful if the become_user is not allowed to log on interactively.

  • new_credentials: Runs under the same credentials as the calling user, but outbound connections are run under the context of the become_user and become_password, similar to runas.exe /netonly. The logon_flags flag should also be set to netcredentials_only. Use this flag if the process needs to access a network resource (like an SMB share) using a different set of credentials.

  • network: Runs the process under a network context without any cached credentials. This results in the same type of logon session as running a normal WinRM process without credential delegation, and operates under the same restrictions.

  • network_cleartext: Like the network logon type, but instead caches the credentials so it can access network resources. This is the same type of logon session as running a normal WinRM process with credential delegation.

For more information, see dwLogonType.

The logon_flags key specifies how Windows will log the user on when creating the new process. The value can be set to none or multiple of the following:

  • with_profile: The default logon flag set. The process will load the user’s profile in the HKEY_USERS registry key to HKEY_CURRENT_USER.

  • netcredentials_only: The process will use the same token as the caller but will use the become_user and become_password when accessing a remote resource. This is useful in inter-domain scenarios where there is no trust relationship, and should be used with the new_credentials logon_type.

By default logon_flags=with_profile is set, if the profile should not be loaded set logon_flags= or if the profile should be loaded with netcredentials_only, set logon_flags=with_profile,netcredentials_only.

For more information, see dwLogonFlags.

Here are some examples of how to use become_flags with Windows tasks:

- name: copy a file from a fileshare with custom credentials
  ansible.windows.win_copy:
    src: \\server\share\data\file.txt
    dest: C:\temp\file.txt
    remote_src: yes
  vars:
    ansible_become: yes
    ansible_become_method: runas
    ansible_become_user: DOMAIN\user
    ansible_become_password: Password01
    ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only

- name: run a command under a batch logon
  ansible.windows.win_whoami:
  become: yes
  become_flags: logon_type=batch

- name: run a command and not load the user profile
  ansible.windows.win_whomai:
  become: yes
  become_flags: logon_flags=

Limitations of become on Windows

  • Running a task with async and become on Windows Server 2008, 2008 R2 and Windows 7 only works when using Ansible 2.7 or newer.

  • By default, the become user logs on with an interactive session, so it must have the right to do so on the Windows host. If it does not inherit the SeAllowLogOnLocally privilege or inherits the SeDenyLogOnLocally privilege, the become process will fail. Either add the privilege or set the logon_type flag to change the logon type used.

  • Prior to Ansible version 2.3, become only worked when ansible_winrm_transport was either basic or credssp. This restriction has been lifted since the 2.4 release of Ansible for all hosts except Windows Server 2008 (non R2 version).

  • The Secondary Logon service seclogon must be running to use ansible_become_method: runas

Loops

Sometimes you want to repeat a task multiple times. In computer programming, this is called a loop. Common Ansible loops include changing ownership on several files and/or directories with the file module, creating multiple users with the user module, and repeating a polling step until a certain result is reached. Ansible offers two keywords for creating loops: loop and with_<lookup>.

Note

  • We added loop in Ansible 2.5. It is not yet a full replacement for with_<lookup>, but we recommend it for most use cases.

  • We have not deprecated the use of with_<lookup> – that syntax will still be valid for the foreseeable future.

  • We are looking to improve loop syntax – watch this page and the changelog for updates.

Comparing loop and with_*

  • The with_<lookup> keywords rely on Lookup Plugins – even items is a lookup.

  • The loop keyword is equivalent to with_list, and is the best choice for simple loops.

  • The loop keyword will not accept a string as input, see Ensuring list input for loop: using query rather than lookup.

  • Generally speaking, any use of with_* covered in Migrating from with_X to loop can be updated to use loop.

  • Be careful when changing with_items to loop, as with_items performed implicit single-level flattening. You may need to use flatten(1) with loop to match the exact outcome. For example, to get the same output as:

with_items:
  - 1
  - [2,3]
  - 4

you would need:

loop: "{{ [1, [2,3] ,4] | flatten(1) }}"
  • Any with_* statement that requires using lookup within a loop should not be converted to use the loop keyword. For example, instead of doing:

loop: "{{ lookup('fileglob', '*.txt', wantlist=True) }}"

it’s cleaner to keep:

with_fileglob: '*.txt'

Standard loops

Iterating over a simple list

Repeated tasks can be written as standard loops over a simple list of strings. You can define the list directly in the task:

- name: Add several users
  ansible.builtin.user:
    name: "{{ item }}"
    state: present
    groups: "wheel"
  loop:
     - testuser1
     - testuser2

You can define the list in a variables file, or in the ‘vars’ section of your play, then refer to the name of the list in the task:

loop: "{{ somelist }}"

Either of these examples would be the equivalent of:

- name: Add user testuser1
  ansible.builtin.user:
    name: "testuser1"
    state: present
    groups: "wheel"

- name: Add user testuser2
  ansible.builtin.user:
    name: "testuser2"
    state: present
    groups: "wheel"

You can pass a list directly to a parameter for some plugins. Most of the packaging modules, like yum and apt, have this capability. When available, passing the list to a parameter is better than looping over the task. For example:

- name: Optimal yum
  ansible.builtin.yum:
    name: "{{  list_of_packages  }}"
    state: present

- name: Non-optimal yum, slower and may cause issues with interdependencies
  ansible.builtin.yum:
    name: "{{  item  }}"
    state: present
  loop: "{{  list_of_packages  }}"

Check the module documentation to see if you can pass a list to any particular module’s parameter(s).

Iterating over a list of hashes

If you have a list of hashes, you can reference subkeys in a loop. For example:

- name: Add several users
  ansible.builtin.user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  loop:
    - { name: 'testuser1', groups: 'wheel' }
    - { name: 'testuser2', groups: 'root' }

When combining conditionals with a loop, the when: statement is processed separately for each item. See Basic conditionals with when for examples.

Iterating over a dictionary

To loop over a dict, use the dict2items:

- name: Using dict2items
  ansible.builtin.debug:
    msg: "{{ item.key }} - {{ item.value }}"
  loop: "{{ tag_data | dict2items }}"
  vars:
    tag_data:
      Environment: dev
      Application: payment

Here, we are iterating over tag_data and printing the key and the value from it.

Registering variables with a loop

You can register the output of a loop as a variable. For example:

- name: Register loop output as a variable
  ansible.builtin.shell: "echo {{ item }}"
  loop:
    - "one"
    - "two"
  register: echo

When you use register with a loop, the data structure placed in the variable will contain a results attribute that is a list of all responses from the module. This differs from the data structure returned when using register without a loop:

{
    "changed": true,
    "msg": "All items completed",
    "results": [
        {
            "changed": true,
            "cmd": "echo \"one\" ",
            "delta": "0:00:00.003110",
            "end": "2013-12-19 12:00:05.187153",
            "invocation": {
                "module_args": "echo \"one\"",
                "module_name": "shell"
            },
            "item": "one",
            "rc": 0,
            "start": "2013-12-19 12:00:05.184043",
            "stderr": "",
            "stdout": "one"
        },
        {
            "changed": true,
            "cmd": "echo \"two\" ",
            "delta": "0:00:00.002920",
            "end": "2013-12-19 12:00:05.245502",
            "invocation": {
                "module_args": "echo \"two\"",
                "module_name": "shell"
            },
            "item": "two",
            "rc": 0,
            "start": "2013-12-19 12:00:05.242582",
            "stderr": "",
            "stdout": "two"
        }
    ]
}

Subsequent loops over the registered variable to inspect the results may look like:

- name: Fail if return code is not 0
  ansible.builtin.fail:
    msg: "The command ({{ item.cmd }}) did not have a 0 return code"
  when: item.rc != 0
  loop: "{{ echo.results }}"

During iteration, the result of the current item will be placed in the variable:

- name: Place the result of the current item in the variable
  ansible.builtin.shell: echo "{{ item }}"
  loop:
    - one
    - two
  register: echo
  changed_when: echo.stdout != "one"

Complex loops

Iterating over nested lists

You can use Jinja2 expressions to iterate over complex lists. For example, a loop can combine nested lists:

- name: Give users access to multiple databases
  community.mysql.mysql_user:
    name: "{{ item[0] }}"
    priv: "{{ item[1] }}.*:ALL"
    append_privs: yes
    password: "foo"
  loop: "{{ ['alice', 'bob'] |product(['clientdb', 'employeedb', 'providerdb'])|list }}"

Retrying a task until a condition is met

New in version 1.4.

You can use the until keyword to retry a task until a certain condition is met. Here’s an example:

- name: Retry a task until a certain condition is met
  ansible.builtin.shell: /usr/bin/foo
  register: result
  until: result.stdout.find("all systems go") != -1
  retries: 5
  delay: 10

This task runs up to 5 times with a delay of 10 seconds between each attempt. If the result of any attempt has “all systems go” in its stdout, the task succeeds. The default value for “retries” is 3 and “delay” is 5.

To see the results of individual retries, run the play with -vv.

When you run a task with until and register the result as a variable, the registered variable will include a key called “attempts”, which records the number of the retries for the task.

Note

You must set the until parameter if you want a task to retry. If until is not defined, the value for the retries parameter is forced to 1.

Looping over inventory

To loop over your inventory, or just a subset of it, you can use a regular loop with the ansible_play_batch or groups variables:

- name: Show all the hosts in the inventory
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ groups['all'] }}"

- name: Show all the hosts in the current play
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ ansible_play_batch }}"

There is also a specific lookup plugin inventory_hostnames that can be used like this:

- name: Show all the hosts in the inventory
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ query('inventory_hostnames', 'all') }}"

- name: Show all the hosts matching the pattern, ie all but the group www
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ query('inventory_hostnames', 'all:!www') }}"

More information on the patterns can be found in Patterns: targeting hosts and groups.

Ensuring list input for loop: using query rather than lookup

The loop keyword requires a list as input, but the lookup keyword returns a string of comma-separated values by default. Ansible 2.5 introduced a new Jinja2 function named query that always returns a list, offering a simpler interface and more predictable output from lookup plugins when using the loop keyword.

You can force lookup to return a list to loop by using wantlist=True, or you can use query instead.

These examples do the same thing:

loop: "{{ query('inventory_hostnames', 'all') }}"

loop: "{{ lookup('inventory_hostnames', 'all', wantlist=True) }}"

Adding controls to loops

New in version 2.1.

The loop_control keyword lets you manage your loops in useful ways.

Limiting loop output with label

New in version 2.2.

When looping over complex data structures, the console output of your task can be enormous. To limit the displayed output, use the label directive with loop_control:

- name: Create servers
  digital_ocean:
    name: "{{ item.name }}"
    state: present
  loop:
    - name: server1
      disks: 3gb
      ram: 15Gb
      network:
        nic01: 100Gb
        nic02: 10Gb
        ...
  loop_control:
    label: "{{ item.name }}"

The output of this task will display just the name field for each item instead of the entire contents of the multi-line {{ item }} variable.

Note

This is for making console output more readable, not protecting sensitive data. If there is sensitive data in loop, set no_log: yes on the task to prevent disclosure.

Pausing within a loop

New in version 2.2.

To control the time (in seconds) between the execution of each item in a task loop, use the pause directive with loop_control:

# main.yml
- name: Create servers, pause 3s before creating next
  community.digitalocean.digital_ocean:
    name: "{{ item }}"
    state: present
  loop:
    - server1
    - server2
  loop_control:
    pause: 3

Tracking progress through a loop with index_var

New in version 2.5.

To keep track of where you are in a loop, use the index_var directive with loop_control. This directive specifies a variable name to contain the current loop index:

- name: Count our fruit
  ansible.builtin.debug:
    msg: "{{ item }} with index {{ my_idx }}"
  loop:
    - apple
    - banana
    - pear
  loop_control:
    index_var: my_idx

Note

index_var is 0 indexed.

Defining inner and outer variable names with loop_var

New in version 2.1.

You can nest two looping tasks using include_tasks. However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control:

# main.yml
- include_tasks: inner.yml
  loop:
    - 1
    - 2
    - 3
  loop_control:
    loop_var: outer_item

# inner.yml
- name: Print outer and inner items
  ansible.builtin.debug:
    msg: "outer item={{ outer_item }} inner item={{ item }}"
  loop:
    - a
    - b
    - c

Note

If Ansible detects that the current loop is using a variable which has already been defined, it will raise an error to fail the task.

Extended loop variables

New in version 2.8.

As of Ansible 2.8 you can get extended loop information using the extended option to loop control. This option will expose the following information.

Variable

Description

ansible_loop.allitems

The list of all items in the loop

ansible_loop.index

The current iteration of the loop. (1 indexed)

ansible_loop.index0

The current iteration of the loop. (0 indexed)

ansible_loop.revindex

The number of iterations from the end of the loop (1 indexed)

ansible_loop.revindex0

The number of iterations from the end of the loop (0 indexed)

ansible_loop.first

True if first iteration

ansible_loop.last

True if last iteration

ansible_loop.length

The number of items in the loop

ansible_loop.previtem

The item from the previous iteration of the loop. Undefined during the first iteration.

ansible_loop.nextitem

The item from the following iteration of the loop. Undefined during the last iteration.

loop_control:
  extended: yes

Accessing the name of your loop_var

New in version 2.8.

As of Ansible 2.8 you can get the name of the value provided to loop_control.loop_var using the ansible_loop_var variable

For role authors, writing roles that allow loops, instead of dictating the required loop_var value, you can gather the value via:

"{{ lookup('vars', ansible_loop_var) }}"

Migrating from with_X to loop

In most cases, loops work best with the loop keyword instead of with_X style loops. The loop syntax is usually best expressed using filters instead of more complex use of query or lookup.

These examples show how to convert many common with_ style loops to loop and filters.

with_list

with_list is directly replaced by loop.

- name: with_list
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_list:
    - one
    - two

- name: with_list -> loop
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop:
    - one
    - two

with_items

with_items is replaced by loop and the flatten filter.

- name: with_items
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_items: "{{ items }}"

- name: with_items -> loop
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ items|flatten(levels=1) }}"

with_indexed_items

with_indexed_items is replaced by loop, the flatten filter and loop_control.index_var.

- name: with_indexed_items
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  with_indexed_items: "{{ items }}"

- name: with_indexed_items -> loop
  ansible.builtin.debug:
    msg: "{{ index }} - {{ item }}"
  loop: "{{ items|flatten(levels=1) }}"
  loop_control:
    index_var: index

with_flattened

with_flattened is replaced by loop and the flatten filter.

- name: with_flattened
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_flattened: "{{ items }}"

- name: with_flattened -> loop
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ items|flatten }}"

with_together

with_together is replaced by loop and the zip filter.

- name: with_together
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  with_together:
    - "{{ list_one }}"
    - "{{ list_two }}"

- name: with_together -> loop
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  loop: "{{ list_one|zip(list_two)|list }}"

Another example with complex data

- name: with_together -> loop
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }} - {{ item.2 }}"
  loop: "{{ data[0]|zip(*data[1:])|list }}"
  vars:
    data:
      - ['a', 'b', 'c']
      - ['d', 'e', 'f']
      - ['g', 'h', 'i']

with_dict

with_dict can be substituted by loop and either the dictsort or dict2items filters.

- name: with_dict
  ansible.builtin.debug:
    msg: "{{ item.key }} - {{ item.value }}"
  with_dict: "{{ dictionary }}"

- name: with_dict -> loop (option 1)
  ansible.builtin.debug:
    msg: "{{ item.key }} - {{ item.value }}"
  loop: "{{ dictionary|dict2items }}"

- name: with_dict -> loop (option 2)
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  loop: "{{ dictionary|dictsort }}"

with_sequence

with_sequence is replaced by loop and the range function, and potentially the format filter.

- name: with_sequence
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_sequence: start=0 end=4 stride=2 format=testuser%02x

- name: with_sequence -> loop
  ansible.builtin.debug:
    msg: "{{ 'testuser%02x' | format(item) }}"
  # range is exclusive of the end point
  loop: "{{ range(0, 4 + 1, 2)|list }}"

with_subelements

with_subelements is replaced by loop and the subelements filter.

- name: with_subelements
  ansible.builtin.debug:
    msg: "{{ item.0.name }} - {{ item.1 }}"
  with_subelements:
    - "{{ users }}"
    - mysql.hosts

- name: with_subelements -> loop
  ansible.builtin.debug:
    msg: "{{ item.0.name }} - {{ item.1 }}"
  loop: "{{ users|subelements('mysql.hosts') }}"

with_nested/with_cartesian

with_nested and with_cartesian are replaced by loop and the product filter.

- name: with_nested
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  with_nested:
    - "{{ list_one }}"
    - "{{ list_two }}"

- name: with_nested -> loop
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  loop: "{{ list_one|product(list_two)|list }}"

with_random_choice

with_random_choice is replaced by just use of the random filter, without need of loop.

- name: with_random_choice
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_random_choice: "{{ my_list }}"

- name: with_random_choice -> loop (No loop is needed here)
  ansible.builtin.debug:
    msg: "{{ my_list|random }}"
  tags: random

See also

Intro to playbooks

An introduction to playbooks

Roles

Playbook organization by roles

Tips and tricks

Tips and tricks for playbooks

Conditionals

Conditional statements in playbooks

Using Variables

All about variables

User Mailing List

Have a question? Stop by the google group!

irc.freenode.net

#ansible IRC chat channel

Controlling where tasks run: delegation and local actions

By default Ansible gathers facts and executes all tasks on the machines that match the hosts line of your playbook. This page shows you how to delegate tasks to a different machine or group, delegate facts to specific machines or groups, or run an entire playbook locally. Using these approaches, you can manage inter-related environments precisely and efficiently. For example, when updating your webservers, you might need to remove them from a load-balanced pool temporarily. You cannot perform this task on the webservers themselves. By delegating the task to localhost, you keep all the tasks within the same play.

Tasks that cannot be delegated

Some tasks always execute on the controller. These tasks, including includeadd_host, and debug, cannot be delegated.

Delegating tasks

If you want to perform a task on one host with reference to other hosts, use the delegate_to keyword on a task. This is ideal for managing nodes in a load balanced pool or for controlling outage windows. You can use delegation with the serial keyword to control the number of hosts executing at one time:

---
- hosts: webservers
  serial: 5

  tasks:
    - name: Take out of load balancer pool
      ansible.builtin.command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
      delegate_to: 127.0.0.1

    - name: Actual steps would go here
      ansible.builtin.yum:
        name: acme-web-stack
        state: latest

    - name: Add back to load balancer pool
      ansible.builtin.command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
      delegate_to: 127.0.0.1

The first and third tasks in this play run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: local_action. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:

---
# ...

  tasks:
    - name: Take out of load balancer pool
      local_action: ansible.builtin.command /usr/bin/take_out_of_pool {{ inventory_hostname }}

# ...

    - name: Add back to load balancer pool
      local_action: ansible.builtin.command /usr/bin/add_back_to_pool {{ inventory_hostname }}

You can use a local action to call ‘rsync’ to recursively copy files to the managed servers:

---
# ...

  tasks:
    - name: Recursively copy files from management server to target
      local_action: ansible.builtin.command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/

Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync asks for a passphrase.

To specify more arguments, use the following syntax:

---
# ...

  tasks:
    - name: Send summary mail
      local_action:
        module: community.general.mail
        subject: "Summary Mail"
        to: "{{ mail_recipient }}"
        body: "{{ mail_body }}"
      run_once: True

The ansible_host variable reflects the host a task is delegated to.

Delegating facts

Delegating Ansible tasks is like delegating tasks in the real world – your groceries belong to you, even if someone else delivers them to your home. Similarly, any facts gathered by a delegated task are assigned by default to the inventory_hostname (the current host), not to the host which produced the facts (the delegated to host). To assign gathered facts to the delegated host instead of the current host, set delegate_facts to true:

---
- hosts: app_servers

  tasks:
    - name: Gather facts from db servers
      ansible.builtin.setup:
      delegate_to: "{{ item }}"
      delegate_facts: true
      loop: "{{ groups['dbservers'] }}"

This task gathers facts for the machines in the dbservers group and assigns the facts to those machines, even though the play targets the app_servers group. This way you can lookup hostvars[‘dbhost1’][‘ansible_default_ipv4’][‘address’] even though dbservers were not part of the play, or left out by using –limit.

Local playbooks

It may be useful to use a playbook locally on a remote host, rather than by connecting over SSH. This can be useful for assuring the configuration of a system by putting a playbook in a crontab. This may also be used to run a playbook inside an OS installer, such as an Anaconda kickstart.

To run an entire playbook locally, just set the hosts: line to hosts: 127.0.0.1 and then run the playbook like so:

ansible-playbook playbook.yml --connection=local

Alternatively, a local connection can be used in a single playbook play, even if other plays in the playbook use the default remote connection type:

---
- hosts: 127.0.0.1
  connection: local

Note

If you set the connection to local and there is no ansible_python_interpreter set, modules will run under /usr/bin/python and not under {{ ansible_playbook_python }}. Be sure to set ansible_python_interpreter: “{{ ansible_playbook_python }}” in host_vars/localhost.yml, for example. You can avoid this issue by using local_action or delegate_to: localhost instead.

See also

Intro to playbooks

An introduction to playbooks

Controlling playbook execution: strategies and more

More ways to control how and where Ansible executes

Ansible Examples on GitHub

Many examples of full-stack deployments

User Mailing List

Have a question? Stop by the google group!

irc.freenode.net

#ansible IRC chat channel