1. Getting started with Ansible in Foreman

Use this guide to configure Foreman to use Ansible for remote execution.

1.1. Supported Ansible versions

Foreman uses Ansible as provided by the base operating system of Foreman server or any Smart Proxies for remote execution. Therefore, the supported version of Ansible depends on your base OS configuration.

1.2. Configuring your Foreman to run Ansible roles

In Foreman, you can import Ansible roles to help with automation of routine tasks. To enable Ansible on Foreman server, see Enabling Ansible integration with Foreman.

Ansible paths

Foreman imports and runs Ansible roles from the following paths:

  • /etc/ansible/roles

  • /usr/share/ansible/roles

  • /etc/ansible/collections

  • /usr/share/ansible/collections

Roles and collections from installed packages are placed under /usr/share/ansible. If you want to add custom roles or collections, place them under /etc/ansible.

The paths are configured by Foreman. For more information, see Customizing Ansible configuration.

Procedure
  1. Add the roles to a directory in an Ansible path on Foreman server and all Smart Proxy servers from where you want to use the roles. If you want to use custom or third party Ansible roles, ensure to configure an external version control system to synchronize roles between Foreman server and Smart Proxy servers.

  2. On all Smart Proxy servers that you want to use to run Ansible roles on hosts, enable the Ansible plugin:

    # foreman-installer --enable-foreman-proxy-plugin-ansible
  3. Distribute SSH keys to enable Smart Proxies to connect to hosts using SSH. For more information, see Distributing SSH Keys for Remote Execution in Managing hosts. Foreman runs Ansible roles the same way it runs remote execution jobs.

  4. Import the Ansible roles into Foreman.

  5. Proceed to Using Ansible roles to automate repetitive tasks on clients.

1.3. Enabling Ansible integration with Foreman

Perform the following procedure to enable the Ansible plugin on your Foreman server.

Procedure
  • Enable the Ansible plugin on your Foreman server:

    # foreman-installer \
    --enable-foreman-plugin-ansible \
    --enable-foreman-proxy-plugin-ansible

1.4. Importing Ansible roles and variables

You can import Ansible roles and variables from the Ansible paths on Foreman server or Smart Proxy servers that has Ansible enabled.

Prerequisites
  • Ensure that the roles and variables that you import are located in the Ansible paths on all Smart Proxies from where you want to use the roles.

Procedure
  1. In the Foreman web UI, navigate to Configure > Ansible > Roles.

  2. Click Import to select the Smart Proxy from which you want to import.

  3. Select the roles that you want to import.

  4. Click Submit.

1.5. Overriding Ansible variables in Foreman

If you run Ansible roles in Foreman, you can use Foreman to override Ansible variables for those roles.

The following procedure refers to hosts and host groups. For more information, see Managing hosts.

Precedence in overriding variables

If you use an Ansible role to run a task as a user that is not the Effective User, there is a strict order of precedence for overriding Ansible variables. To ensure the variable that you override follows the correct order of precedence, see Variable precedence: Where should I put a variable?

Prerequisites
  • You must have Ansible variables in Foreman. For more information, see Importing Ansible roles and variables

  • To use overridden Ansible variables, a user must have a role that allows them to see the attributes that are matched against hosts.

Procedure
  1. In the Foreman web UI, navigate to Configure > Ansible > Variables.

  2. Select the Ansible variable that you want to override and manage with Foreman.

  3. In the Default Behavior area, select the Override checkbox.

  4. In the Parameter Type field, select the value type for validation such as string or boolean. The types array and hash have further options for handling upon a variable match. For more information, see the Prioritize Attribute Order area below.

  5. In the Default Value field, enter the default value that you want to use if there is no match for the variable.

  6. Optional: If you do not want to display the value of the variable as plain text in the Foreman web UI, select the Hidden Value checkbox to display the content of the variable as asterisks. This is useful for sensitive values such as passwords or secret tokens.

  7. Optional: Expand the Optional Input Validator area and specify conditions that will be used to validate concrete values of the variable:

    • Select Required if you want to enforce users to fill in this variable.

    • In the Validator Type field, select how the value will be validated:

      • list – The value will be validated against an enumeration of allowed values.

      • regex – The value will be validated against a regular expression pattern.

  8. Optional: In the Prioritize Attribute Order area, specify the order of priority to match an override with a host by host attributes. Order at the top takes higher precedence. The first match wins.

    You can combine multiple attributes into a single matcher key using a comma as the AND operation. For example, the matcher key of hostgroup, environment would expect matchers such as hostgroup = "web servers" AND environment = production.

    If you use the parameter type array or hash, you can further set:

    • Merge Overrides – Merges members of the arrays/hashes instead of replacing the whole array or hash. If the hashes contain the same key, the value is overwritten by the value of the host.

    • Merge Default – Adds the default value to the array or hash.

    • Avoid Duplicates – Ensures that the values in the array or hash are unique.

  9. Optional: Expand the Specify Matchers area and specify criteria for selecting hosts on which the variable overrides.

  10. To save the override settings, click Submit.

To use the Ansible variable, add the variable as a parameter to your host or host group, or add the variable as a global parameter.

Adding the variable to a host
  1. In the Foreman web UI, navigate to Hosts > All Hosts and select the host that you want to use.

  2. Click the Ansible tab, and in the Variables area, click the pencil icon to edit the value of the variable.

  3. Click the tick icon to accept the value of the changed variable or the cross icon to cancel the change.

Adding the variable to a host group
  1. In the Foreman web UI, navigate to Configure > Host Groups, and select the host group that you want to use.

  2. Click the Parameters tab, and in the Host Group Parameters area, click Add Parameter.

  3. In the Name field, add the Ansible variable name.

  4. From the Type list, select the type of the variable for validation.

  5. In the Value field, enter the value for the variable.

Adding the variable as a global parameter
  1. In the Foreman web UI, navigate to Configure > Global Parameters, and click Create Parameter.

  2. In the Name field, add the Ansible variable name.

  3. From the Type list, select the type of the variable for validation.

  4. In the Value field, enter the value for the variable.

  5. Optional: If you do not want to display the Ansible variable in plain text, select the Hidden Values checkbox to display the content of the variable as asterisks in the Foreman web UI.

1.6. Adding Red Hat Enterprise Linux System Roles

Red Hat Enterprise Linux System Roles is a configuration interface to remotely manage Red Hat Enterprise Linux servers. You can use Red Hat Enterprise Linux System Roles to add Ansible roles in Foreman. Using Ansible Roles in Foreman can make configuration faster and easier.

Support levels for some of the Red Hat Enterprise Linux System Roles might be in Technology Preview. For up-to-date information about support levels and general information about Red Hat Enterprise Linux System Roles, see Red Hat Enterprise Linux System Roles.

Before subscribing to the Extras channels, see the Red Hat Enterprise Linux Extras Product Lifecycle article.

Procedure
  1. Ensure that the following repository is enabled:

    • On Red Hat Enterprise Linux 8, ensure that the Appstream repository is enabled:

      # subscription-manager repos --enable=rhel-8-for-x86_64-appstream-rpms

      You must enable an Appstream repository that is designated for your architecture.

    • On Red Hat Enterprise Linux 7, ensure that the Extras repository is enabled:

      # subscription-manager repos --enable=rhel-7-server-extras-rpms
  2. Install the rhel-system-roles package:

    # dnf install rhel-system-roles

    The rhel-system-roles package downloads to /usr/share/ansible/roles/. You can view and make any modifications that you want to the files before you import.

  3. In the Foreman web UI, navigate to Configure > Ansible > Roles.

  4. Click the Smart Proxy that contains the roles that you want to import.

  5. From the list of Ansible roles, select the checkbox of the roles you want to import, and then click Update.

You can now assign Ansible roles to hosts or host groups. For more information, see Assigning Ansible roles to an existing host.

You can also add the modules contained in these roles to your Ansible Playbooks by adding them to Ansible Job Templates. You must include the hosts:all line in the job template.

1.7. Synchronizing Ansible Collections

On Foreman, you can synchronize your Ansible Collections from any Ansible Galaxy and other Foreman instances. Ansible Collections will appear on Foreman as a new repository type in the Foreman web UI menu under Content after the sync.

Procedure
  1. In the Foreman web UI, navigate to Content > Products.

  2. Select the required product name.

  3. In the Products window, select the name of a product that you want to create a repository for.

  4. Click the Repositories tab, and then click New Repository.

  5. In the Name field, enter a name for the repository.

    The Label field is populated automatically based on the name.

  6. From the Type list, select ansible collection.

  7. In the Upstream URL field, enter the URL for the upstream collections repository.

    The URL can be any Ansible Galaxy endpoint. For example, https://galaxy.ansible.com.

  8. Optional: In the Requirements.yml field, you can specify the list of collections you want to sync from the endpoint, as well as their versions.

    If you do not specify the list of collections, everything from the endpoint will be synced.

    ---
    collections:
    - name: my_namespace.my_collection
      version: 1.2.3

    For more information, see Installing roles and collections from the same requirements.yml file in the Galaxy User Guide.

  9. Authenticate.

    1. To sync Foreman from Private Automation Hub, enter your token in the Auth Token field.

    2. To sync Foreman from console.redhat.com, enter your token in the Auth Token field and enter your SSO URL in the the Auth URL field.

    3. To sync Foreman from Foreman, leave both authentication fields blank.

  10. Click Save.

  11. Navigate to the Ansible Collections repository.

  12. From the Select Action menu, select Sync Now.

1.8. Customizing Ansible configuration

Foreman manages essential Ansible configuration that is required for Ansible integration with Foreman. However, you can customize other Ansible configuration options as usual.

Foreman stores the essential Ansible configuration as environment variables in /etc/foreman-proxy/ansible.env. This file is managed by foreman-installer.

Ansible reads configuration from a configuration file and the environment provided by Smart Proxy. If you need to customize Ansible configuration, you can do so in the system-wide /etc/ansible/ansible.cfg file or in the /usr/share/foreman-proxy/.ansible.cfg file in the home directory of the foreman-proxy user. Note that if you use /usr/share/foreman-proxy/.ansible.cfg, Ansible spawned by Foreman ignores configuration in /etc/ansible/ansible.cfg.

Note that environment variables take precedence over values in ansible.cfg, which ensures that the essential configuration required by Foreman is retained.

The following table lists the essential Ansible configuration options managed by Foreman.

Table 1. Essential Ansible configuration
Environment Variable Config Key Description

ANSIBLE_CALLBACKS_ENABLED

callbacks_enabled

Enables callback to Foreman; equivalent to callback_whitelist for cross-version compatibility

ANSIBLE_CALLBACK_WHITELIST

callback_whitelist

Enables callback to Foreman; equivalent to callbacks_enabled for cross-version compatibility

ANSIBLE_COLLECTIONS_PATHS

collections_paths

List of paths to Ansible collections

ANSIBLE_HOST_KEY_CHECKING

host_key_checking

Disables checking of host keys during SSH connection

ANSIBLE_LOCAL_TEMP

local_tmp

Temporary directory on Smart Proxy

ANSIBLE_ROLES_PATH

roles_path

List of paths to Ansible roles

ANSIBLE_SSH_ARGS

ssh_args

Arguments passed to SSH connection

Additional resources

1.9. Using Ansible Vault with Foreman

You can encrypt sensitive Ansible data files using the Ansible Vault tool and configure Ansible to access the encrypted files using a password stored in a file.

Procedure
  1. If you customized /etc/ansible/ansible.cfg, copy your configuration from /etc/ansible/ansible.cfg to /usr/share/foreman-proxy/.ansible.cfg.

  2. Encrypt the sensitive file using the ansible-vault command:

    # ansible-vault encrypt /etc/ansible/roles/Role_Name/vars/main.yml

    Note that ansible-vault changes the file permissions to 600.

  3. Change the group and permissions of the encrypted file to ensure that the foreman-proxy user can read it:

    # chgrp foreman-proxy /etc/ansible/roles/Role_Name/vars/main.yml
    # chmod 0640 /etc/ansible/roles/Role_Name/vars/main.yml
  4. Create the /usr/share/foreman-proxy/.ansible_vault_password file and enter the Vault password into it.

  5. Change the user and permissions of the .ansible_vault_password file to ensure that only the foreman-proxy user can read it:

    # chown foreman-proxy:foreman-proxy /usr/share/foreman-proxy/.ansible_vault_password
    # chmod 0400 /usr/share/foreman-proxy/.ansible_vault_password
  6. Add the path of the Vault password file to the [defaults] section in /usr/share/foreman-proxy/.ansible.cfg:

    [defaults]
    vault_password_file = /usr/share/foreman-proxy/.ansible_vault_password

    The path to the Vault password file must be absolute.

2. Using Ansible roles to automate repetitive tasks on clients

2.1. Assigning Ansible roles to an existing host

You can use Ansible roles for remote management of Foreman clients.

Prerequisites
  • Ensure that you have configured and imported Ansible roles.

Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts.

  2. Select the host and click Edit.

  3. On the Ansible Roles tab, select the role that you want to add from the Available Ansible Roles list.

  4. Click the + icon to add the role to the host. You can add more than one role.

  5. Click Submit.

After you assign Ansible roles to hosts, you can use Ansible for remote execution. For more information, see Distributing SSH keys for remote execution.

Overriding parameter variables

On the Parameters tab, click Add Parameter to add any parameter variables that you want to pass to job templates at run time. This includes all Ansible Playbook parameters and host parameters that you want to associate with the host. To use a parameter variable with an Ansible job template, you must add a Host Parameter.

2.2. Removing Ansible roles from a host

Use the following procedure to remove Ansible roles from a host.

Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts.

  2. Select the host and click Edit.

  3. Select the Ansible Roles tab.

  4. In the Assigned Ansible Roles area, click the - icon to remove the role from the host. Repeat to remove more roles.

  5. Click Submit.

2.3. Changing the order of Ansible roles

Use the following procedure to change the order of Ansible roles applied to a host.

Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts.

  2. Select a host.

  3. Select the Ansible Roles tab.

  4. In the Assigned Ansible Roles area, you can change the order of the roles by dragging and dropping the roles into the preferred position.

  5. Click Submit to save the order of the Ansible roles.

2.4. Running Ansible roles on a host

You can run Ansible roles on a host through the Foreman web UI.

Prerequisites
Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts.

  2. Select the checkbox of the host that contains the Ansible role you want to run.

  3. From the Select Action list, select Run all Ansible roles.

You can view the status of your Ansible job on the Run Ansible roles page. To rerun a job, click Rerun.

2.5. Assigning Ansible roles to a host group

You can use Ansible roles for remote management of Foreman clients.

Prerequisites
Procedure
  1. In the Foreman web UI, navigate to Configure > Host Groups.

  2. Click the host group name to which you want to assign an Ansible role.

  3. On the Ansible Roles tab, select the role that you want to add from the Available Ansible Roles list.

  4. Click the + icon to add the role to the host group. You can add more than one role.

  5. Click Submit.

2.6. Running Ansible roles on a host group

You can run Ansible roles on a host group through the Foreman web UI.

Prerequisites
  • You must configure your deployment to run Ansible roles. For more information, see Configuring your Foreman to run Ansible roles.

  • You must have assigned the Ansible roles to the host group.

  • You must have at least one host in your host group.

Procedure
  1. In the Foreman web UI, navigate to Configure > Host Groups.

  2. From the list in the Actions column for the host group, select Run all Ansible roles.

You can view the status of your Ansible job on the Run Ansible roles page. Click Rerun to rerun a job.

2.7. Running Ansible roles in check mode

You can run Ansible roles in check mode through the Foreman web UI.

Prerequisites
  • You must configure your deployment to run Ansible roles. For more information, see Configuring your Foreman to run Ansible roles.

  • You must have assigned the Ansible roles to the host group.

  • You must have at least one host in your host group.

Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts.

  2. Click Edit for the host you want to enable check mode for.

  3. In the Parameters tab, ensure that the host has a parameter named ansible_roles_check_mode with type boolean set to true.

  4. Click Submit.

3. Running an Ansible Playbook from Foreman

You can run an Ansible Playbook on a host or host group by executing a remote job in Foreman.

Limitation of host parameters in Ansible Playbook job templates

When you execute an Ansible Playbook on multiple hosts, Foreman renders the playbook for all hosts in the batch, but only uses the rendered playbook of the first host to execute it on all hosts in the batch. Therefore, you cannot modify the behavior of the playbook per host by using a host parameter in the template control flow constructs. Host parameters are translated into Ansible variables, so you can use them to control the behavior in native Ansible constructs. For more information, see BZ#2282275.

Prerequisites
Procedure
  1. In the Foreman web UI, navigate to Monitor > Jobs.

  2. Click Run Job.

  3. In Job category, select Ansible Playbook.

  4. In Job template, select Ansible - Run playbook.

  5. Click Next.

  6. Select the hosts on which you want to run the playbook.

  7. In the playbook field, paste the content of your Ansible Playbook.

  8. Follow the wizard to complete setting the remote job. For more information, see Executing a remote job.

  9. Click Submit to run the Ansible Playbook on your hosts.

Additional resources

4. Configuring and setting up remote jobs

Foreman supports remote execution of commands on hosts. Using remote execution, you can perform various tasks on multiple hosts simultaneously.

4.1. Remote execution in Foreman

With remote execution, you can run jobs on hosts from Smart Proxies by using shell scripts or Ansible roles and playbooks.

Use remote execution for the following benefits in Foreman:

  • Run jobs on multiple hosts at once.

  • Use variables in your commands for more granular control over the jobs you run.

  • Use host facts and parameters to populate the variable values.

  • Specify custom values for templates when you run the command.

Communication for remote execution occurs through Smart Proxy server, which means that Foreman server does not require direct access to the target host, and can scale to manage many hosts. For more information, see Transport modes for remote execution.

To use remote execution, you must define a job template. A job template is a command that you want to apply to remote hosts. You can execute a job template multiple times.

Foreman uses ERB syntax job templates. For more information, see Template Writing Reference in Managing hosts.

By default, Foreman includes several job templates for shell scripts and Ansible. For more information, see Setting up Job Templates in Managing hosts.

Additional resources

4.2. Remote execution workflow

For custom Ansible roles that you create, or roles that you download, you must install the package containing the roles on your Smart Proxy server. Before you can use Ansible roles, you must import the roles into Foreman from the Smart Proxy where they are installed.

When you run a remote job on hosts, for every host, Foreman performs the following actions to find a remote execution Smart Proxy to use.

Foreman searches only for Smart Proxies that have the Ansible feature enabled.

  1. Foreman finds the host’s interfaces that have the Remote execution checkbox selected.

  2. Foreman finds the subnets of these interfaces.

  3. Foreman finds remote execution Smart Proxies assigned to these subnets.

  4. From this set of Smart Proxies, Foreman selects the Smart Proxy that has the least number of running jobs. By doing this, Foreman ensures that the jobs load is balanced between remote execution Smart Proxies.

If you have enabled Prefer registered through Smart Proxy for remote execution, Foreman runs the REX job by using the Smart Proxy to which the host is registered.

By default, Prefer registered through Smart Proxy for remote execution is set to No. To enable it, in the Foreman web UI, navigate to Administer > Settings, and on the Content tab, set Prefer registered through Smart Proxy for remote execution to Yes. This ensures that Foreman performs REX jobs on hosts by the Smart Proxy to which they are registered to.

If Foreman does not find a remote execution Smart Proxy at this stage, and if the Fallback to Any Smart Proxy setting is enabled, Foreman adds another set of Smart Proxies to select the remote execution Smart Proxy from. Foreman selects the most lightly loaded Smart Proxy from the following types of Smart Proxies that are assigned to the host:

  • DHCP, DNS and TFTP Smart Proxies assigned to the host’s subnets

  • DNS Smart Proxy assigned to the host’s domain

  • Realm Smart Proxy assigned to the host’s realm

  • Puppet server Smart Proxy

  • Puppet CA Smart Proxy

  • OpenSCAP Smart Proxy

If Foreman does not find a remote execution Smart Proxy at this stage, and if the Enable Global Smart Proxy setting is enabled, Foreman selects the most lightly loaded remote execution Smart Proxy from the set of all Smart Proxies in the host’s organization and location to execute a remote job.

4.3. Permissions for remote execution

You can control which roles can run which jobs within your infrastructure, including which hosts they can target. The remote execution feature provides two built-in roles:

  • Remote Execution Manager: Can access all remote execution features and functionality.

  • Remote Execution User: Can only run jobs.

You can clone the Remote Execution User role and customize its filter for increased granularity. If you adjust the filter with the view_job_templates permission on a customized role, you can only see and trigger jobs based on matching job templates. You can use the view_hosts and view_smart_proxies permissions to limit which hosts or Smart Proxies are visible to the role.

The execute_template_invocation permission is a special permission that is checked immediately before execution of a job begins. This permission defines which job template you can run on a particular host. This allows for even more granularity when specifying permissions.

You can run remote execution jobs against Foreman and Smart Proxy registered as hosts to Foreman with the execute_jobs_on_infrastructure_hosts permission. Standard Manager and Site Manager roles have this permission by default. If you use either the Manager or Site Manager role, or if you use a custom role with the execute_jobs_on_infrastructure_hosts permission, you can execute remote jobs against registered Foreman and Smart Proxy hosts.

For more information on working with roles and permissions, see Creating and Managing Roles in Administering Foreman.

The following example shows filters for the execute_template_invocation permission:

name = Reboot and host.name = staging.example.com
name = Reboot and host.name ~ *.staging.example.com
name = "Restart service" and host_group.name = webservers

Use the first line in this example to apply the Reboot template to one selected host. Use the second line to define a pool of hosts with names ending with .staging.example.com. Use the third line to bind the template with a host group.

Note

Permissions assigned to users with these roles can change over time. If you have already scheduled some jobs to run in the future, and the permissions change, this can result in execution failure because permissions are checked immediately before job execution.

4.4. Transport modes for remote execution

You can configure your Foreman to use two different modes of transport for remote job execution. You can configure single Smart Proxy to use either one mode or the other but not both.

Push-based transport

On Smart Proxies in ssh mode, remote execution uses the SSH service to transport job details. This is the default transport mode. The SSH service must be enabled and active on the target hosts. The remote execution Smart Proxy must have access to the SSH port on the target hosts. Unless you have a different setting, the standard SSH port is 22.

This transport mode supports both Script and Ansible providers.

Pull-based transport

On Smart Proxies in pull-mqtt mode, remote execution uses Message Queueing Telemetry Transport (MQTT) to initiate the job execution it receives from Foreman server. The host subscribes to the MQTT broker on Smart Proxy for job notifications by using the yggdrasil pull client. After the host receives a notification from the MQTT broker, it pulls job details from Smart Proxy over HTTPS, runs the job, and reports results back to Smart Proxy.

This transport mode supports the Script provider only.

To use the pull-mqtt mode, you must enable it on Smart Proxy server and configure the pull client on hosts.

Note

If your Smart Proxy already uses the pull-mqtt mode and you want to switch back to the ssh mode, run this foreman-installer command:

# foreman-installer --foreman-proxy-plugin-remote-execution-script-mode=ssh
Additional resources

4.5. Configuring a host to use the pull client

For Smart Proxies configured to use pull-mqtt mode, hosts can subscribe to remote jobs using the remote execution pull client. Hosts do not require an SSH connection from their Smart Proxy server.

Prerequisites
  • You have registered the host to Foreman.

  • The Smart Proxy through which the host is registered is configured to use pull-mqtt mode. For more information, see Configuring pull-based transport for remote execution in Installing a Smart Proxy Server 3.12 on Enterprise Linux.

  • Foreman Client repository for the operating system version of the host is synchronized on Foreman server, available in the content view and the lifecycle environment of the host, and enabled for the host. For more information, see Changing the repository sets status for a host in Foreman in Managing content.

  • The host can communicate with its Smart Proxy over MQTT using port 1883.

  • The host can communicate with its Smart Proxy over HTTPS.

Procedure
  • Install the katello-pull-transport-migrate package on your host:

    • On Enterprise Linux 9 and Enterprise Linux 8 hosts:

      # dnf install katello-pull-transport-migrate
    • On Debian/Ubuntu hosts:

      # apt install katello-pull-transport-migrate
    • On SUSE Linux Enterprise Server hosts:

      # zypper install katello-pull-transport-migrate

    The package installs foreman_ygg_worker and yggdrasil as dependencies, configures the yggdrasil client, and starts the pull client worker on the host.

Verification
  • Check the status of the yggdrasild service:

    # systemctl status yggdrasild

4.6. Creating a job template

Use this procedure to create a job template. To use the CLI instead of the Foreman web UI, see the CLI procedure.

Procedure
  1. In the Foreman web UI, navigate to Hosts > Templates > Job templates.

  2. Click New Job Template.

  3. Click the Template tab, and in the Name field, enter a unique name for your job template.

  4. Select Default to make the template available for all organizations and locations.

  5. Create the template directly in the template editor or upload it from a text file by clicking Import.

  6. Optional: In the Audit Comment field, add information about the change.

  7. Click the Job tab, and in the Job category field, enter your own category or select from the default categories listed in Default Job Template Categories in Managing hosts.

  8. Optional: In the Description Format field, enter a description template. For example, Install package %{package_name}. You can also use %{template_name} and %{job_category} in your template.

  9. From the Provider Type list, select SSH for shell scripts and Ansible for Ansible tasks or playbooks.

  10. Optional: In the Timeout to kill field, enter a timeout value to terminate the job if it does not complete.

  11. Optional: Click Add Input to define an input parameter. Parameters are requested when executing the job and do not have to be defined in the template. For examples, see the Help tab.

  12. Optional: Click Foreign input set to include other templates in this job.

  13. Optional: In the Effective user area, configure a user if the command cannot use the default remote_execution_effective_user setting.

  14. Optional: If this template is a snippet to be included in other templates, click the Type tab and select Snippet.

  15. Optional: If you use the Ansible provider, click the Ansible tab. Select Enable Ansible Callback to allow hosts to send facts, which are used to create configuration reports, back to Foreman after a job finishes.

  16. Click the Location tab and add the locations where you want to use the template.

  17. Click the Organizations tab and add the organizations where you want to use the template.

  18. Click Submit to save your changes.

You can extend and customize job templates by including other templates in the template syntax. For more information, see Template Writing Reference and Job Template Examples and Extensions in Managing hosts.

CLI procedure
  • To create a job template using a template-definition file, enter the following command:

    # hammer job-template create \
    --file "Path_to_My_Template_File" \
    --job-category "My_Category_Name" \
    --name "My_Template_Name" \
    --provider-type SSH

4.7. Importing an Ansible Playbook by name

You can import Ansible Playbooks by name to Foreman from collections installed on Smart Proxy. Foreman creates a job template from the imported playbook and places the template in the Ansible Playbook - Imported job category.

If you have a custom collection, place it in /etc/ansible/collections/ansible_collections/My_Namespace/My_Collection.

Prerequisites
  • Ansible plugin is enabled.

  • Your Foreman account has a role that grants the import_ansible_playbooks permission.

Procedure
  1. Fetch the available Ansible Playbooks by using the following API request:

    $ curl \
    --header 'Content-Type: application/json' \
    --request GET \
    https://foreman.example.com/ansible/api/v2/ansible_playbooks/fetch?proxy_id=My_smart-proxy_ID
  2. Select the Ansible Playbook you want to import and note its name.

  3. Import the Ansible Playbook by its name:

    $ curl \
    --data '{ "playbook_names": ["My_Playbook_Name"] }' \
    --header 'Content-Type: application/json' \
    --request PUT \
    https://foreman.example.com/ansible/api/v2/ansible_playbooks/sync?proxy_id=My_smart-proxy_ID

    You get a notification in the Foreman web UI after the import completes.

Next steps
  • You can run the playbook by executing a remote job from the created job template. For more information, see Executing a remote job.

4.8. Importing all available Ansible Playbooks

You can import all the available Ansible Playbooks to Foreman from collections installed on Smart Proxy. Foreman creates job templates from the imported playbooks and places the templates in the Ansible Playbook - Imported job category.

If you have a custom collection, place it in /etc/ansible/collections/ansible_collections/My_Namespace/My_Collection.

Prerequisites
  • Ansible plugin is enabled.

  • Your Foreman account has a role that grants the import_ansible_playbooks permission.

Procedure
  • Import the Ansible Playbooks by using the following API request:

    # curl -X PUT -H 'Content-Type: application/json' https://foreman.example.com/ansible/api/v2/ansible_playbooks/sync?proxy_id=My_smart-proxy_ID

    You get a notification in the Foreman web UI after the import completes.

Next steps
  • You can run the playbooks by executing a remote job from the created job templates. For more information, see Executing a remote job.

4.9. Configuring the fallback to any Smart Proxy remote execution setting in Foreman

You can enable the Fallback to Any Smart Proxy setting to configure Foreman to search for remote execution Smart Proxies from the list of Smart Proxies that are assigned to hosts. This can be useful if you need to run remote jobs on hosts that have no subnets configured or if the hosts' subnets are assigned to Smart Proxies that do not have the remote execution feature enabled.

If the Fallback to Any Smart Proxy setting is enabled, Foreman adds another set of Smart Proxies to select the remote execution Smart Proxy from. Foreman also selects the most lightly loaded Smart Proxy from the set of all Smart Proxies assigned to the host, such as the following:

  • DHCP, DNS and TFTP Smart Proxies assigned to the host’s subnets

  • DNS Smart Proxy assigned to the host’s domain

  • Realm Smart Proxy assigned to the host’s realm

  • Puppet server Smart Proxy

  • Puppet CA Smart Proxy

  • OpenSCAP Smart Proxy

Procedure
  1. In the Foreman web UI, navigate to Administer > Settings.

  2. Click Remote Execution.

  3. Configure the Fallback to Any Smart Proxy setting.

CLI procedure
  • Enter the hammer settings set command on Foreman to configure the Fallback to Any Smart Proxy setting. To set the value to true, enter the following command:

    # hammer settings set \
    --name=remote_execution_fallback_proxy \
    --value=true

4.10. Configuring the global Smart Proxy remote execution setting in Foreman

By default, Foreman searches for remote execution Smart Proxies in hosts' organizations and locations regardless of whether Smart Proxies are assigned to hosts' subnets or not. You can disable the Enable Global Smart Proxy setting if you want to limit the search to the Smart Proxies that are assigned to hosts' subnets.

If the Enable Global Smart Proxy setting is enabled, Foreman adds another set of Smart Proxies to select the remote execution Smart Proxy from. Foreman also selects the most lightly loaded remote execution Smart Proxy from the set of all Smart Proxies in the host’s organization and location to execute a remote job.

Procedure
  1. In the Foreman web UI, navigate to Administer > Settings.

  2. Click Remote Execution.

  3. Configure the Enable Global Smart Proxy setting.

CLI procedure
  • Enter the hammer settings set command on Foreman to configure the Enable Global Smart Proxy setting. To set the value to true, enter the following command:

    # hammer settings set \
    --name=remote_execution_global_proxy \
    --value=true

4.11. Configuring Foreman to use an alternative directory to execute remote jobs on hosts

Ansible puts its own files it requires on the server side into the /tmp directory. You have the option to set a different directory if required.

Procedure
  1. On your Foreman server or Smart Proxy server, create a new directory:

    # mkdir /My_Remote_Working_Directory
  2. Copy the SELinux context from the default /tmp directory:

    # chcon --reference=/tmp /My_Remote_Working_Directory
  3. Configure your Foreman server or Smart Proxy server to use the new directory:

    # foreman-installer \
    --foreman-proxy-plugin-ansible-working-dir /My_Remote_Working_Directory

4.12. Altering the privilege elevation method

By default, push-based remote execution uses sudo to switch from the SSH user to the effective user that executes the script on your host. In some situations, you might require to use another method, such as su or dzdo. You can globally configure an alternative method in your Foreman settings.

Prerequisites
  • Your user account has a role assigned that grants the view_settings and edit_settings permissions.

  • If you want to use dzdo for Ansible jobs, ensure the community.general Ansible collection, which contains the required dzdo become plugin, is installed. For more information, see Installing collections in Ansible documentation.

Procedure
  1. Navigate to Administer > Settings.

  2. Select the Remote Execution tab.

  3. Click the value of the Effective User Method setting.

  4. Select the new value.

  5. Click Submit.

4.13. Distributing SSH keys for remote execution

For Smart Proxies in ssh mode, remote execution connections are authenticated using SSH. The public SSH key from Smart Proxy must be distributed to its attached hosts that you want to manage.

Ensure that the SSH service is enabled and running on the hosts. Configure any network or host-based firewalls to enable access to port 22.

Use one of the following methods to distribute the public SSH key from Smart Proxy to target hosts:

  1. Distributing SSH keys for remote execution manually.

  2. Using the Foreman API to obtain SSH keys for remote execution.

  3. Configuring a Kickstart template to distribute SSH keys during provisioning.

  4. For new Foreman hosts, you can deploy SSH keys to Foreman hosts during registration using the global registration template. For more information, see Registering a Host to Foreman Using the Global Registration Template in Managing hosts.

Foreman distributes SSH keys for the remote execution feature to the hosts provisioned from Foreman by default.

If the hosts are running on Amazon Web Services, enable password authentication. For more information, see New User Accounts.

4.14. Distributing SSH keys for remote execution manually

To distribute SSH keys manually, complete the following steps:

Procedure
  • Copy the SSH pub key from your Smart Proxy to your target host:

    # ssh-copy-id -i ~foreman-proxy/.ssh/id_rsa_foreman_proxy.pub root@client.example.com

    Repeat this step for each target host you want to manage.

Verification
  • To confirm that the key was successfully copied to the target host, enter the following command on Smart Proxy:

    # ssh -i ~foreman-proxy/.ssh/id_rsa_foreman_proxy root@client.example.com

4.15. Adding a passphrase to SSH key used for remote execution

By default, Smart Proxy uses a non-passphrase protected SSH key to execute remote jobs on hosts. You can protect the SSH key with a passphrase by following this procedure.

Procedure
  • On your Foreman server or Smart Proxy server, use ssh-keygen to add a passphrase to your SSH key:

    # ssh-keygen -p -f ~foreman-proxy/.ssh/id_rsa_foreman_proxy
Next steps
  • Users now must use a passphrase when running remote execution jobs on hosts.

4.16. Using the Foreman API to obtain SSH keys for remote execution

To use the Foreman API to download the public key from Smart Proxy, complete this procedure on each target host.

Procedure
  1. On the target host, create the ~/.ssh directory to store the SSH key:

    # mkdir ~/.ssh
  2. Download the SSH key from Smart Proxy:

    # curl https://smartproxy.example.com:9090/ssh/pubkey >> ~/.ssh/authorized_keys
  3. Configure permissions for the ~/.ssh directory:

    # chmod 700 ~/.ssh
  4. Configure permissions for the authorized_keys file:

    # chmod 600 ~/.ssh/authorized_keys

4.17. Configuring a AutoYaST template to distribute SSH keys during provisioning

You can add a remote_execution_ssh_keys snippet to your custom AutoYaST template to deploy SSH keys to hosts during provisioning. AutoYaST templates that Foreman ships include this snippet by default. Foreman copies the SSH key for remote execution to the systems during provisioning.

Procedure
  • To include the public key in newly-provisioned hosts, add the following snippet to the AutoYaST template that you use:

    <%= snippet 'remote_execution_ssh_keys' %>

4.18. Configuring a Kickstart template to distribute SSH keys during provisioning

You can add a remote_execution_ssh_keys snippet to your custom Kickstart template to deploy SSH keys to hosts during provisioning. Kickstart templates that Foreman ships include this snippet by default. Foreman copies the SSH key for remote execution to the systems during provisioning.

Procedure
  • To include the public key in newly-provisioned hosts, add the following snippet to the Kickstart template that you use:

    <%= snippet 'remote_execution_ssh_keys' %>

4.19. Configuring a Preseed template to distribute SSH keys during provisioning

You can add a remote_execution_ssh_keys snippet to your custom Preseed template to deploy SSH keys to hosts during provisioning. Preseed templates that Foreman ships include this snippet by default. Foreman copies the SSH key for remote execution to the systems during provisioning.

Procedure
  • To include the public key in newly-provisioned hosts, add the following snippet to the Preseed template that you use:

    <%= snippet 'remote_execution_ssh_keys' %>

4.20. Configuring a keytab for Kerberos ticket granting tickets

Use this procedure to configure Foreman to use a keytab to obtain Kerberos ticket granting tickets. If you do not set up a keytab, you must manually retrieve tickets.

Procedure
  1. Find the ID of the foreman-proxy user:

    # id -u foreman-proxy
  2. Modify the umask value so that new files have the permissions 600:

    # umask 077
  3. Create the directory for the keytab:

    # mkdir -p "/var/kerberos/krb5/user/My_User_ID"
  4. Create a keytab or copy an existing keytab to the directory:

    # cp My_Client.keytab /var/kerberos/krb5/user/My_User_ID/client.keytab
  5. Change the directory owner to the foreman-proxy user:

    # chown -R foreman-proxy:foreman-proxy "/var/kerberos/krb5/user/My_User_ID"
  6. Ensure that the keytab file is read-only:

    # chmod -wx "/var/kerberos/krb5/user/My_User_ID/client.keytab"
  7. Restore the SELinux context:

    # restorecon -RvF /var/kerberos/krb5

4.21. Configuring Kerberos authentication for remote execution

You can use Kerberos authentication to establish an SSH connection for remote execution on Foreman hosts.

Prerequisites
  • Enroll Foreman server on the Kerberos server

  • Enroll the Foreman target host on the Kerberos server

  • Configure and initialize a Kerberos user account for remote execution

  • Ensure that the foreman-proxy user on Foreman has a valid Kerberos ticket granting ticket

Procedure
  1. To install and enable Kerberos authentication for remote execution, enter the following command:

    # foreman-installer --foreman-proxy-plugin-remote-execution-script-ssh-kerberos-auth true
  2. To edit the default user for remote execution, in the Foreman web UI, navigate to Administer > Settings and click the Remote Execution tab. In the SSH User row, edit the second column and add the user name for the Kerberos account.

  3. Navigate to remote_execution_effective_user and edit the second column to add the user name for the Kerberos account.

Verification
  • To confirm that Kerberos authentication is ready to use, run a remote job on the host. For more information, see Executing a Remote Job in Configuring hosts by using Ansible.

4.22. Setting up job templates

Foreman provides default job templates that you can use for executing jobs. To view the list of job templates, navigate to Hosts > Templates > Job templates. If you want to use a template without making changes, proceed to Executing a Remote Job in Managing hosts.

You can use default templates as a base for developing your own. Default job templates are locked for editing. Clone the template and edit the clone.

Procedure
  1. To clone a template, in the Actions column, select Clone.

  2. Enter a unique name for the clone and click Submit to save the changes.

Job templates use the Embedded Ruby (ERB) syntax. For more information about writing templates, see the Template Writing Reference in Managing hosts.

Ansible considerations

To create an Ansible job template, use the following procedure and instead of ERB syntax, use YAML syntax. Begin the template with ---. You can embed an Ansible Playbook YAML file into the job template body. You can also add ERB syntax to customize your YAML Ansible template. You can also import Ansible Playbooks in Foreman. For more information, see Synchronizing Repository Templates in Managing hosts.

Parameter variables

At run time, job templates can accept parameter variables that you define for a host. Note that only the parameters visible on the Parameters tab at the host’s edit page can be used as input parameters for job templates.

4.23. Executing a remote job

You can execute a job that is based on a job template against one or more hosts.

Note

Ansible jobs run in batches on multiple hosts, so you cannot cancel a job running on a specific host. A job completes only after the Ansible Playbook runs on all hosts in the batch.

To use the CLI instead of the Foreman web UI, see the CLI procedure.

Procedure
  1. In the Foreman web UI, navigate to Monitor > Jobs and click Run job.

  2. Select the Job category and the Job template you want to use, then click Next.

  3. Select hosts on which you want to run the job. If you do not select any hosts, the job will run on all hosts you can see in the current context.

    Note

    If you want to select a host group and all of its subgroups, it is not sufficient to select the host group as the job would only run on hosts directly in that group and not on hosts in subgroups. Instead, you must either select the host group and all of its subgroups or use this search query:

    hostgroup_fullname ~ "My_Host_Group*"

    Replace My_Host_Group with the name of the top-level host group.

  4. If required, provide inputs for the job template. Different templates have different inputs and some templates do not have any inputs. After entering all the required inputs, click Next.

  5. Optional: To configure advanced settings for the job, fill in the Advanced fields. To learn more about advanced settings, see Advanced settings in the job wizard.

  6. Click Next.

  7. Schedule time for the job.

    • To execute the job immediately, keep the pre-selected Immediate execution.

    • To execute the job in future time, select Future execution.

    • To execute the job on regular basis, select Recurring execution.

  8. Optional: If you selected future or recurring execution, select the Query type, otherwise click Next.

    • Static query means that job executes on the exact list of hosts that you provided.

    • Dynamic query means that the list of hosts is evaluated just before the job is executed. If you entered the list of hosts based on some filter, the results can be different from when you first used that filter.

    Click Next after you have selected the query type.

  9. Optional: If you selected future or recurring execution, provide additional details:

    • For Future execution, enter the Starts at date and time. You also have the option to select the Starts before date and time. If the job cannot start before that time, it will be canceled.

    • For Recurring execution, select the start date and time, frequency, and the condition for ending the recurring job. You can choose the recurrence to never end, end at a certain time, or end after a given number of repetitions. You can also add Purpose - a special label for tracking the job. There can only be one active job with a given purpose at a time.

    Click Next after you have entered the required information.

  10. Review job details. You have the option to return to any part of the job wizard and edit the information.

  11. Click Submit to schedule the job for execution.

CLI procedure
  1. Enter the following command on Foreman:

    # hammer settings set \
    --name=remote_execution_global_proxy \
    --value=false
  2. Find the ID of the job template you want to use:

    # hammer job-template list
  3. Show the template details to see parameters required by your template:

    # hammer job-template info --id My_Template_ID
  4. Execute a remote job with custom parameters:

    # hammer job-invocation create \
    --inputs My_Key_1="My_Value_1",My_Key_2="My_Value_2",... \
    --job-template "My_Template_Name" \
    --search-query "My_Search_Query"

    Replace My_Search_Query with the filter expression that defines hosts, for example "name ~ My_Pattern".

Additional resources
  • For more information about creating, monitoring, or canceling remote jobs with Hammer CLI, enter hammer job-template --help and hammer job-invocation --help.

4.24. Advanced settings in the job wizard

Some job templates require you to enter advanced settings. Some of the advanced settings are only visible to certain job templates. Below is the list of general advanced settings.

SSH user

A user to be used for connecting to the host through SSH.

Effective user

A user to be used for executing the job. By default it is the SSH user. If it differs from the SSH user, su or sudo, depending on your settings, is used to switch the accounts.

  • If you set an effective user in the advanced settings, Ansible sets ansible_become_user to your input value and ansible_become to true. This means that if you use the parameters become: true and become_user: My_User within a playbook, these will be overwritten by Foreman.

  • If your SSH user and effective user are identical, Foreman does not overwrite the become_user. Therefore, you can set a custom become_user in your Ansible Playbook.

Description

A description template for the job.

Timeout to kill

Time in seconds from the start of the job after which the job should be killed if it is not finished already.

Time to pickup

Time in seconds after which the job is canceled if it is not picked up by a client. This setting only applies to hosts using pull-mqtt transport.

Password

Is used if SSH authentication method is a password instead of the SSH key.

Private key passphrase

Is used if SSH keys are protected by a passphrase.

Effective user password

Is used if effective user is different from the ssh user.

Concurrency level

Defines the maximum number of jobs executed at once. This can prevent overload of system resources in a case of executing the job on a large number of hosts.

Execution ordering

Determines the order in which the job is executed on hosts. It can be alphabetical or randomized.

4.25. Using extended cron lines

When scheduling a cron job with remote execution, you can use an extended cron line to specify the cadence of the job. The standard cron line contains five fields that specify minute, hour, day of the month, month, and day of the week. For example, 0 5 * * * stands for every day at 5 AM. If you want to learn more about the standard cron line, check crontab guru.

The extended cron line provides the following features:

You can use # to specify a concrete week day in a month

For example:

  • 0 0 * * mon#1 specifies first Monday of the month

  • 0 0 * * fri#3,fri#4 specifies 3rd and 4th Fridays of the month

  • 0 7 * * fri#-1 specifies the last Friday of the month at 07:00

  • 0 7 * * fri#L also specifies the last Friday of the month at 07:00

  • 0 23 * * mon#2,tue specifies the 2nd Monday of the month and every Tuesday, at 23:00

You can use % to specify every n-th day of the month

For example:

  • 9 0 * * sun%2 specifies every other Sunday at 00:09

  • 0 0 * * sun%2+1 specifies every odd Sunday

  • 9 0 * * sun%2,tue%3 specifies every other Sunday and every third Tuesday

You can use & to specify that the day of the month has to match the day of the week

For example:

  • 0 0 30 * 1& specifies 30th day of the month, but only if it is Monday

4.26. Scheduling a recurring Ansible job for a host

You can schedule a recurring job to run Ansible roles on hosts.

Prerequisites
  • Ensure you have the view_foreman_tasks, view_job_invocations, and view_recurring_logics permissions.

Procedure
  1. In the Foreman web UI, navigate to Hosts > All Hosts and select the target host on which you want to execute a remote job.

  2. On the Ansible tab, select Jobs.

  3. Click Schedule recurring job.

  4. Define the repetition frequency, start time, and date of the first run in the Create New Recurring Ansible Run window.

  5. Click Submit.

  6. Optional: View the scheduled Ansible job in host overview or by navigating to Ansible > Jobs.

4.27. Scheduling a recurring Ansible job for a host group

You can schedule a recurring job to run Ansible roles on host groups.

Procedure
  1. In the Foreman web UI, navigate to Configure > Host groups.

  2. In the Actions column, select Configure Ansible Job for the host group you want to schedule an Ansible roles run for.

  3. Click Schedule recurring job.

  4. Define the repetition frequency, start time, and date of the first run in the Create New Recurring Ansible Run window.

  5. Click Submit.

4.28. Using Ansible provider for package and errata actions

By default, Foreman is configured to use the Script provider templates for remote execution jobs. If you prefer using Ansible job templates for your remote jobs, you can configure Foreman to use them by default for remote execution features associated with them.

Note

Remember that Ansible job templates only work when remote execution is configured for ssh mode.

Procedure
  1. In the Foreman web UI, navigate to Administer > Remote Execution Features.

  2. Find each feature whose name contains by_search.

  3. Change the job template for these features from Katello Script Default to Katello Ansible Default.

  4. Click Submit.

Foreman now uses Ansible provider templates for remote execution jobs by which you can perform package and errata actions. This applies to job invocations from the Foreman web UI as well as by using hammer job-invocation create with the same remote execution features that you have changed.

4.29. Setting the job rate limit on Smart Proxy

You can limit the maximum number of active jobs on a Smart Proxy at a time to prevent performance spikes. The job is active from the time Smart Proxy first tries to notify the host about the job until the job is finished on the host.

The job rate limit only applies to mqtt based jobs.

Note

The optimal maximum number of active jobs depends on the computing resources of your Smart Proxy server. By default, the maximum number of active jobs is unlimited.

Procedure
  • Set the maximum number of active jobs using foreman-installer:

    # foreman-installer \
    --foreman-proxy-plugin-remote-execution-script-mqtt-rate-limit MAX_JOBS_NUMBER

    For example:

    # foreman-installer \
    --foreman-proxy-plugin-remote-execution-script-mqtt-rate-limit 200

5. Integrating Foreman and AWX

You can integrate Foreman and AWX to use Foreman server as a dynamic inventory source for AWX.

You can also use the provisioning callback function to run playbooks on hosts managed by Foreman, from either the host or AWX. When provisioning new hosts from Foreman server, you can use the provisioning callback function to trigger playbook runs from AWX. The playbook configures the host after the provisioning process.

5.1. Adding Foreman server to AWX as a dynamic inventory item

To add Foreman server to AWX as a dynamic inventory item, you must create a credential for a Foreman server user on AWX, add an AWX user to the credential, and then configure an inventory source.

Prerequisites
  • If your Foreman deployment is large, for example, managing tens of thousands of hosts, using a non-admin user can negatively impact performance because of time penalties that accrue during authorization checks. For large deployments, consider using an admin user.

  • For non-admin users, you must assign the Ansible Tower Inventory Reader role to your Foreman server user. For more information about managing users, roles, and permission filters, see Creating and Managing Roles in Administering Foreman.

  • You must host your Foreman server and AWX on the same network or subnet.

Procedure
  1. In the AWX web UI, create a credential for your Foreman. For more information about creating credentials, see Add a New Credential and Foreman Credentials in the Automation Controller User Guide.

    Table 2. Foreman credentials
    Credential Type: Foreman

    Foreman URL:

    https://foreman.example.com

    Username:

    The username of the Foreman user with the integration role.

    Password:

    The password of the Foreman user.

  2. Add an AWX user to the new credential. For more information about adding a user to a credential, see Getting Started with Credentials in the Automation Controller User Guide.

  3. Add a new inventory. For more information, see Add a new inventory in the Automation Controller User Guide.

  4. In the new inventory, add Foreman server as the inventory source, specifying the following inventory source options. For more information, see Add Source in the Automation Controller User Guide.

    Table 3. Inventory source options
    Source Foreman

    Credential

    The credential you create for Foreman server.

    Overwrite

    Select

    Overwrite Variables

    Select

    Update on Launch

    Select

    Cache Timeout

    90

  5. Ensure that you synchronize the source that you add.

5.2. Configuring provisioning callback for a host

When you create hosts in Foreman, you can use AWX to run playbooks to configure your newly created hosts. This is called provisioning callback in AWX.

The provisioning callback function triggers a playbook run from AWX as part of the provisioning process. The playbook configures the host after the provisioning process.

For more information about provisioning callbacks, see Provisioning Callbacks in the Automation Controller User Guide.

In Foreman server, the Kickstart Default and Kickstart Default Finish templates include three snippets:

  1. ansible_provisioning_callback

  2. ansible_tower_callback_script

  3. ansible_tower_callback_service

You can add parameters to hosts or host groups to provide the credentials that these snippets can use to run Ansible Playbooks on your newly created hosts.

Prerequisites

Before you can configure provisioning callbacks, you must add Foreman as a dynamic inventory in AWX. For more information, see Integrating Foreman and AWX.

In the AWX web UI, you must complete the following tasks:

  1. Create a machine credential for your new host. Ensure that you enter the same password in the credential that you plan to assign to the host that you create in Foreman. For more information, see Add a New Credential in the Automation Controller User Guide.

  2. Create a project. For more information, see Projects in the AWX User Guide.

  3. Add a job template to your project. For more information, see Job Templates in the Automation Controller User Guide.

  4. In your job template, you must enable provisioning callbacks, generate the host configuration key, and note the template_ID of your job template. For more information about job templates, see Job Templates in the Automation Controller User Guide.

Procedure
  1. In the Foreman web UI, navigate to Configure > Host Group.

  2. Create a host group or edit an existing host group.

  3. In the Host Group window, click the Parameters tab.

  4. Click Add Parameter.

  5. Enter the following information for each new parameter:

    Table 4. Host parameters
    Name Value Description

    ansible_tower_provisioning

    true

    Enables Provisioning Callback.

    ansible_tower_fqdn

    controller.example.com

    The fully qualified domain name (FQDN) of your AWX. Do not add https because this is appended by Foreman.

    ansible_job_template_id

    template_ID

    The ID of your provisioning template that you can find in the URL of the template: /templates/job_template/5.

    ansible_host_config_key

    config_KEY

    The host configuration key that your job template generates in AWX.

  6. Click Submit.

  7. Create a host using the host group.

  8. On the new host, enter the following command to start the ansible-callback service:

    # systemctl start ansible-callback
  9. On the new host, enter the following command to output the status of the ansible-callback service:

    # systemctl status ansible-callback

    Provisioning callback is configured correctly if the command returns the following output:

    foreman.example.com systemd[1]: Started Provisioning callback to AWX...
Manual provisioning callback
  • You can use the provisioning callback URL and the host configuration key from a host to call AWX:

    $ curl \
    --data curl \
    --data host_config_key=My_Host_Config_Key \
    --insecure \
    --show-error \
    --silent \
    https://controller.example.com/api/v2/job_templates/8/callback/

    Ensure that you use https when you enter the provisioning callback URL.

This triggers the playbook run specified in the template against the host.

6. Job template examples and extensions

Use this section as a reference to help modify, customize, and extend your job templates to suit your requirements.

6.1. Customizing job templates

When creating a job template, you can include an existing template in the template editor field. This way you can combine templates, or create more specific templates from the general ones.

The following template combines default templates to install and start the nginx service on clients:

<%= render_template 'Package Action - SSH Default', :action => 'install', :package => 'nginx' %>
<%= render_template 'Service Action - SSH Default', :action => 'start', :service_name => 'nginx' %>

The above template specifies parameter values for the rendered template directly. It is also possible to use the input() method to allow users to define input for the rendered template on job execution. For example, you can use the following syntax:

<%= render_template 'Package Action - SSH Default', :action => 'install', :package => input("package") %>

With the above template, you have to import the parameter definition from the rendered template. To do so, navigate to the Jobs tab, click Add Foreign Input Set, and select the rendered template from the Target template list. You can import all parameters or specify a comma separated list.

6.2. Default job template categories

Job template category Description

Packages

Templates for performing package related actions. Install, update, and remove actions are included by default.

Puppet

Templates for executing Puppet runs on target hosts.

Power

Templates for performing power related actions. Restart and shutdown actions are included by default.

Commands

Templates for executing custom commands on remote hosts.

Services

Templates for performing service related actions. Start, stop, restart, and status actions are included by default.

Katello

Templates for performing content related actions. These templates are used mainly from different parts of the Foreman web UI (for example bulk actions UI for content hosts), but can be used separately to perform operations such as errata installation.

6.3. Example restorecon template

This example shows how to create a template called Run Command - restorecon that restores the default SELinux context for all files in the selected directory on target hosts.

Procedure
  1. In the Foreman web UI, navigate to Hosts > Templates > Job templates.

  2. Click New Job Template.

  3. Enter Run Command - restorecon in the Name field. Select Default to make the template available to all organizations. Add the following text to the template editor:

    restorecon -RvF <%= input("directory") %>

    The <%= input("directory") %> string is replaced by a user-defined directory during job invocation.

  4. On the Job tab, set Job category to Commands.

  5. Click Add Input to allow job customization. Enter directory to the Name field. The input name must match the value specified in the template editor.

  6. Click Required so that the command cannot be executed without the user specified parameter.

  7. Select User input from the Input type list. Enter a description to be shown during job invocation, for example Target directory for restorecon.

  8. Click Submit. For more information, see Executing a restorecon Template on Multiple Hosts in Managing hosts.

6.4. Rendering a restorecon template

This example shows how to create a template derived from the Run command - restorecon template created in Example restorecon Template. This template does not require user input on job execution, it will restore the SELinux context in all files under the /home/ directory on target hosts.

Create a new template as described in Setting up Job Templates, and specify the following string in the template editor:

<%= render_template("Run Command - restorecon", :directory => "/home") %>

6.5. Executing a restorecon template on multiple hosts

This example shows how to run a job based on the template created in Example restorecon Template on multiple hosts. The job restores the SELinux context in all files under the /home/ directory.

Procedure
  1. In the Foreman web UI, navigate to Monitor > Jobs and click Run job.

  2. Select Commands as Job category and Run Command – restorecon as Job template and click Next.

  3. Select the hosts on which you want to run the job. If you do not select any hosts, the job will run on all hosts you can see in the current context.

  4. In the directory field, provide a directory, for example /home, and click Next.

  5. Optional: To configure advanced settings for the job, fill in the Advanced fields. To learn more about advanced settings, see Advanced settings in the job wizard. When you are done entering the advanced settings or if it is not required, click Next.

  6. Schedule time for the job.

    • To execute the job immediately, keep the pre-selected Immediate execution.

    • To execute the job in future time, select Future execution.

    • To execute the job on regular basis, select Recurring execution.

  7. Optional: If you selected future or recurring execution, select the Query type, otherwise click Next.

    • Static query means that the job executes on the exact list of hosts that you provided.

    • Dynamic query means that the list of hosts is evaluated just before the job is executed. If you entered the list of hosts based on some filter, the results can be different from when you first used that filter.

      Click Next after you have selected the query type.

  8. Optional: If you selected future or recurring execution, provide additional details:

    • For Future execution, enter the Starts at date and time. You also have the option to select the Starts before date and time. If the job cannot start before that time, it will be canceled.

    • For Recurring execution, select the start date and time, frequency, and condition for ending the recurring job. You can choose the recurrence to never end, end at a certain time, or end after a given number of repetitions. You can also add Purpose - a special label for tracking the job. There can only be one active job with a given purpose at a time.

      Click Next after you have entered the required information.

  9. Review job details. You have the option to return to any part of the job wizard and edit the information.

  10. Click Submit to schedule the job for execution.

6.6. Including power actions in templates

This example shows how to set up a job template for performing power actions, such as reboot. This procedure prevents Foreman from interpreting the disconnect exception upon reboot as an error, and consequently, remote execution of the job works correctly.

Create a new template as described in Setting up Job Templates, and specify the following string in the template editor:

<%= render_template("Power Action - SSH Default", :action => "restart") %>