NIGHTSCROLLER
NIGHTSCROLLER

Reputation: 127

store hosts IP addresses in variable file instead of inventory

I tried to look this up online but can't find a clear answer. Is it possible to store inventory hosts' IP addresses in the playbook or in var files like group_vars or host_vars or even myvault.yml? something like:

[webserver]    
webserver_ip_variable

then that variable would be defined in some var files like group_vars/all/myvars.yml as:

webserver_ip_variable: 8.8.8.8

is that any possible? The goal is to store the IP addresses in a vault.yml file, what would be the best way to accomplish this?

Upvotes: 0

Views: 1238

Answers (2)

Jack
Jack

Reputation: 6158

As you say, you can vault a file with the IP addresses. So your inventory can have two files, one with the hosts, and one with the IPs:

inventory/hosts:

srv1
srv2
srv3

inventory/ips (vault this file):

srv1 ansible_host=192.168.1.11
srv2 ansible_host=192.168.1.12
srv3 ansible_host=192.168.1.13

Of course, you don't really need that hosts file, but you can use that to group hosts, too.

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 68034

Q: "The goal is to store the IP addresses in a vault.yml file, what would be the best way to accomplish this?"

A: Ansible doesn't have to know the IP address of the remote host as long as either the alias or ansible_host is resolvable. See Connecting to hosts: behavioral inventory parameters. For example, let's create an inventory file

shell> cat hosts
[srv]
srv1 ansible_host=srv1.example.com
srv2 ansible_host=srv2.example.com
srv3 ansible_host=srv3.example.com

Then create the vault file with the IP addresses. For example

shell> cat group_vars/srv/ip.yml
srv_ip:
  srv1: 192.168.1.11
  srv2: 192.168.1.12
  srv3: 192.168.1.13

Encrypt the file

shell> ansible-vault encrypt group_vars/srv/ip.yml
Encryption successful

Now it's possible to use the encrypted file in the playbook. For example

shell> cat pb.yml 
- hosts: srv
  tasks:
    - debug:
        var: srv_ip[inventory_hostname]

gives

shell> ansible-playbook -i hosts pb.yml 

ok: [srv2] => {
    "srv_ip[inventory_hostname]": "192.168.1.12"
}
ok: [srv1] => {
    "srv_ip[inventory_hostname]": "192.168.1.11"
}
ok: [srv3] => {
    "srv_ip[inventory_hostname]": "192.168.1.13"
}

Upvotes: 1

Related Questions