I am provisioning AWS infrastructure using terraform and want to pass variables such as aws_subnet_id and aws_security_id into ansible playbook using vars_file (don't know if there is any other way though). How can I do that?
I use Terraform local_file to create an Ansible vars_file. I add a tf_ prefix to the variable names to make it clear that they originate in Terraform:
# Export Terraform variable values to an Ansible var_file
resource "local_file" "tf_ansible_vars_file_new" {
content = <<-DOC
# Ansible vars_file containing variable values from Terraform.
# Generated by Terraform mgmt configuration.
tf_environment: ${var.environment}
tf_gitlab_backup_bucket_name: ${aws_s3_bucket.gitlab_backup.bucket}
DOC
filename = "./tf_ansible_vars_file.yml"
}
Run terraform apply to create Ansible var_file tf_ansible_vars_file.yml containing Terraform variable values:
# Ansible vars_file containing variable values from Terraform.
# Generated by Terraform mgmt configuration.
tf_environment: "mgmt"
tf_gitlab_backup_bucket_name: "project-mgmt-gitlab-backup"
Add tf_ansible_vars_file.yml to your Ansible playbook:
vars_files:
- ../terraform/mgmt/tf_ansible_vars_file.yml
Now, in Ansible the variables defined in this file will contain values from Terraform.
Obviously, this means that you must run Terraform before Ansible. But it won't be so obvious to all your Ansible users. Add assertions to your Ansible playbook to help the user figure out what to do if a tf_ variable is missing:
- name: Check mandatory variables imported from Terraform
assert:
that:
- tf_environment is defined
- tf_gitlab_backup_bucket_name is defined
fail_msg: "tf_* variable usually defined in '../terraform/mgmt/tf_ansible_vars_file.yml' is missing"
UPDATE: An earlier version of this answer used a Terraform template. Experience shows that the template file is error prone and adds unnecessarily complexity. So I moved the template file to the content of the local_file.
terraform outputs are an option, or you can just use something like:
provisioner "local-exec" {
command = "ANSIBLE_HOST_KEY_CHECKING=\"False\" ansible-playbook -u ${var.ssh_user} --private-key=\"~/.ssh/id_rsa\" --extra-vars='{"aws_subnet_id": ${aws_terraform_variable_here}, "aws_security_id": ${aws_terraform_variable_here} }' -i '${azurerm_public_ip.pnic.ip_address},' ansible/deploy-with-ansible.yml"
}
or you can do a sed thing ... as a local provisioner to update the var file..
or you can use terraform outputs.... your preference....
I highly recommend this script. It works well and is maintained by Cisco and will give you more flexibility.
https://github.com/CiscoCloud/terraform.py
Since I want to run both terraform plan and ansible --check in a pull request with a CI, I've decided to go with terraform output.
Basically this is how I run my Ansible now and it gets all outputs from terraform :
With the following output
// output.tf
output "tf_gh_deployment_status_token" {
value = var.GH_DEPLOYMENT_STATUS_TOKEN
sensitive = true
}
Running a bit modified terraform output parsed with jq :
$ terraform output --json | jq 'with_entries(.value |= .value)'
{
"tf_gh_deployment_status_token": "<some token>"
}
This makes it great to run with --extra-args with Ansible :
$ ansible-playbook \
-i ./inventory/production.yaml \
./playbook.yaml \
--extra-vars "$(terraform output --json | jq 'with_entries(.value |= .value)')"
Now I can use {{ tf_gh_deployment_status_token }} anywhere in my playbook.
Use terraform outputs - https://www.terraform.io/intro/getting-started/outputs.html (it is not clear if you are using it already)
Then using command like terraform output ip, you can then use those values in your scripts to generate or populate other files like inventory files or vars_file.
Another option is to use terraform templates and render your files like inventory files from terraform itself and then use it from Ansible.
Related
I'm setting up a project using terraform and Ansible. After Terraform creates all the needed resources, I need to provision the servers using Ansible, where I am using the following:
# provisioner "local-exec" {
# environment = {
# ANSIBLE_SSH_RETRIES = "30"
# ANSIBLE_HOST_KEY_CHECKING = "False"
# }
# command = "ansible-playbook ${var.ec2_ansible_playbook} --extra-vars env_name=${var.env} -u ubuntu -i ${aws_eip.main.0.public_ip},"
# }
Ansible fails to find my group_vars, How do I point Ansible to the correct path where group_vars are located? Previously, I was only using Ansible and I would run something like
ansible-playbook provision.yml -i inventory/prod/hosts
Ansible wouldn't have any problems finding group_vars since they were sitting at the same location as the hosts. Any help is appreciated.
You can specify the working-dir like mentioned in the documentation
I think per default it uses the module directory as working directory.
Curious as to how I can pass a number to a jinja2 template file in a Terraform -> Ansible flow?
In my tfvars json, I have:
{
"Users": 100
}
And in my main.tf, I am calling an ansible playbook upon starting my ec2 instance and running:
- sudo ansible-playbook /PostServerConfiguration.yml --extra-vars '${jsonencode({"lic_users"=var.Users})}'
That variable in ansible should go to a jinja2 template file, but I need it as an int and not a string. Would anyone happen to know the solution to pass an int through? In my variables.tf I have also put the type for Users to be a number
I found the answer :)
First I tested by running the debug task in the ansible-playbook to output lic_users during runtime. It was 100 as an int, so that crosses off Terraform as the culprit.
I ended up using "{{ lic_users | int }}" in my j2 template and it worked. Thanks all!
How do I get the value of a variable from the inventory if the variable could be either in the inventory file or group_vars directory?
For example, region=place-a could be in the inventory file or in a file in the group_vars somewhere. I would like a command to be able to retrieve that value using ansible or something retrieve that value. like:
$ ansible -i /somewhere/production/web --get-value region
place-a
That would help me with deployments and knowing which region is being deployed to.
.
A longer explanation to clarify, my inventory structure looks like this:
/somewhere/production/web
/somewhere/production/group_vars/web
The contents with the variables of the inventory file, /somewhere/production/web looks like this:
[web:children]
web1 ansible_ssh_host=10.0.0.1
web2 ansible_ssh_host=10.0.0.2
[web:vars]
region=place-a
I could get the value from the inventory file by simply parsing the file. like so:
$ awk -F "=" '/^region/ {print $2}' /somewhere/production/web
place-a
But that variable could be in the group_vars file, too. For example:
$ cat /somewhere/production/group_vars/web
region: place-a
Or it could look like an array:
$ cat /somewhere/production/group_vars/web
region:
- place-a
I don't want to look for and parse all the possible files.
Does Ansible have a way to get the values? Kind of like how it does with --list-hosts?
$ ansible web -i /somewhere/production/web --list-hosts
web1
web2
Short Answer
NO there is no CLI option to get value of variables.
Long Answer
First of all, you must look into how variable precedence works in Ansible.
The exact order is defined in the documentation. Here is an summary excerpt:
Basically, anything that goes into “role defaults” (the defaults
folder inside the role) is the most malleable and easily overridden.
Anything in the vars directory of the role overrides previous versions
of that variable in namespace. The idea here to follow is that the
more explicit you get in scope, the more precedence it takes with
command line -e extra vars always winning. Host and/or inventory
variables can win over role defaults, but not explicit includes like
the vars directory or an include_vars task.
With that cleared out, the only way to see what value is a variable taking is to use the debug task as follows:
- name: debug a variable
debug:
var: region
This will print out the value of the variable region.
My suggestion would be to maintain a single value type, either a string or a list to prevent confusion across tasks in different playbooks.
You could use something like this:
- name: deploy to regions
<task_type>:
<task_options>: <task_option_value>
// use the region variable as you wish
region: {{ item }}
...
with_items: "{{ regions.split(',') }}"
In this case you could have a variable regions=us-west,us-east comma-separated. The with_items statement would split it over the , and repeat the task for all the regions.
The CLI version of this is important for people who are trying to connect ansible to other systems. Building on the usage of the copy module elsewhere, if you have a POSIX mktemp and a copy of jq locally, then here's a bash one-liner that does the trick from the CLI:
export TMP=`mktemp` && ansible localhost -c local -i inventory.yml -m copy -a "content={{hostvars['SOME_HOSTNAME']}} dest=${TMP}" >/dev/null && cat ${TMP}|jq -r .SOME_VAR_NAME && rm ${TMP}
Breaking it down
# create a tempfile
export TMP=`mktemp`
# quietly use Ansible in local only mode, loading inventory.yml
# digging up the already-merged global/host/group vars
# for SOME_HOSTNAME, copying them to our tempfile from before
ansible localhost --connection local \
--inventory inventory.yml --module-name copy \
--args "content={{hostvars['SOME_HOSTNAME']}} dest=${TMP}" \
> /dev/null
# CLI-embedded ansible is a bit cumbersome. After all the data
# is exported to JSON, we can use `jq` to get a lot more flexibility
# out of queries/filters on this data. Here we just want a single
# value though, so we parse out SOME_VAR_NAME from all the host variables
# we saved before
cat ${TMP}|jq -r .SOME_VAR_NAME
rm ${TMP}
Another more easy solution get a variable through cli from ansible could be this:
export tmp_file=/tmp/ansible.$RANDOM
ansible -i <inventory> localhost -m copy -a "content={{ $VARIABLE_NAME }} dest=$tmp_file"
export VARIBALE_VALUE=$(cat $tmp_file)
rm -f $tmp_file
Looks quite ugly but is really helpful.
I ran into a configuration problem when coding an Ansible playbook for SSH private key files. In static Ansible inventories, I can define combinations of host servers, IP addresses, and related SSH private keys - but I have no idea how to define those with dynamic inventories.
For example:
---
- hosts: tag_Name_server1
gather_facts: no
roles:
- role1
- hosts: tag_Name_server2
gather_facts: no
roles:
- roles2
I use the below command to call that playbook:
ansible-playbook test.yml -i ec2.py --private-key ~/.ssh/SSHKEY.pem
My questions are:
How can I define ~/.ssh/SSHKEY.pem in Ansible files rather than on the command line?
Is there a parameter in playbooks (like gather_facts) to define which private keys should be used which hosts?
If there is no way to define private keys in files, what should be called on the command line when different keys are used for different hosts in the same inventory?
TL;DR: Specify key file in group variable file, since 'tag_Name_server1' is a group.
Note: I'm assuming you're using the EC2 external inventory script. If you're using some other dynamic inventory approach, you might need to tweak this solution.
This is an issue I've been struggling with, on and off, for months, and I've finally found a solution, thanks to Brian Coca's suggestion here. The trick is to use Ansible's group variable mechanisms to automatically pass along the correct SSH key file for the machine you're working with.
The EC2 inventory script automatically sets up various groups that you can use to refer to hosts. You're using this in your playbook: in the first play, you're telling Ansible to apply 'role1' to the entire 'tag_Name_server1' group. We want to direct Ansible to use a specific SSH key for any host in the 'tag_Name_server1' group, which is where group variable files come in.
Assuming that your playbook is located in the 'my-playbooks' directory, create files for each group under the 'group_vars' directory:
my-playbooks
|-- test.yml
+-- group_vars
|-- tag_Name_server1.yml
+-- tag_Name_server2.yml
Now, any time you refer to these groups in a playbook, Ansible will check the appropriate files, and load any variables you've defined there.
Within each group var file, we can specify the key file to use for connecting to hosts in the group:
# tag_Name_server1.yml
# --------------------
#
# Variables for EC2 instances named "server1"
---
ansible_ssh_private_key_file: /path/to/ssh/key/server1.pem
Now, when you run your playbook, it should automatically pick up the right keys!
Using environment vars for portability
I often run playbooks on many different servers (local, remote build server, etc.), so I like to parameterize things. Rather than using a fixed path, I have an environment variable called SSH_KEYDIR that points to the directory where the SSH keys are stored.
In this case, my group vars files look like this, instead:
# tag_Name_server1.yml
# --------------------
#
# Variables for EC2 instances named "server1"
---
ansible_ssh_private_key_file: "{{ lookup('env','SSH_KEYDIR') }}/server1.pem"
Further Improvements
There's probably a bunch of neat ways this could be improved. For one thing, you still need to manually specify which key to use for each group. Since the EC2 inventory script includes details about the keypair used for each server, there's probably a way to get the key name directly from the script itself. In that case, you could supply the directory the keys are located in (as above), and have it choose the correct keys based on the inventory data.
The best solution I could find for this problem is to specify private key file in ansible.cfg (I usually keep it in the same folder as a playbook):
[defaults]
inventory=ec2.py
vault_password_file = ~/.vault_pass.txt
host_key_checking = False
private_key_file = /Users/eric/.ssh/secret_key_rsa
Though, it still sets private key globally for all hosts in playbook.
Note: You have to specify full path to the key file - ~user/.ssh/some_key_rsa silently ignored.
You can simply define the key to use directly when running the command:
ansible-playbook \
\ # Super verbose output incl. SSH-Details:
-vvvv \
\ # The Server to target: (Keep the trailing comma!)
-i "000.000.0.000," \
\ # Define the key to use:
--private-key=~/.ssh/id_rsa_ansible \
\ # The `env` var is needed if `python` is not available:
-e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
\ # Dry–Run:
--check \
deploy.yml
Copy/ Paste:
ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml
I'm using the following configuration:
#site.yml:
- name: Example play
hosts: all
remote_user: ansible
become: yes
become_method: sudo
vars:
ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"
I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.
The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):
[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem
Here is the patch for ec2.py:
204a205,206
> 'ssh_key_path': '~/.ssh',
> 'ssh_key_suffix': '.pem',
422a425,428
> # SSH key setup
> self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
> self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
>
1490a1497
> instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)
I have a harness to build VMs using Packer that in turn calls Ansible (in local mode) to do the heavy lifting.
I'd like to be able to parameters to Packer (got that), which is passes to Ansible as extra vars.
I can pass an external variables files and also a simple variable such as the example below.
ansible-playbook -v -c local something.yml --extra-vars "deploy_loc=custom"
Thats okay, but I really need to pass more complex array of variables, such as the examples below.
I've tried a number of formatting such as the one below and usually get some kind of delimiter error.
ansible-playbook -v -c local something.yml --extra-vars 'deploy_loc=custom deploy_scen: [custom][ip=1.2.34]}'
Role variable file
# Which location
deploy_loc: 'external-dhcp'
# location defaults
deploy_scen:
custom:
ipv4: yes
net_type: dhcp
ip: '1.1.1.1'
prefix: '24'
gw: '1.1.1.1.254'
host: 'custom'
domain: 'domain.com'
dns1: '1.1.1.2'
standard-eng:
ipv4: yes
net_type: none
ip: '12.12.12.5'
prefix: '24'
external-dhcp:
ipv4: yes
net_type: dhcp
I think it's more robust and readable to generate a yaml file and use that with vars_files.
Alternatively you can generate a json file and read and parse it using a file lookup and the from_json filter. Something like this:
- name: Read objects
set_fact: deploy_scen={{lookup('file', 'deploy_scen.json') | from_json}}
However, if you really want --extra-var you can use the dict() function:
-e 'var={{dict(key1=dict(subkey1="value"),key2=dict(subkey1="value2"))}}'
You can pass a json structure in to ansible via the extra-vars parameter. You have to be a little careful to make sure it's set up properly though. You want to have the parameter look something like this:
--extra-vars {"param1":"foo","param2":"bar","file_list":[ "file1", "file2", "file3" ]}
When I do things like this I typically write a small bash wrapper script that will ensure extra-vars is set up properly and then invokes ansible.