Page Menu
Home
Software Heritage
Search
Configure Global Search
Log In
Paste
P383
ansible_terraform.py
Active
Public
Actions
Authored by
vlorentz
on Apr 17 2019, 2:33 PM.
Edit Paste
Archive Paste
View Raw File
Subscribe
Mute Notifications
Award Token
Flag For Later
Tags
None
Subscribers
None
azure
@desktop5
~/
ansible
master
✚
cat
plugins
/
inventory
/
terraform
.
py
import
json
import
os
from
subprocess
import
check_output
from
ansible.plugins.inventory
import
BaseInventoryPlugin
,
Constructable
,
Cacheable
def
get_state
(
terraform_dir
):
terraform_bin
=
os
.
environ
.
get
(
'ANSIBLE_TF_BIN'
,
'terraform'
)
output
=
check_output
([
terraform_bin
,
'state'
,
'pull'
,
'-input=false'
],
cwd
=
terraform_dir
)
return
json
.
loads
(
output
)
class
InventoryModule
(
BaseInventoryPlugin
,
Constructable
,
Cacheable
):
NAME
=
'terraform'
def
verify_file
(
self
,
path
):
"""Checks the path is a directory containing a .tf file."""
return
path
.
endswith
(
'.tf'
)
def
parse
(
self
,
inventory
,
loader
,
path
,
cache
=
True
):
super
(
InventoryModule
,
self
)
.
parse
(
inventory
,
loader
,
path
,
cache
)
state
=
get_state
(
os
.
path
.
dirname
(
path
))
for
module
in
state
[
'modules'
]:
self
.
_parse_azurerm_resources
(
module
[
'resources'
])
def
_parse_azurerm_resources
(
self
,
resources
):
"""Populate the ansible inventory from azure resources."""
interfaces
=
self
.
_get_azurerm_interfaces
(
resources
)
self
.
_parse_azurerm_vms
(
interfaces
,
resources
)
def
_get_azurerm_interfaces
(
self
,
resources
):
"""Returns a dict associating the interface's attributes to
each interface ID."""
interfaces
=
{}
for
(
name
,
resource
)
in
resources
.
items
():
if
resource
[
'type'
]
==
'azurerm_network_interface'
:
id_
=
resource
[
'primary'
][
'id'
]
interfaces
[
id_
]
=
resource
[
'primary'
][
'attributes'
]
return
interfaces
def
_parse_azurerm_vms
(
self
,
interfaces
,
resources
):
"""Populates the ansible inventory with the VMs in the `resources`
dict."""
for
(
name
,
resource
)
in
resources
.
items
():
if
resource
[
'type'
]
==
'azurerm_virtual_machine'
:
attributes
=
resource
[
'primary'
][
'attributes'
]
host
=
attributes
[
'name'
]
self
.
inventory
.
add_host
(
host
)
interface
=
interfaces
[
attributes
[
'network_interface_ids.0'
]]
ip_address
=
interface
[
'private_ip_address'
]
self
.
inventory
.
set_variable
(
host
,
'ansible_host'
,
ip_address
)
azure
@desktop5
~/
ansible
master
✚
cat
ansible
.
cfg
|
sed
"s/#.*//"
|
grep
inventory
inventory
=
/
home
/
azure
/
ansible
/
hosts
,
/
home
/
azure
/
ansible
/
terraform
/
test
.
tf
inventory_plugins
=
/
home
/
azure
/
ansible
/
plugins
/
inventory
[
inventory
]
Event Timeline
vlorentz
created this paste.
Apr 17 2019, 2:33 PM
2019-04-17 14:33:57 (UTC+2)
Log In to Comment