How to use a Variable in Ansible aws_ec2 plugin - variables

I want to filter ec2 instances according to the Environment tag which I define when I run the scripts, i.e ansible-playbook start.yml -e env=dev
However, it seems that the plugin is not parsing variables. Any idea on how to achieve this task?
my aws_ec2.yml:
---
plugin: aws_ec2
regions:
- eu-central-1
filters:
tag:Secure: 'yes'
tag:Environment: "{{ env }}"
hostnames:
- private-ip-address
strict: False
groups:
keyed_groups:
- key: tags.Function
separator: ''
Edit
There is no error message resulting when running the playbook. The only problem that ansible handle the variable exactly as a string tag:Environment: "{{ env }}"instead of value tag:Environment: dev

Related

dbt env macro produces wrong output

i've encountered strange problem with env var.
Here's my profiles.yml file
project:
outputs:
prod:
type: postgres
threads: 4
host: my_host
port: 5432
user: "{{ env_var('DBT_USER') }}"
pass: "{{ env_var('DBT_PASS') }}"
dbname: my_db
schema: my_schema
target: prod
Here's my env variables:
echo $DBT_USER;
my_user
echo $DBT_PASS;
my_password
dbt-debug output:
connection to server at "my_host", port 5432 failed: FATAL: password authentication failed for user "my_user"
But if I change
pass: "{{ env_var('DBT_PASS') }}"
to
my_password
in profiles.yml, dbt-debug shows no error.
dbt version is 1.0.1.
What am i doing wrong?
#dcpt The way you used the env_var function looks correct per the env_var docs but there's two things I can think of.
Are you restarting your shell after setting your env variables? Maybe there's something about the CLI session that needs to be renewed after a profiles.yml or env_var change.
I think that you need to layout your profiles.yml with target as a higher header? Looking at the example here on profiles.yml it looks like:
profiles.yml
<profile-name>:
target: <target-name>
outputs:
<target-name>:
type: <bigquery | postgres | redshift | snowflake | other>
schema: <schema_identifier>
threads: <natural_number>
But you have your target: at the bottom? Is that supposed to be an additional target definition or should it be higher above your prod: tag.

Ansible task includes undefined var, despite being defined in defaults/main.yml

I am trying to create a Galaxy role for our org's internal galaxy, which I am testing first locally. In our org we use a common list of defaults across all roles.
Ansible is throwing me a "The task includes an option with an undefined variable The error was: 'redis_download_url' is undefined" error when running my playbook, despite me having defined the variable in defaults/main.yml:
# Download
redis_version: "6.2.3"
redis_download_url: "https://download.redis.io/releases/redis-{{ redis_version }}.tar.gz"
When running my simple role/playbook.yml
---
- hosts: all
become: true
tasks:
- include: tasks/main.yml
Linked to tasks/main.yml
---
- name: Check ansible version
assert:
that: "ansible_version.full is version_compare('2.4', '>=')"
msg: "Please use Ansible 2.4 or later"
- include: download.yml
tags:
- download
- include: install.yml
tags:
- install
It should pull the tar file from tasks/download.yml as stated:
---
- name: Download Redis
get_url:
url: "{{ redis_download_url }}"
dest: /usr/local/src/redis-{{ redis_version }}.tar.gz
- name: Extract Redis tarball
unarchive:
src: /usr/local/src/redis-{{ redis_version }}.tar.gz
dest: /usr/local/src
creates: /usr/local/src/redis-{{ redis_version }}/Makefile
copy: no
The redis_download_url var is defined in defaults/main.yml which as I understand ansible should be able to locate there. I also have similar vars defined in defaults/task.yml eg.
redis_user: redis
redis_group: "{{ redis_user }}"
redis_port: "6379"
redis_root_dir: "/opt/redis"
redis_config_dir: "/etc/redis"
redis_conf_file: "{{ redis_config_dir }}/{{ redis_port }}.conf"
redis_password: "change-me"
redis_protected_mode: "yes"
and I assume they are also not able to be found/seen by ansible (but it does not get that far). I have also checked all file permissions and they seem to be fine.
Apologies in advance if the question is badly formatted.
As per documentation:
If you include a task file from a role, it will NOT trigger role behavior, this only happens when running as a role, include_role will work.
To get the role functionality of reading variables from defaults/main.yml, you'll need to use include_role or roles: [].
- hosts: all
become: true
tasks:
- include_role:
name: myrole
OR
- hosts: all
become: true
roles:
- myrole

Ansible: Can't set variable for sequential execution

I'm trying to build a playbook with rolling update use case (Sequential Execution) with the serial element. Since I have to use the serial value in multiple places in the playbook, I wanted to use it as a variable which can be used to define somewhere as a group variable.
Inventory file
[all]
webserver1 ansible_host=10.1.1.1 ansible_user=root
webserver2 ansible_host=10.1.1.2 ansible_user=root
webserver3 ansible_host=10.1.1.3 ansible_user=root
dbserver1 ansible_host=10.1.2.1 ansible_user=root
[webserver]
webserver1
webserver2
webserver3
[dbserver]
dbserver1
[app-stack:children]
webservers
dbservers
[app-stack:vars]
app_stack_serial_value=1
Playbook
- hosts: app-stack
serial: "{{ app_stack_serial_value }}"
tasks:
- name: debug
debug:
msg: "Ansible Host - {{ ansible_host }}"
Error
ERROR! The field 'serial' has an invalid value, which includes an undefined variable. The error was: 'app_stack_serial_value' is undefined
This will work if I specify the value in the serial field like serial: 1. But I wanted to use this value as a variable. Any Idea ??
Ansible Version: ansible 2.7.10
python version = 3.7.2 (default, Jan 13 2019, 12:50:01) [Clang 10.0.0 (clang-1000.11.45.5)]
As far as I know, you cannot set it in the group variables. But you can try set ENV SERIAL_NUMBER=1 before run this playbook and set the serial parameter like:
serial: "{{lookup('env','SERIAL_NUMBER')|default(3, true)}}"

Ansible - when conditional not working for vars_prompt at playbook level

ansible 2.1.2.0
I have a situation here for which I'm trying to check with you all to see if the solution is even possible with Ansible vars_prompt feature and when conditional.
Ansible has this feature called: vars_prompt and I want to club this with the when conditional (when: ... which we generally use in tasks at task or playbook level actions)
PS: My question is different than this post: Ansible to Conditionally Prompt for a Variable? i.e. my vars: variables are not dependent upon any machine's OS ENV variables, in my case, I just have a simple hardcoded value for vars: variables. I'm also running the when condition at the main playbook level (and not at the task's level).
What I'm trying to do is to prompt a user for entering a variable value, only if at command line, the user has called the ansible-playbook install_tool.yml ... ... with --extra-vars "install_tool=true"
In workspace/ansible/install_tool.yml I have:
- hosts: all
become: true
gather_facts: false
vars:
instance: test
#install_tool: false
company_api_url: DUMMY_INVALID_URL
vars_prompt:
- name: "company_api_url"
prompt: "Enter Company API URL: "
default: "https://{{ instance }}.company.com"
private: no
when: install_tool == "true" and company_api_url == "DUMMY_INVALID_URL"
# or
#when: ( "{{ install_tool }}" == "true" and "{{ company_api_url }}" == "DUMMY_INVALID_URL" )
pre_tasks:
- debug: msg="install_tool = {{ install_tool }} and instance = {{ instance }}"
when: install_tool == "true"
My question:
How can I get the above conditional prompt working (with a valid substituted default value for a prompt variable) and also SKIP to prompt a user altogether depending upon the value of install_tool variable?
My understanding:
In top level playbook file (install_tool.yml), I'm defining a variable instance with value as test. Why the default value for the vars_prompt section did NOT pick test and substituted its value when it's defined at the playbook level (--OR what if a user is passing instance variable at command line for ex: --extra-vars "instance=qa"? In that case, I would want the default value as [https://qa.company.com], how can I do that)? I don't see any errors while running it for any syntax.
I'm getting the following output (but I was expecting a substituted URL value like: [https://test.company.com]) and it's still prompting even when install_tool was set or passed at command line as false:
Running:
$ ansible-playbook -i "localhost," --connection=local install_tool.yml --extra-vars "install_tool=false instance=qa"
or
$ ansible-playbook -i inventory -l localhost install_tool.yml --extra-vars "install_tool=false"
...
.....some lines here
...
PLAYBOOK: install_tool.yml *******************************************
1 plays in install_tool.yml
Enter Company API URL: [https://{{ instance }}.company.com]:
As using when: ( "{{ install_tool }}" == "true" and ...) condition within vars_prompt section, under/for - name: company_api_url variable, it didn't error out for any syntax issues or etc (that means, Ansible doesn't think it's wrong), then WHY, Ansible is still prompting me to enter the above vars_prompts variable, even when I'm passing --extra-vars "install_tool=false" --OR-- if I uncomment the line: install_tool: false under vars: section?
PS: when: ... condition is successfully working for the pre_tasks section i.e. when install_tool is true, it shows the value of those 2 variables and when install_tool is set to false, then it does NOT run the - debug step and skips it (which is expected).
Thanks.
You can check all supported attributes for prompted vars here.
when statement is not supported for prompted vars. And never was.
Templated default values for prompted vars is not supported also.
The only way to prevent vars prompt is to pass the variable in question via extra_vars. In your example, if you pass -e company_api_url=my_custom_url, Ansible will skip prompting for it.

How can I pass variable to ansible playbook in the command line?

How can one pass variable to ansible playbook in the command line?
The following command didn't work:
$ ansible-playbook -i '10.0.0.1,' yada-yada.yml --tags 'loaddata' django_fixtures="tile_colors"
Where django_fixtures is my variable.
Reading the docs I find the section Passing Variables On The Command Line, that gives this example:
ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"
Others examples demonstrate how to load from JSON string (≥1.2) or file (≥1.3)
Other answers state how to pass in the command line variables but not how to access them, so if you do:
--extra-vars "version=1.23.45 other_variable=foo"
In your yml file you assign these to scoped ansible variables by doing something like:
vars:
my_version: "{{ version }}"
my_other_variable: {{ other_variable }}
An alternative to using command line args is to utilise environmental variables that are already defined within your session, you can reference these within your ansible yml files like this:
vars:
my_version: "{{ lookup('env', 'version') }}"
my_other_variable: {{ lookup('env', 'other_variable') }}
ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
For some reason none of the above Answers worked for me. As I need to pass several extra vars to my playbook in Ansbile 2.2.0, this is how I got it working (note the -e option before each var):
ansible-playbook site.yaml -i hostinv -e firstvar=false -e second_var=value2
You can use the --extra-vars option. See the docs
ansible-playbook test.yml --extra-vars "arg1=${var1} arg2=${var2}"
In the yml file you can use them like this
---
arg1: "{{ var1 }}"
arg2: "{{ var2 }}"
Also, --extra-vars and -e are the same, you can use one of them.
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
This also worked for me if you want to use shell environment variables:
ansible-playbook -i "localhost," ldap.yaml --extra-vars="LDAP_HOST={{ lookup('env', 'LDAP_HOST') }} clustername=mycluster env=dev LDAP_USERNAME={{ lookup('env', 'LDAP_USERNAME') }} LDAP_PASSWORD={{ lookup('env', 'LDAP_PASSWORD') }}"
In Ansible, we can define variables when running our playbook by passing variables at the command line using the --extra-vars (or -e) argument.
Bellow are some ways to pass variables to an Ansible playbook in the command line:
Method 1: key=value format
ansible-playbook site.yml --extra-vars "arg1=demo1 arg2=demo2"
Method 2: JSON string format
ansible-playbook site.yml --extra-vars '{"arg1":"demo1","arg2":"demo2"}'
The site.yml playbook will be:
---
- name: ansible playbook to print external variables
hosts: localhost
connection: local
tasks:
- name: print values
ansible.builtin.debug:
msg: "variable1 = {{ arg1 }}, variable2 = {{ arg2 }}"
when: arg1 is defined and arg2 is defined
Method 3: Read from an external JSON file
If you have a lot of special characters, use a JSON or YAML file containing the variable definitions.
ansible-playbook site.yml --extra-vars "#vars.json"
The vars.json file:
{
arg1: "demo1",
arg2: "demo2"
}
ansible-playbook release.yml --extra-vars "username=hello password=bye"
#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"
ansible-playbok -i <inventory> <playbook-name> -e "proc_name=sshd"
You can use the above command in below playbooks.
---
- name: Service Status
gather_facts: False
tasks:
- name: Check Service Status (Linux)
shell: pgrep "{{ proc_name }}"
register: service_status
ignore_errors: yes
debug: var=service_status.rc`