refactor: update 1Password lookup syntax for consistency and clarity
Some checks failed
Nix Format Check / check-format (push) Failing after 38s

This commit is contained in:
2025-03-11 21:09:47 +01:00
parent 8eded69aee
commit f7c25a0ed2
5 changed files with 34 additions and 84 deletions

View File

@@ -7,39 +7,25 @@ DOCUMENTATION = """
version_added: "1.0" version_added: "1.0"
short_description: fetch secrets from 1Password short_description: fetch secrets from 1Password
description: description:
- Uses the 1Password CLI to fetch secrets from 1Password - Uses the 1Password CLI to fetch secrets from 1Password using the op read command
options: options:
item: _terms:
description: the item to fetch description: 1Password reference string (op://vault/item/field)
required: false required: true
field:
description: the field to fetch from the item
required: false
default: password
vault:
description: the vault to fetch from (name or ID)
required: false
reveal:
description: whether to reveal concealed fields
required: false
default: true
ref:
description: full 1Password reference (op://vault/item/field)
required: false
""" """
EXAMPLES = """ EXAMPLES = """
- name: fetch password for an item - name: fetch password using 1Password reference
debug: debug:
msg: "{{ lookup('onepassword', 'xxxx', field='password') }}" msg: "{{ lookup('onepassword', 'op://vault/item/password') }}"
- name: fetch password from specific vault - name: fetch username from item
debug: debug:
msg: "{{ lookup('onepassword', 'xxxx', field='password', vault='xxxx') }}" msg: "{{ lookup('onepassword', 'op://vault/item/username') }}"
- name: fetch using full reference - name: fetch custom field
debug: debug:
msg: "{{ lookup('onepassword', ref='op://vault/item/field') }}" msg: "{{ lookup('onepassword', 'op://vault/item/custom_field') }}"
""" """
RETURN = """ RETURN = """
@@ -56,72 +42,37 @@ display = Display()
class LookupModule(LookupBase): class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs): def run(self, terms, variables=None, **kwargs):
ref = kwargs.get('ref') result = []
if ref: for term in terms:
# If ref is provided, use op read command if not term.startswith('op://'):
cmd = ['op', 'read', ref] raise AnsibleError(f"1Password reference must start with 'op://', got: {term}")
display.vvv(f"Executing command with reference: {' '.join(cmd)}")
cmd = ['op', 'read', term]
display.vvv(f"Executing command: {' '.join(cmd)}")
try: try:
result = subprocess.run( process = subprocess.run(
cmd, cmd,
capture_output=True, capture_output=True,
text=True, text=True,
check=True check=True
) )
output = result.stdout.strip() output = process.stdout.strip()
display.vvv(f"1Password output for ref '{ref}': '{output}'") display.vvv(f"1Password output for '{term}': '{output}'")
if not output: if not output:
display.warning(f"1Password returned empty output for ref '{ref}'") display.warning(f"1Password returned empty output for '{term}'")
return [output] result.append(output)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
error_msg = e.stderr.strip() error_msg = e.stderr.strip()
display.warning(f"Error executing 1Password CLI: {error_msg}") display.warning(f"Error executing 1Password CLI: {error_msg}")
display.warning(f"Command used: {' '.join(cmd)}") display.warning(f"Command used: {' '.join(cmd)}")
if "not found" in error_msg: if "not found" in error_msg:
return [f"Secret referenced by '{ref}' not found in 1Password"] raise AnsibleError(f"Secret referenced by '{term}' not found in 1Password")
raise AnsibleError(f"Error fetching from 1Password: {error_msg}") raise AnsibleError(f"Error fetching from 1Password: {error_msg}")
# If no ref is provided, fall back to the original behavior return result
if len(terms) != 1:
raise AnsibleError("onepassword lookup expects exactly one argument when not using ref parameter")
item = terms[0]
field = kwargs.get('field', 'password')
vault = kwargs.get('vault', '')
reveal = kwargs.get('reveal', True)
cmd = ['op', 'item', 'get', item, '--field', field]
# Add vault parameter if specified
if vault:
cmd.extend(['--vault', vault])
# Add reveal flag for concealed fields
if reveal and field.lower() in ['password', 'secret', 'token', 'key']:
cmd.append('--reveal')
display.vvv(f"Executing command: {' '.join(cmd)}")
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True
)
return [result.stdout.strip()]
except subprocess.CalledProcessError as e:
error_msg = e.stderr.strip()
display.warning(f"Error executing 1Password CLI: {error_msg}")
display.warning(f"Command used: {' '.join(cmd)}")
if "not found" in error_msg:
return [f"Secret '{item}' not found in 1Password"]
raise AnsibleError(f"Error fetching from 1Password: {error_msg}")

View File

@@ -4,7 +4,7 @@ services:
image: ghcr.io/tailscale/golink:main image: ghcr.io/tailscale/golink:main
user: root user: root
environment: environment:
- TS_AUTHKEY={{ lookup('onepassword', '4gsgavajnxfpcrjvbkqhoc4drm', field='TS_AUTHKEY', vault='j7nmhqlsjmp2r6umly5t75hzb4') }} - TS_AUTHKEY={{ lookup('onepassword', "op://j7nmhqlsjmp2r6umly5t75hzb4/GoLink/TS_AUTHKEY") }}
volumes: volumes:
- {{ golink_data_dir }}:/home/nonroot - {{ golink_data_dir }}:/home/nonroot
restart: "unless-stopped" restart: "unless-stopped"

View File

@@ -7,6 +7,6 @@ NEXTAUTH_URL=http://localhost:3000
DATA_DIR=/data DATA_DIR=/data
NEXTAUTH_SECRET="{{ lookup('onepassword', ref='op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/NEXTAUTH_SECRET') }}" NEXTAUTH_SECRET="{{ lookup('onepassword', 'op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/NEXTAUTH_SECRET') }}"
MEILI_MASTER_KEY="{{ lookup('onepassword', ref='op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/MEILI_MASTER_KEY') }}" MEILI_MASTER_KEY="{{ lookup('onepassword', 'op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/MEILI_MASTER_KEY') }}"
OPENAI_API_KEY="{{ lookup('onepassword', ref='op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/OPENAI_API_KEY') }}" OPENAI_API_KEY="{{ lookup('onepassword', 'op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/OPENAI_API_KEY') }}"

View File

@@ -6,17 +6,16 @@
vars: vars:
hoarder_data_dir: /mnt/storage-box/services/hoarder hoarder_data_dir: /mnt/storage-box/services/hoarder
tasks: tasks:
- name: Test lookup with ref parameter - name: Test lookup with direct reference
ansible.builtin.debug: ansible.builtin.debug:
msg: "{{ lookup('onepassword', ref='op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/OPENAI_API_KEY') }}" msg: "{{ lookup('onepassword', 'op://j7nmhqlsjmp2r6umly5t75hzb4/Hoarder/OPENAI_API_KEY') }}"
- name: Template with lookup - name: Template with lookup
ansible.builtin.template: ansible.builtin.template:
src: ../tasks/servers/services/hoarder/docker-compose.yml.j2 src: ../tasks/servers/services/hoarder/dotenv.j2
dest: /tmp/docker-compose.yml dest: /tmp/.env
register: op_direct register: op_direct
- name: Print out the templated file - name: Print out the templated file
ansible.builtin.debug: ansible.builtin.debug:
msg: "{{ lookup('file', '/tmp/docker-compose.yml') }}" msg: "{{ lookup('file', '/tmp/.env') }}"