gpt4 book ai didi

linux - 用于将连续整数分配为主机名的 Ansible 循环

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:53 26 4
gpt4 key购买 nike

我是 Ansible 新手。我有以下更改远程服务器主机名的剧本:

---
- hosts: dbservers
remote_user: testuser1
become: yes
become_method: sudo

vars:
LOCAL_HOSTNAME: 'db01'
LOCAL_DOMAIN_NAME: 'ansibletest.com'

tasks:
# Checks and removed the existing occurences of <IP hostname FQDN> from /etc/hosts
- name: Remove occurences of the existing IP
lineinfile: dest=/etc/hosts
regexp='{{ hostvars[item].ansible_default_ipv4.address }}'
state=absent
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['dbservers'] }}"

# Adds the IP in the format <IP hostname FQDN> to /etc/hosts
- name: Add the IP and hostname to the hosts file
lineinfile: dest=/etc/hosts
regexp='.*{{ item }}$'
line="{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
state=present
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['dbservers'] }}"

- name: Remove HOSTNAME occurences from /etc/sysconfig/network
lineinfile: dest=/etc/sysconfig/network
regexp='^HOSTNAME'
state=absent
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['dbservers'] }}"

- name: Add new HOSTNAME to /etc/sysconfig/network
lineinfile: dest=/etc/sysconfig/network
regexp='^HOSTNAME='
line="HOSTNAME={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
state=present
when: hostvars[item].ansible_default_ipv4.address is defined
with_items: "{{ groups['dbservers'] }}"

- name: Set up the hostname
hostname: name={{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}

在此示例中,LOCAL_HOSTNAME 已被分配了值 db01。在这种情况下,dbservers 组只有一台服务器:

[dbservers]
192.168.1.93

但是,我还有另外 2 台指定为网络服务器的服务器:

[webservers]
192.168.1.95
192.168.1.96

[dbservers]
192.168.1.93

目的是将它们命名为web01.domainweb02.domain等。

根据 docs这似乎可以通过使用with_sequence来实现。

我的问题是,是否可以(在 Ansible 中)在循环中使用 2 个变量?类似于下面的伪代码:

i=1
for host in webservers:
open host(/etc/hosts):
add "IP<space>HOSTNAME{i}<space>"<space>"HOSTNAME{i}.FQDN"
i++

这是否可以使用剧本来实现,还是我以错误的方式处理了这个问题?

最佳答案

首先生成索引主机名,将其定义为 hostfact,稍后使用它来填充其他服务器的主机文件。

- hosts: webservers
gather_facts: no
tasks:
- set_fact:
indexed_hostname: "{{ 'web{0:02d}'.format(play_hosts.index(inventory_hostname)+1) }}"

- hosts: dbservers
gather_facts: no
tasks:
- debug:
msg: "{{ hostvars[item].indexed_hostname }}"
with_items: "{{ groups['webservers'] }}"

还有with_indexed_items这样的东西.

关于linux - 用于将连续整数分配为主机名的 Ansible 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41628806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com