📅  最后修改于: 2023-12-03 14:59:19.459000             🧑  作者: Mango
Ansible is an open-source automation tool that helps to manage IT infrastructure, applications, and network services. With Ansible, you can automate complex IT tasks such as configuration management, application deployment, and cloud provisioning.
One of the powerful features of Ansible is its ability to gather facts about the target hosts. These facts can be used in creating dynamic inventories or for debugging purposes.
In this article, we will explore how to use Ansible to set the hostname of a target host based on a fact.
Before we proceed, make sure that you have the following:
The first step is to gather facts about the target host. You can use the setup
module to gather all the facts or you can specify only the facts that you need. Here's an example:
- name: Gather facts
hosts: target_host
tasks:
- name: Gather all facts
setup:
- name: Get hostname fact
debug:
var: ansible_hostname
The above playbook will gather all the facts about target_host
and print the ansible_hostname
variable.
Once you have the hostname fact, you can use the hostname
module to set the hostname of the target host.
- name: Set hostname using facts
hosts: target_host
tasks:
- name: Gather all facts
setup:
- name: Set hostname
hostname:
name: "{{ ansible_hostname }}"
The above playbook will set the hostname of target_host
to ansible_hostname
fact.
To verify that the hostname has been set correctly, you can use the assert
module to compare the expected hostname with the actual hostname.
- name: Verify hostname
hosts: target_host
tasks:
- name: Gather all facts
setup:
- name: Set hostname
hostname:
name: "{{ ansible_hostname }}"
- name: Verify hostname
assert:
that:
- ansible_hostname == ansible_fqdn
The above playbook will set the hostname of target_host
to ansible_hostname
fact and then verify that the hostname has been set correctly.
In this article, we learned how to use Ansible to set the hostname of a target host based on a fact. Gathering facts and using them in automation can greatly increase the efficiency and accuracy of your IT workflows.