在Ansible中作为extra-vars传递时如何获取主机的IP地址?

时间:2017-01-10 22:45:53

标签: ansible

假设我将主机名传递给Ansible剧本,如下所示:

//First the includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>

int main(void) {
        string str = GetString(); //Here you should enter your string
        str[0] = toupper(str[0]); //Capitalize the first letter so you don't have to do extra checking in the for loop
        for (int i = 1; i < strlen(str); i++){ //Start from the second letter(or space) since index 0 is already capitalized
                if(str[i-1] == ' ') //Check if the previous character was a space
                        str[i] = toupper(str[i]); //Convert to uppercase
        }
        puts(str); //Print out the string, same thing as printf(str);
}

在剧本中,我想访问ansible-playbook ansible/db-playbook.yml --extra-vars "master=mydb-master, slave=mydb-slave" 主机的实际IP地址:

mydb-slave

在这种情况下,输出是字符串文字- name: Copy ssh key to Slave command: ... "{{ mydb-slave }}" ,但我需要完整的mydb-slave地址。

1 个答案:

答案 0 :(得分:0)

确保在运行ansible的主机上安装了python模块dnspython,然后以下内容应该有效(如果给出的主机是DNS名称):

- name: Lookup slave IP
  set_fact: slave_ip="{{ lookup('dig', '{{ slave }}')}}"

- name: Copy ssh key to Slave
  command: ... "{{ slave_ip }}"

如果主机位于您的安全库存中,则以下内容应该有效:

- name: Copy ssh key to Slave
  command: ... "{{ hostvars[slave]['ansible_eth0']['ipv4']['address'] }}"