大网数据广告活动
服务器运维问答

How do I loop over items 1 by 1 in Ansible config (YAML/Jinja2)?

· 52CE 我爱测

I am trying to loop over my hosts from my inventory in Ansible, and use the name of the host of that iteration in a command. In particular, I am trying to set the hostname of each of my hosts to whatever I have called them in my …

问题原文

原帖链接 · user3399551 · CC BY-SA 3.0

I am trying to loop over my hosts from my inventory in Ansible, and use the name of the host of that iteration in a command. In particular, I am trying to set the hostname of each of my hosts to whatever I have called them in my hosts file. So, I have web01, web02, web03 etc for my webservers -- I want to set these as hostnames on the servers in each question, i.e. I want to loop over "all" hosts and when I'm on web01 (first iteration), I want to pass that name of the host I am on to the hostname module. This is what I tried:

- hosts: all
become: true
tasks:
  - hostname:
      name: "{{ item }}"
    with_items: "{{ play_hosts }}"

However, instead of setting as hostname the name of the host I am on, this tries to set every single host from my ansible config as hostname on each single server. So it tries to do:

connect to web01; hostname -> web01; hostname -> web02; hostname -> web03
connect to web02; hostname -> web01; hostname -> web02; hostname -> web03
connect to web03; hostname -> web01; hostname -> web02; hostname -> web03

Instead I want:

connect to web01; hostname -> web01
connect to web02; hostname -> web02
connect to web03; hostname -> web03

How can I do that?

I found a similar question here: Ansible: setting hostname over inventory

but this was answered with a more complicated solution than I am hoping for. The suggestion there was to add suffixes, but surely a simple loop like I want shouldn't require that in principle.

已采纳解答

原帖链接 · techraf · CC BY-SA 3.0

You don't need to loop over hosts, as this is one of the most fundamental Ansible functions (it is disabled on a few selected modules, but hostname is not one of them).

To set the target machine's hostname to the value defined in the Ansible inventory file, all you need to do, is to reference the inventory_hostname variable (see Magic Variables):

- hosts: all
  become: true
  tasks:
    - hostname:
        name: "{{ inventory_hostname }}"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-02-22)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。